sqlite3.c revision 269851
1/******************************************************************************
2** This file is an amalgamation of many separate C source files from SQLite
3** version 3.8.5.  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#ifndef SQLITE_API
26# define SQLITE_API
27#endif
28/************** Begin file sqliteInt.h ***************************************/
29/*
30** 2001 September 15
31**
32** The author disclaims copyright to this source code.  In place of
33** a legal notice, here is a blessing:
34**
35**    May you do good and not evil.
36**    May you find forgiveness for yourself and forgive others.
37**    May you share freely, never taking more than you give.
38**
39*************************************************************************
40** Internal interface definitions for SQLite.
41**
42*/
43#ifndef _SQLITEINT_H_
44#define _SQLITEINT_H_
45
46/*
47** These #defines should enable >2GB file support on POSIX if the
48** underlying operating system supports it.  If the OS lacks
49** large file support, or if the OS is windows, these should be no-ops.
50**
51** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
52** system #includes.  Hence, this block of code must be the very first
53** code in all source files.
54**
55** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
56** on the compiler command line.  This is necessary if you are compiling
57** on a recent machine (ex: Red Hat 7.2) but you want your code to work
58** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
59** without this option, LFS is enable.  But LFS does not exist in the kernel
60** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
61** portability you should omit LFS.
62**
63** The previous paragraph was written in 2005.  (This paragraph is written
64** on 2008-11-28.) These days, all Linux kernels support large files, so
65** you should probably leave LFS enabled.  But some embedded platforms might
66** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
67**
68** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
69*/
70#ifndef SQLITE_DISABLE_LFS
71# define _LARGE_FILE       1
72# ifndef _FILE_OFFSET_BITS
73#   define _FILE_OFFSET_BITS 64
74# endif
75# define _LARGEFILE_SOURCE 1
76#endif
77
78/*
79** For MinGW, check to see if we can include the header file containing its
80** version information, among other things.  Normally, this internal MinGW
81** header file would [only] be included automatically by other MinGW header
82** files; however, the contained version information is now required by this
83** header file to work around binary compatibility issues (see below) and
84** this is the only known way to reliably obtain it.  This entire #if block
85** would be completely unnecessary if there was any other way of detecting
86** MinGW via their preprocessor (e.g. if they customized their GCC to define
87** some MinGW-specific macros).  When compiling for MinGW, either the
88** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
89** defined; otherwise, detection of conditions specific to MinGW will be
90** disabled.
91*/
92#if defined(_HAVE_MINGW_H)
93# include "mingw.h"
94#elif defined(_HAVE__MINGW_H)
95# include "_mingw.h"
96#endif
97
98/*
99** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
100** define is required to maintain binary compatibility with the MSVC runtime
101** library in use (e.g. for Windows XP).
102*/
103#if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
104    defined(_WIN32) && !defined(_WIN64) && \
105    defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
106    defined(__MSVCRT__)
107# define _USE_32BIT_TIME_T
108#endif
109
110/* The public SQLite interface.  The _FILE_OFFSET_BITS macro must appear
111** first in QNX.  Also, the _USE_32BIT_TIME_T macro must appear first for
112** MinGW.
113*/
114/************** Include sqlite3.h in the middle of sqliteInt.h ***************/
115/************** Begin file sqlite3.h *****************************************/
116/*
117** 2001 September 15
118**
119** The author disclaims copyright to this source code.  In place of
120** a legal notice, here is a blessing:
121**
122**    May you do good and not evil.
123**    May you find forgiveness for yourself and forgive others.
124**    May you share freely, never taking more than you give.
125**
126*************************************************************************
127** This header file defines the interface that the SQLite library
128** presents to client programs.  If a C-function, structure, datatype,
129** or constant definition does not appear in this file, then it is
130** not a published API of SQLite, is subject to change without
131** notice, and should not be referenced by programs that use SQLite.
132**
133** Some of the definitions that are in this file are marked as
134** "experimental".  Experimental interfaces are normally new
135** features recently added to SQLite.  We do not anticipate changes
136** to experimental interfaces but reserve the right to make minor changes
137** if experience from use "in the wild" suggest such changes are prudent.
138**
139** The official C-language API documentation for SQLite is derived
140** from comments in this file.  This file is the authoritative source
141** on how SQLite interfaces are suppose to operate.
142**
143** The name of this file under configuration management is "sqlite.h.in".
144** The makefile makes some minor changes to this file (such as inserting
145** the version number) and changes its name to "sqlite3.h" as
146** part of the build process.
147*/
148#ifndef _SQLITE3_H_
149#define _SQLITE3_H_
150#include <stdarg.h>     /* Needed for the definition of va_list */
151
152/*
153** Make sure we can call this stuff from C++.
154*/
155#if 0
156extern "C" {
157#endif
158
159
160/*
161** Add the ability to override 'extern'
162*/
163#ifndef SQLITE_EXTERN
164# define SQLITE_EXTERN extern
165#endif
166
167#ifndef SQLITE_API
168# define SQLITE_API
169#endif
170
171
172/*
173** These no-op macros are used in front of interfaces to mark those
174** interfaces as either deprecated or experimental.  New applications
175** should not use deprecated interfaces - they are support for backwards
176** compatibility only.  Application writers should be aware that
177** experimental interfaces are subject to change in point releases.
178**
179** These macros used to resolve to various kinds of compiler magic that
180** would generate warning messages when they were used.  But that
181** compiler magic ended up generating such a flurry of bug reports
182** that we have taken it all out and gone back to using simple
183** noop macros.
184*/
185#define SQLITE_DEPRECATED
186#define SQLITE_EXPERIMENTAL
187
188/*
189** Ensure these symbols were not defined by some previous header file.
190*/
191#ifdef SQLITE_VERSION
192# undef SQLITE_VERSION
193#endif
194#ifdef SQLITE_VERSION_NUMBER
195# undef SQLITE_VERSION_NUMBER
196#endif
197
198/*
199** CAPI3REF: Compile-Time Library Version Numbers
200**
201** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
202** evaluates to a string literal that is the SQLite version in the
203** format "X.Y.Z" where X is the major version number (always 3 for
204** SQLite3) and Y is the minor version number and Z is the release number.)^
205** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
206** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
207** numbers used in [SQLITE_VERSION].)^
208** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
209** be larger than the release from which it is derived.  Either Y will
210** be held constant and Z will be incremented or else Y will be incremented
211** and Z will be reset to zero.
212**
213** Since version 3.6.18, SQLite source code has been stored in the
214** <a href="http://www.fossil-scm.org/">Fossil configuration management
215** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
216** a string which identifies a particular check-in of SQLite
217** within its configuration management system.  ^The SQLITE_SOURCE_ID
218** string contains the date and time of the check-in (UTC) and an SHA1
219** hash of the entire source tree.
220**
221** See also: [sqlite3_libversion()],
222** [sqlite3_libversion_number()], [sqlite3_sourceid()],
223** [sqlite_version()] and [sqlite_source_id()].
224*/
225#define SQLITE_VERSION        "3.8.5"
226#define SQLITE_VERSION_NUMBER 3008005
227#define SQLITE_SOURCE_ID      "2014-06-04 14:06:34 b1ed4f2a34ba66c29b130f8d13e9092758019212"
228
229/*
230** CAPI3REF: Run-Time Library Version Numbers
231** KEYWORDS: sqlite3_version, sqlite3_sourceid
232**
233** These interfaces provide the same information as the [SQLITE_VERSION],
234** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
235** but are associated with the library instead of the header file.  ^(Cautious
236** programmers might include assert() statements in their application to
237** verify that values returned by these interfaces match the macros in
238** the header, and thus insure that the application is
239** compiled with matching library and header files.
240**
241** <blockquote><pre>
242** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
243** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
244** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
245** </pre></blockquote>)^
246**
247** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
248** macro.  ^The sqlite3_libversion() function returns a pointer to the
249** to the sqlite3_version[] string constant.  The sqlite3_libversion()
250** function is provided for use in DLLs since DLL users usually do not have
251** direct access to string constants within the DLL.  ^The
252** sqlite3_libversion_number() function returns an integer equal to
253** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns
254** a pointer to a string constant whose value is the same as the
255** [SQLITE_SOURCE_ID] C preprocessor macro.
256**
257** See also: [sqlite_version()] and [sqlite_source_id()].
258*/
259SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
260SQLITE_API const char *sqlite3_libversion(void);
261SQLITE_API const char *sqlite3_sourceid(void);
262SQLITE_API int sqlite3_libversion_number(void);
263
264/*
265** CAPI3REF: Run-Time Library Compilation Options Diagnostics
266**
267** ^The sqlite3_compileoption_used() function returns 0 or 1
268** indicating whether the specified option was defined at
269** compile time.  ^The SQLITE_ prefix may be omitted from the
270** option name passed to sqlite3_compileoption_used().
271**
272** ^The sqlite3_compileoption_get() function allows iterating
273** over the list of options that were defined at compile time by
274** returning the N-th compile time option string.  ^If N is out of range,
275** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_
276** prefix is omitted from any strings returned by
277** sqlite3_compileoption_get().
278**
279** ^Support for the diagnostic functions sqlite3_compileoption_used()
280** and sqlite3_compileoption_get() may be omitted by specifying the
281** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
282**
283** See also: SQL functions [sqlite_compileoption_used()] and
284** [sqlite_compileoption_get()] and the [compile_options pragma].
285*/
286#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
287SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
288SQLITE_API const char *sqlite3_compileoption_get(int N);
289#endif
290
291/*
292** CAPI3REF: Test To See If The Library Is Threadsafe
293**
294** ^The sqlite3_threadsafe() function returns zero if and only if
295** SQLite was compiled with mutexing code omitted due to the
296** [SQLITE_THREADSAFE] compile-time option being set to 0.
297**
298** SQLite can be compiled with or without mutexes.  When
299** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
300** are enabled and SQLite is threadsafe.  When the
301** [SQLITE_THREADSAFE] macro is 0,
302** the mutexes are omitted.  Without the mutexes, it is not safe
303** to use SQLite concurrently from more than one thread.
304**
305** Enabling mutexes incurs a measurable performance penalty.
306** So if speed is of utmost importance, it makes sense to disable
307** the mutexes.  But for maximum safety, mutexes should be enabled.
308** ^The default behavior is for mutexes to be enabled.
309**
310** This interface can be used by an application to make sure that the
311** version of SQLite that it is linking against was compiled with
312** the desired setting of the [SQLITE_THREADSAFE] macro.
313**
314** This interface only reports on the compile-time mutex setting
315** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
316** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
317** can be fully or partially disabled using a call to [sqlite3_config()]
318** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
319** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
320** sqlite3_threadsafe() function shows only the compile-time setting of
321** thread safety, not any run-time changes to that setting made by
322** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
323** is unchanged by calls to sqlite3_config().)^
324**
325** See the [threading mode] documentation for additional information.
326*/
327SQLITE_API int sqlite3_threadsafe(void);
328
329/*
330** CAPI3REF: Database Connection Handle
331** KEYWORDS: {database connection} {database connections}
332**
333** Each open SQLite database is represented by a pointer to an instance of
334** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
335** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
336** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
337** and [sqlite3_close_v2()] are its destructors.  There are many other
338** interfaces (such as
339** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
340** [sqlite3_busy_timeout()] to name but three) that are methods on an
341** sqlite3 object.
342*/
343typedef struct sqlite3 sqlite3;
344
345/*
346** CAPI3REF: 64-Bit Integer Types
347** KEYWORDS: sqlite_int64 sqlite_uint64
348**
349** Because there is no cross-platform way to specify 64-bit integer types
350** SQLite includes typedefs for 64-bit signed and unsigned integers.
351**
352** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
353** The sqlite_int64 and sqlite_uint64 types are supported for backwards
354** compatibility only.
355**
356** ^The sqlite3_int64 and sqlite_int64 types can store integer values
357** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
358** sqlite3_uint64 and sqlite_uint64 types can store integer values
359** between 0 and +18446744073709551615 inclusive.
360*/
361#ifdef SQLITE_INT64_TYPE
362  typedef SQLITE_INT64_TYPE sqlite_int64;
363  typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
364#elif defined(_MSC_VER) || defined(__BORLANDC__)
365  typedef __int64 sqlite_int64;
366  typedef unsigned __int64 sqlite_uint64;
367#else
368  typedef long long int sqlite_int64;
369  typedef unsigned long long int sqlite_uint64;
370#endif
371typedef sqlite_int64 sqlite3_int64;
372typedef sqlite_uint64 sqlite3_uint64;
373
374/*
375** If compiling for a processor that lacks floating point support,
376** substitute integer for floating-point.
377*/
378#ifdef SQLITE_OMIT_FLOATING_POINT
379# define double sqlite3_int64
380#endif
381
382/*
383** CAPI3REF: Closing A Database Connection
384**
385** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
386** for the [sqlite3] object.
387** ^Calls to sqlite3_close() and sqlite3_close_v2() return SQLITE_OK if
388** the [sqlite3] object is successfully destroyed and all associated
389** resources are deallocated.
390**
391** ^If the database connection is associated with unfinalized prepared
392** statements or unfinished sqlite3_backup objects then sqlite3_close()
393** will leave the database connection open and return [SQLITE_BUSY].
394** ^If sqlite3_close_v2() is called with unfinalized prepared statements
395** and unfinished sqlite3_backups, then the database connection becomes
396** an unusable "zombie" which will automatically be deallocated when the
397** last prepared statement is finalized or the last sqlite3_backup is
398** finished.  The sqlite3_close_v2() interface is intended for use with
399** host languages that are garbage collected, and where the order in which
400** destructors are called is arbitrary.
401**
402** Applications should [sqlite3_finalize | finalize] all [prepared statements],
403** [sqlite3_blob_close | close] all [BLOB handles], and
404** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
405** with the [sqlite3] object prior to attempting to close the object.  ^If
406** sqlite3_close_v2() is called on a [database connection] that still has
407** outstanding [prepared statements], [BLOB handles], and/or
408** [sqlite3_backup] objects then it returns SQLITE_OK but the deallocation
409** of resources is deferred until all [prepared statements], [BLOB handles],
410** and [sqlite3_backup] objects are also destroyed.
411**
412** ^If an [sqlite3] object is destroyed while a transaction is open,
413** the transaction is automatically rolled back.
414**
415** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
416** must be either a NULL
417** pointer or an [sqlite3] object pointer obtained
418** from [sqlite3_open()], [sqlite3_open16()], or
419** [sqlite3_open_v2()], and not previously closed.
420** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
421** argument is a harmless no-op.
422*/
423SQLITE_API int sqlite3_close(sqlite3*);
424SQLITE_API int sqlite3_close_v2(sqlite3*);
425
426/*
427** The type for a callback function.
428** This is legacy and deprecated.  It is included for historical
429** compatibility and is not documented.
430*/
431typedef int (*sqlite3_callback)(void*,int,char**, char**);
432
433/*
434** CAPI3REF: One-Step Query Execution Interface
435**
436** The sqlite3_exec() interface is a convenience wrapper around
437** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
438** that allows an application to run multiple statements of SQL
439** without having to use a lot of C code.
440**
441** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
442** semicolon-separate SQL statements passed into its 2nd argument,
443** in the context of the [database connection] passed in as its 1st
444** argument.  ^If the callback function of the 3rd argument to
445** sqlite3_exec() is not NULL, then it is invoked for each result row
446** coming out of the evaluated SQL statements.  ^The 4th argument to
447** sqlite3_exec() is relayed through to the 1st argument of each
448** callback invocation.  ^If the callback pointer to sqlite3_exec()
449** is NULL, then no callback is ever invoked and result rows are
450** ignored.
451**
452** ^If an error occurs while evaluating the SQL statements passed into
453** sqlite3_exec(), then execution of the current statement stops and
454** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
455** is not NULL then any error message is written into memory obtained
456** from [sqlite3_malloc()] and passed back through the 5th parameter.
457** To avoid memory leaks, the application should invoke [sqlite3_free()]
458** on error message strings returned through the 5th parameter of
459** of sqlite3_exec() after the error message string is no longer needed.
460** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
461** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
462** NULL before returning.
463**
464** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
465** routine returns SQLITE_ABORT without invoking the callback again and
466** without running any subsequent SQL statements.
467**
468** ^The 2nd argument to the sqlite3_exec() callback function is the
469** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
470** callback is an array of pointers to strings obtained as if from
471** [sqlite3_column_text()], one for each column.  ^If an element of a
472** result row is NULL then the corresponding string pointer for the
473** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
474** sqlite3_exec() callback is an array of pointers to strings where each
475** entry represents the name of corresponding result column as obtained
476** from [sqlite3_column_name()].
477**
478** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
479** to an empty string, or a pointer that contains only whitespace and/or
480** SQL comments, then no SQL statements are evaluated and the database
481** is not changed.
482**
483** Restrictions:
484**
485** <ul>
486** <li> The application must insure that the 1st parameter to sqlite3_exec()
487**      is a valid and open [database connection].
488** <li> The application must not close the [database connection] specified by
489**      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
490** <li> The application must not modify the SQL statement text passed into
491**      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
492** </ul>
493*/
494SQLITE_API int sqlite3_exec(
495  sqlite3*,                                  /* An open database */
496  const char *sql,                           /* SQL to be evaluated */
497  int (*callback)(void*,int,char**,char**),  /* Callback function */
498  void *,                                    /* 1st argument to callback */
499  char **errmsg                              /* Error msg written here */
500);
501
502/*
503** CAPI3REF: Result Codes
504** KEYWORDS: SQLITE_OK {error code} {error codes}
505** KEYWORDS: {result code} {result codes}
506**
507** Many SQLite functions return an integer result code from the set shown
508** here in order to indicate success or failure.
509**
510** New error codes may be added in future versions of SQLite.
511**
512** See also: [SQLITE_IOERR_READ | extended result codes],
513** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes].
514*/
515#define SQLITE_OK           0   /* Successful result */
516/* beginning-of-error-codes */
517#define SQLITE_ERROR        1   /* SQL error or missing database */
518#define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
519#define SQLITE_PERM         3   /* Access permission denied */
520#define SQLITE_ABORT        4   /* Callback routine requested an abort */
521#define SQLITE_BUSY         5   /* The database file is locked */
522#define SQLITE_LOCKED       6   /* A table in the database is locked */
523#define SQLITE_NOMEM        7   /* A malloc() failed */
524#define SQLITE_READONLY     8   /* Attempt to write a readonly database */
525#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
526#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
527#define SQLITE_CORRUPT     11   /* The database disk image is malformed */
528#define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
529#define SQLITE_FULL        13   /* Insertion failed because database is full */
530#define SQLITE_CANTOPEN    14   /* Unable to open the database file */
531#define SQLITE_PROTOCOL    15   /* Database lock protocol error */
532#define SQLITE_EMPTY       16   /* Database is empty */
533#define SQLITE_SCHEMA      17   /* The database schema changed */
534#define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
535#define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
536#define SQLITE_MISMATCH    20   /* Data type mismatch */
537#define SQLITE_MISUSE      21   /* Library used incorrectly */
538#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
539#define SQLITE_AUTH        23   /* Authorization denied */
540#define SQLITE_FORMAT      24   /* Auxiliary database format error */
541#define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
542#define SQLITE_NOTADB      26   /* File opened that is not a database file */
543#define SQLITE_NOTICE      27   /* Notifications from sqlite3_log() */
544#define SQLITE_WARNING     28   /* Warnings from sqlite3_log() */
545#define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
546#define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
547/* end-of-error-codes */
548
549/*
550** CAPI3REF: Extended Result Codes
551** KEYWORDS: {extended error code} {extended error codes}
552** KEYWORDS: {extended result code} {extended result codes}
553**
554** In its default configuration, SQLite API routines return one of 26 integer
555** [SQLITE_OK | result codes].  However, experience has shown that many of
556** these result codes are too coarse-grained.  They do not provide as
557** much information about problems as programmers might like.  In an effort to
558** address this, newer versions of SQLite (version 3.3.8 and later) include
559** support for additional result codes that provide more detailed information
560** about errors. The extended result codes are enabled or disabled
561** on a per database connection basis using the
562** [sqlite3_extended_result_codes()] API.
563**
564** Some of the available extended result codes are listed here.
565** One may expect the number of extended result codes will increase
566** over time.  Software that uses extended result codes should expect
567** to see new result codes in future releases of SQLite.
568**
569** The SQLITE_OK result code will never be extended.  It will always
570** be exactly zero.
571*/
572#define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
573#define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
574#define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
575#define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
576#define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
577#define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
578#define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
579#define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
580#define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
581#define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
582#define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
583#define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
584#define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
585#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
586#define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
587#define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
588#define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
589#define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
590#define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
591#define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
592#define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))
593#define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))
594#define SQLITE_IOERR_DELETE_NOENT      (SQLITE_IOERR | (23<<8))
595#define SQLITE_IOERR_MMAP              (SQLITE_IOERR | (24<<8))
596#define SQLITE_IOERR_GETTEMPPATH       (SQLITE_IOERR | (25<<8))
597#define SQLITE_IOERR_CONVPATH          (SQLITE_IOERR | (26<<8))
598#define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
599#define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
600#define SQLITE_BUSY_SNAPSHOT           (SQLITE_BUSY   |  (2<<8))
601#define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
602#define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
603#define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))
604#define SQLITE_CANTOPEN_CONVPATH       (SQLITE_CANTOPEN | (4<<8))
605#define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
606#define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
607#define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
608#define SQLITE_READONLY_ROLLBACK       (SQLITE_READONLY | (3<<8))
609#define SQLITE_READONLY_DBMOVED        (SQLITE_READONLY | (4<<8))
610#define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))
611#define SQLITE_CONSTRAINT_CHECK        (SQLITE_CONSTRAINT | (1<<8))
612#define SQLITE_CONSTRAINT_COMMITHOOK   (SQLITE_CONSTRAINT | (2<<8))
613#define SQLITE_CONSTRAINT_FOREIGNKEY   (SQLITE_CONSTRAINT | (3<<8))
614#define SQLITE_CONSTRAINT_FUNCTION     (SQLITE_CONSTRAINT | (4<<8))
615#define SQLITE_CONSTRAINT_NOTNULL      (SQLITE_CONSTRAINT | (5<<8))
616#define SQLITE_CONSTRAINT_PRIMARYKEY   (SQLITE_CONSTRAINT | (6<<8))
617#define SQLITE_CONSTRAINT_TRIGGER      (SQLITE_CONSTRAINT | (7<<8))
618#define SQLITE_CONSTRAINT_UNIQUE       (SQLITE_CONSTRAINT | (8<<8))
619#define SQLITE_CONSTRAINT_VTAB         (SQLITE_CONSTRAINT | (9<<8))
620#define SQLITE_CONSTRAINT_ROWID        (SQLITE_CONSTRAINT |(10<<8))
621#define SQLITE_NOTICE_RECOVER_WAL      (SQLITE_NOTICE | (1<<8))
622#define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
623#define SQLITE_WARNING_AUTOINDEX       (SQLITE_WARNING | (1<<8))
624
625/*
626** CAPI3REF: Flags For File Open Operations
627**
628** These bit values are intended for use in the
629** 3rd parameter to the [sqlite3_open_v2()] interface and
630** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
631*/
632#define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
633#define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
634#define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
635#define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
636#define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
637#define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
638#define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */
639#define SQLITE_OPEN_MEMORY           0x00000080  /* Ok for sqlite3_open_v2() */
640#define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
641#define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
642#define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
643#define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
644#define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
645#define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
646#define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
647#define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
648#define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
649#define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
650#define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
651#define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
652
653/* Reserved:                         0x00F00000 */
654
655/*
656** CAPI3REF: Device Characteristics
657**
658** The xDeviceCharacteristics method of the [sqlite3_io_methods]
659** object returns an integer which is a vector of these
660** bit values expressing I/O characteristics of the mass storage
661** device that holds the file that the [sqlite3_io_methods]
662** refers to.
663**
664** The SQLITE_IOCAP_ATOMIC property means that all writes of
665** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
666** mean that writes of blocks that are nnn bytes in size and
667** are aligned to an address which is an integer multiple of
668** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
669** that when data is appended to a file, the data is appended
670** first then the size of the file is extended, never the other
671** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
672** information is written to disk in the same order as calls
673** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
674** after reboot following a crash or power loss, the only bytes in a
675** file that were written at the application level might have changed
676** and that adjacent bytes, even bytes within the same sector are
677** guaranteed to be unchanged.  The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
678** flag indicate that a file cannot be deleted when open.  The
679** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
680** read-only media and cannot be changed even by processes with
681** elevated privileges.
682*/
683#define SQLITE_IOCAP_ATOMIC                 0x00000001
684#define SQLITE_IOCAP_ATOMIC512              0x00000002
685#define SQLITE_IOCAP_ATOMIC1K               0x00000004
686#define SQLITE_IOCAP_ATOMIC2K               0x00000008
687#define SQLITE_IOCAP_ATOMIC4K               0x00000010
688#define SQLITE_IOCAP_ATOMIC8K               0x00000020
689#define SQLITE_IOCAP_ATOMIC16K              0x00000040
690#define SQLITE_IOCAP_ATOMIC32K              0x00000080
691#define SQLITE_IOCAP_ATOMIC64K              0x00000100
692#define SQLITE_IOCAP_SAFE_APPEND            0x00000200
693#define SQLITE_IOCAP_SEQUENTIAL             0x00000400
694#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
695#define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000
696#define SQLITE_IOCAP_IMMUTABLE              0x00002000
697
698/*
699** CAPI3REF: File Locking Levels
700**
701** SQLite uses one of these integer values as the second
702** argument to calls it makes to the xLock() and xUnlock() methods
703** of an [sqlite3_io_methods] object.
704*/
705#define SQLITE_LOCK_NONE          0
706#define SQLITE_LOCK_SHARED        1
707#define SQLITE_LOCK_RESERVED      2
708#define SQLITE_LOCK_PENDING       3
709#define SQLITE_LOCK_EXCLUSIVE     4
710
711/*
712** CAPI3REF: Synchronization Type Flags
713**
714** When SQLite invokes the xSync() method of an
715** [sqlite3_io_methods] object it uses a combination of
716** these integer values as the second argument.
717**
718** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
719** sync operation only needs to flush data to mass storage.  Inode
720** information need not be flushed. If the lower four bits of the flag
721** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
722** If the lower four bits equal SQLITE_SYNC_FULL, that means
723** to use Mac OS X style fullsync instead of fsync().
724**
725** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
726** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
727** settings.  The [synchronous pragma] determines when calls to the
728** xSync VFS method occur and applies uniformly across all platforms.
729** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
730** energetic or rigorous or forceful the sync operations are and
731** only make a difference on Mac OSX for the default SQLite code.
732** (Third-party VFS implementations might also make the distinction
733** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
734** operating systems natively supported by SQLite, only Mac OSX
735** cares about the difference.)
736*/
737#define SQLITE_SYNC_NORMAL        0x00002
738#define SQLITE_SYNC_FULL          0x00003
739#define SQLITE_SYNC_DATAONLY      0x00010
740
741/*
742** CAPI3REF: OS Interface Open File Handle
743**
744** An [sqlite3_file] object represents an open file in the
745** [sqlite3_vfs | OS interface layer].  Individual OS interface
746** implementations will
747** want to subclass this object by appending additional fields
748** for their own use.  The pMethods entry is a pointer to an
749** [sqlite3_io_methods] object that defines methods for performing
750** I/O operations on the open file.
751*/
752typedef struct sqlite3_file sqlite3_file;
753struct sqlite3_file {
754  const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
755};
756
757/*
758** CAPI3REF: OS Interface File Virtual Methods Object
759**
760** Every file opened by the [sqlite3_vfs.xOpen] method populates an
761** [sqlite3_file] object (or, more commonly, a subclass of the
762** [sqlite3_file] object) with a pointer to an instance of this object.
763** This object defines the methods used to perform various operations
764** against the open file represented by the [sqlite3_file] object.
765**
766** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
767** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
768** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The
769** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
770** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
771** to NULL.
772**
773** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
774** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
775** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
776** flag may be ORed in to indicate that only the data of the file
777** and not its inode needs to be synced.
778**
779** The integer values to xLock() and xUnlock() are one of
780** <ul>
781** <li> [SQLITE_LOCK_NONE],
782** <li> [SQLITE_LOCK_SHARED],
783** <li> [SQLITE_LOCK_RESERVED],
784** <li> [SQLITE_LOCK_PENDING], or
785** <li> [SQLITE_LOCK_EXCLUSIVE].
786** </ul>
787** xLock() increases the lock. xUnlock() decreases the lock.
788** The xCheckReservedLock() method checks whether any database connection,
789** either in this process or in some other process, is holding a RESERVED,
790** PENDING, or EXCLUSIVE lock on the file.  It returns true
791** if such a lock exists and false otherwise.
792**
793** The xFileControl() method is a generic interface that allows custom
794** VFS implementations to directly control an open file using the
795** [sqlite3_file_control()] interface.  The second "op" argument is an
796** integer opcode.  The third argument is a generic pointer intended to
797** point to a structure that may contain arguments or space in which to
798** write return values.  Potential uses for xFileControl() might be
799** functions to enable blocking locks with timeouts, to change the
800** locking strategy (for example to use dot-file locks), to inquire
801** about the status of a lock, or to break stale locks.  The SQLite
802** core reserves all opcodes less than 100 for its own use.
803** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
804** Applications that define a custom xFileControl method should use opcodes
805** greater than 100 to avoid conflicts.  VFS implementations should
806** return [SQLITE_NOTFOUND] for file control opcodes that they do not
807** recognize.
808**
809** The xSectorSize() method returns the sector size of the
810** device that underlies the file.  The sector size is the
811** minimum write that can be performed without disturbing
812** other bytes in the file.  The xDeviceCharacteristics()
813** method returns a bit vector describing behaviors of the
814** underlying device:
815**
816** <ul>
817** <li> [SQLITE_IOCAP_ATOMIC]
818** <li> [SQLITE_IOCAP_ATOMIC512]
819** <li> [SQLITE_IOCAP_ATOMIC1K]
820** <li> [SQLITE_IOCAP_ATOMIC2K]
821** <li> [SQLITE_IOCAP_ATOMIC4K]
822** <li> [SQLITE_IOCAP_ATOMIC8K]
823** <li> [SQLITE_IOCAP_ATOMIC16K]
824** <li> [SQLITE_IOCAP_ATOMIC32K]
825** <li> [SQLITE_IOCAP_ATOMIC64K]
826** <li> [SQLITE_IOCAP_SAFE_APPEND]
827** <li> [SQLITE_IOCAP_SEQUENTIAL]
828** </ul>
829**
830** The SQLITE_IOCAP_ATOMIC property means that all writes of
831** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
832** mean that writes of blocks that are nnn bytes in size and
833** are aligned to an address which is an integer multiple of
834** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
835** that when data is appended to a file, the data is appended
836** first then the size of the file is extended, never the other
837** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
838** information is written to disk in the same order as calls
839** to xWrite().
840**
841** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
842** in the unread portions of the buffer with zeros.  A VFS that
843** fails to zero-fill short reads might seem to work.  However,
844** failure to zero-fill short reads will eventually lead to
845** database corruption.
846*/
847typedef struct sqlite3_io_methods sqlite3_io_methods;
848struct sqlite3_io_methods {
849  int iVersion;
850  int (*xClose)(sqlite3_file*);
851  int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
852  int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
853  int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
854  int (*xSync)(sqlite3_file*, int flags);
855  int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
856  int (*xLock)(sqlite3_file*, int);
857  int (*xUnlock)(sqlite3_file*, int);
858  int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
859  int (*xFileControl)(sqlite3_file*, int op, void *pArg);
860  int (*xSectorSize)(sqlite3_file*);
861  int (*xDeviceCharacteristics)(sqlite3_file*);
862  /* Methods above are valid for version 1 */
863  int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
864  int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
865  void (*xShmBarrier)(sqlite3_file*);
866  int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
867  /* Methods above are valid for version 2 */
868  int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
869  int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
870  /* Methods above are valid for version 3 */
871  /* Additional methods may be added in future releases */
872};
873
874/*
875** CAPI3REF: Standard File Control Opcodes
876**
877** These integer constants are opcodes for the xFileControl method
878** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
879** interface.
880**
881** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
882** opcode causes the xFileControl method to write the current state of
883** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
884** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
885** into an integer that the pArg argument points to. This capability
886** is used during testing and only needs to be supported when SQLITE_TEST
887** is defined.
888** <ul>
889** <li>[[SQLITE_FCNTL_SIZE_HINT]]
890** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
891** layer a hint of how large the database file will grow to be during the
892** current transaction.  This hint is not guaranteed to be accurate but it
893** is often close.  The underlying VFS might choose to preallocate database
894** file space based on this hint in order to help writes to the database
895** file run faster.
896**
897** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
898** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
899** extends and truncates the database file in chunks of a size specified
900** by the user. The fourth argument to [sqlite3_file_control()] should
901** point to an integer (type int) containing the new chunk-size to use
902** for the nominated database. Allocating database file space in large
903** chunks (say 1MB at a time), may reduce file-system fragmentation and
904** improve performance on some systems.
905**
906** <li>[[SQLITE_FCNTL_FILE_POINTER]]
907** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
908** to the [sqlite3_file] object associated with a particular database
909** connection.  See the [sqlite3_file_control()] documentation for
910** additional information.
911**
912** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
913** No longer in use.
914**
915** <li>[[SQLITE_FCNTL_SYNC]]
916** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
917** sent to the VFS immediately before the xSync method is invoked on a
918** database file descriptor. Or, if the xSync method is not invoked
919** because the user has configured SQLite with
920** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
921** of the xSync method. In most cases, the pointer argument passed with
922** this file-control is NULL. However, if the database file is being synced
923** as part of a multi-database commit, the argument points to a nul-terminated
924** string containing the transactions master-journal file name. VFSes that
925** do not need this signal should silently ignore this opcode. Applications
926** should not call [sqlite3_file_control()] with this opcode as doing so may
927** disrupt the operation of the specialized VFSes that do require it.
928**
929** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
930** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
931** and sent to the VFS after a transaction has been committed immediately
932** but before the database is unlocked. VFSes that do not need this signal
933** should silently ignore this opcode. Applications should not call
934** [sqlite3_file_control()] with this opcode as doing so may disrupt the
935** operation of the specialized VFSes that do require it.
936**
937** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
938** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
939** retry counts and intervals for certain disk I/O operations for the
940** windows [VFS] in order to provide robustness in the presence of
941** anti-virus programs.  By default, the windows VFS will retry file read,
942** file write, and file delete operations up to 10 times, with a delay
943** of 25 milliseconds before the first retry and with the delay increasing
944** by an additional 25 milliseconds with each subsequent retry.  This
945** opcode allows these two values (10 retries and 25 milliseconds of delay)
946** to be adjusted.  The values are changed for all database connections
947** within the same process.  The argument is a pointer to an array of two
948** integers where the first integer i the new retry count and the second
949** integer is the delay.  If either integer is negative, then the setting
950** is not changed but instead the prior value of that setting is written
951** into the array entry, allowing the current retry settings to be
952** interrogated.  The zDbName parameter is ignored.
953**
954** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
955** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
956** persistent [WAL | Write Ahead Log] setting.  By default, the auxiliary
957** write ahead log and shared memory files used for transaction control
958** are automatically deleted when the latest connection to the database
959** closes.  Setting persistent WAL mode causes those files to persist after
960** close.  Persisting the files is useful when other processes that do not
961** have write permission on the directory containing the database file want
962** to read the database file, as the WAL and shared memory files must exist
963** in order for the database to be readable.  The fourth parameter to
964** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
965** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
966** WAL mode.  If the integer is -1, then it is overwritten with the current
967** WAL persistence setting.
968**
969** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
970** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
971** persistent "powersafe-overwrite" or "PSOW" setting.  The PSOW setting
972** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
973** xDeviceCharacteristics methods. The fourth parameter to
974** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
975** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
976** mode.  If the integer is -1, then it is overwritten with the current
977** zero-damage mode setting.
978**
979** <li>[[SQLITE_FCNTL_OVERWRITE]]
980** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
981** a write transaction to indicate that, unless it is rolled back for some
982** reason, the entire database file will be overwritten by the current
983** transaction. This is used by VACUUM operations.
984**
985** <li>[[SQLITE_FCNTL_VFSNAME]]
986** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
987** all [VFSes] in the VFS stack.  The names are of all VFS shims and the
988** final bottom-level VFS are written into memory obtained from
989** [sqlite3_malloc()] and the result is stored in the char* variable
990** that the fourth parameter of [sqlite3_file_control()] points to.
991** The caller is responsible for freeing the memory when done.  As with
992** all file-control actions, there is no guarantee that this will actually
993** do anything.  Callers should initialize the char* variable to a NULL
994** pointer in case this file-control is not implemented.  This file-control
995** is intended for diagnostic use only.
996**
997** <li>[[SQLITE_FCNTL_PRAGMA]]
998** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
999** file control is sent to the open [sqlite3_file] object corresponding
1000** to the database file to which the pragma statement refers. ^The argument
1001** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
1002** pointers to strings (char**) in which the second element of the array
1003** is the name of the pragma and the third element is the argument to the
1004** pragma or NULL if the pragma has no argument.  ^The handler for an
1005** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
1006** of the char** argument point to a string obtained from [sqlite3_mprintf()]
1007** or the equivalent and that string will become the result of the pragma or
1008** the error message if the pragma fails. ^If the
1009** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
1010** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]
1011** file control returns [SQLITE_OK], then the parser assumes that the
1012** VFS has handled the PRAGMA itself and the parser generates a no-op
1013** prepared statement.  ^If the [SQLITE_FCNTL_PRAGMA] file control returns
1014** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
1015** that the VFS encountered an error while handling the [PRAGMA] and the
1016** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]
1017** file control occurs at the beginning of pragma statement analysis and so
1018** it is able to override built-in [PRAGMA] statements.
1019**
1020** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
1021** ^The [SQLITE_FCNTL_BUSYHANDLER]
1022** file-control may be invoked by SQLite on the database file handle
1023** shortly after it is opened in order to provide a custom VFS with access
1024** to the connections busy-handler callback. The argument is of type (void **)
1025** - an array of two (void *) values. The first (void *) actually points
1026** to a function of type (int (*)(void *)). In order to invoke the connections
1027** busy-handler, this function should be invoked with the second (void *) in
1028** the array as the only argument. If it returns non-zero, then the operation
1029** should be retried. If it returns zero, the custom VFS should abandon the
1030** current operation.
1031**
1032** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
1033** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
1034** to have SQLite generate a
1035** temporary filename using the same algorithm that is followed to generate
1036** temporary filenames for TEMP tables and other internal uses.  The
1037** argument should be a char** which will be filled with the filename
1038** written into memory obtained from [sqlite3_malloc()].  The caller should
1039** invoke [sqlite3_free()] on the result to avoid a memory leak.
1040**
1041** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
1042** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
1043** maximum number of bytes that will be used for memory-mapped I/O.
1044** The argument is a pointer to a value of type sqlite3_int64 that
1045** is an advisory maximum number of bytes in the file to memory map.  The
1046** pointer is overwritten with the old value.  The limit is not changed if
1047** the value originally pointed to is negative, and so the current limit
1048** can be queried by passing in a pointer to a negative number.  This
1049** file-control is used internally to implement [PRAGMA mmap_size].
1050**
1051** <li>[[SQLITE_FCNTL_TRACE]]
1052** The [SQLITE_FCNTL_TRACE] file control provides advisory information
1053** to the VFS about what the higher layers of the SQLite stack are doing.
1054** This file control is used by some VFS activity tracing [shims].
1055** The argument is a zero-terminated string.  Higher layers in the
1056** SQLite stack may generate instances of this file control if
1057** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
1058**
1059** <li>[[SQLITE_FCNTL_HAS_MOVED]]
1060** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
1061** pointer to an integer and it writes a boolean into that integer depending
1062** on whether or not the file has been renamed, moved, or deleted since it
1063** was first opened.
1064**
1065** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
1066** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging.  This
1067** opcode causes the xFileControl method to swap the file handle with the one
1068** pointed to by the pArg argument.  This capability is used during testing
1069** and only needs to be supported when SQLITE_TEST is defined.
1070**
1071** </ul>
1072*/
1073#define SQLITE_FCNTL_LOCKSTATE               1
1074#define SQLITE_GET_LOCKPROXYFILE             2
1075#define SQLITE_SET_LOCKPROXYFILE             3
1076#define SQLITE_LAST_ERRNO                    4
1077#define SQLITE_FCNTL_SIZE_HINT               5
1078#define SQLITE_FCNTL_CHUNK_SIZE              6
1079#define SQLITE_FCNTL_FILE_POINTER            7
1080#define SQLITE_FCNTL_SYNC_OMITTED            8
1081#define SQLITE_FCNTL_WIN32_AV_RETRY          9
1082#define SQLITE_FCNTL_PERSIST_WAL            10
1083#define SQLITE_FCNTL_OVERWRITE              11
1084#define SQLITE_FCNTL_VFSNAME                12
1085#define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13
1086#define SQLITE_FCNTL_PRAGMA                 14
1087#define SQLITE_FCNTL_BUSYHANDLER            15
1088#define SQLITE_FCNTL_TEMPFILENAME           16
1089#define SQLITE_FCNTL_MMAP_SIZE              18
1090#define SQLITE_FCNTL_TRACE                  19
1091#define SQLITE_FCNTL_HAS_MOVED              20
1092#define SQLITE_FCNTL_SYNC                   21
1093#define SQLITE_FCNTL_COMMIT_PHASETWO        22
1094#define SQLITE_FCNTL_WIN32_SET_HANDLE       23
1095
1096/*
1097** CAPI3REF: Mutex Handle
1098**
1099** The mutex module within SQLite defines [sqlite3_mutex] to be an
1100** abstract type for a mutex object.  The SQLite core never looks
1101** at the internal representation of an [sqlite3_mutex].  It only
1102** deals with pointers to the [sqlite3_mutex] object.
1103**
1104** Mutexes are created using [sqlite3_mutex_alloc()].
1105*/
1106typedef struct sqlite3_mutex sqlite3_mutex;
1107
1108/*
1109** CAPI3REF: OS Interface Object
1110**
1111** An instance of the sqlite3_vfs object defines the interface between
1112** the SQLite core and the underlying operating system.  The "vfs"
1113** in the name of the object stands for "virtual file system".  See
1114** the [VFS | VFS documentation] for further information.
1115**
1116** The value of the iVersion field is initially 1 but may be larger in
1117** future versions of SQLite.  Additional fields may be appended to this
1118** object when the iVersion value is increased.  Note that the structure
1119** of the sqlite3_vfs object changes in the transaction between
1120** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1121** modified.
1122**
1123** The szOsFile field is the size of the subclassed [sqlite3_file]
1124** structure used by this VFS.  mxPathname is the maximum length of
1125** a pathname in this VFS.
1126**
1127** Registered sqlite3_vfs objects are kept on a linked list formed by
1128** the pNext pointer.  The [sqlite3_vfs_register()]
1129** and [sqlite3_vfs_unregister()] interfaces manage this list
1130** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1131** searches the list.  Neither the application code nor the VFS
1132** implementation should use the pNext pointer.
1133**
1134** The pNext field is the only field in the sqlite3_vfs
1135** structure that SQLite will ever modify.  SQLite will only access
1136** or modify this field while holding a particular static mutex.
1137** The application should never modify anything within the sqlite3_vfs
1138** object once the object has been registered.
1139**
1140** The zName field holds the name of the VFS module.  The name must
1141** be unique across all VFS modules.
1142**
1143** [[sqlite3_vfs.xOpen]]
1144** ^SQLite guarantees that the zFilename parameter to xOpen
1145** is either a NULL pointer or string obtained
1146** from xFullPathname() with an optional suffix added.
1147** ^If a suffix is added to the zFilename parameter, it will
1148** consist of a single "-" character followed by no more than
1149** 11 alphanumeric and/or "-" characters.
1150** ^SQLite further guarantees that
1151** the string will be valid and unchanged until xClose() is
1152** called. Because of the previous sentence,
1153** the [sqlite3_file] can safely store a pointer to the
1154** filename if it needs to remember the filename for some reason.
1155** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1156** must invent its own temporary name for the file.  ^Whenever the
1157** xFilename parameter is NULL it will also be the case that the
1158** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1159**
1160** The flags argument to xOpen() includes all bits set in
1161** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1162** or [sqlite3_open16()] is used, then flags includes at least
1163** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1164** If xOpen() opens a file read-only then it sets *pOutFlags to
1165** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1166**
1167** ^(SQLite will also add one of the following flags to the xOpen()
1168** call, depending on the object being opened:
1169**
1170** <ul>
1171** <li>  [SQLITE_OPEN_MAIN_DB]
1172** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1173** <li>  [SQLITE_OPEN_TEMP_DB]
1174** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1175** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1176** <li>  [SQLITE_OPEN_SUBJOURNAL]
1177** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1178** <li>  [SQLITE_OPEN_WAL]
1179** </ul>)^
1180**
1181** The file I/O implementation can use the object type flags to
1182** change the way it deals with files.  For example, an application
1183** that does not care about crash recovery or rollback might make
1184** the open of a journal file a no-op.  Writes to this journal would
1185** also be no-ops, and any attempt to read the journal would return
1186** SQLITE_IOERR.  Or the implementation might recognize that a database
1187** file will be doing page-aligned sector reads and writes in a random
1188** order and set up its I/O subsystem accordingly.
1189**
1190** SQLite might also add one of the following flags to the xOpen method:
1191**
1192** <ul>
1193** <li> [SQLITE_OPEN_DELETEONCLOSE]
1194** <li> [SQLITE_OPEN_EXCLUSIVE]
1195** </ul>
1196**
1197** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1198** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
1199** will be set for TEMP databases and their journals, transient
1200** databases, and subjournals.
1201**
1202** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1203** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1204** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1205** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1206** SQLITE_OPEN_CREATE, is used to indicate that file should always
1207** be created, and that it is an error if it already exists.
1208** It is <i>not</i> used to indicate the file should be opened
1209** for exclusive access.
1210**
1211** ^At least szOsFile bytes of memory are allocated by SQLite
1212** to hold the  [sqlite3_file] structure passed as the third
1213** argument to xOpen.  The xOpen method does not have to
1214** allocate the structure; it should just fill it in.  Note that
1215** the xOpen method must set the sqlite3_file.pMethods to either
1216** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1217** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1218** element will be valid after xOpen returns regardless of the success
1219** or failure of the xOpen call.
1220**
1221** [[sqlite3_vfs.xAccess]]
1222** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1223** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1224** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1225** to test whether a file is at least readable.   The file can be a
1226** directory.
1227**
1228** ^SQLite will always allocate at least mxPathname+1 bytes for the
1229** output buffer xFullPathname.  The exact size of the output buffer
1230** is also passed as a parameter to both  methods. If the output buffer
1231** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1232** handled as a fatal error by SQLite, vfs implementations should endeavor
1233** to prevent this by setting mxPathname to a sufficiently large value.
1234**
1235** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1236** interfaces are not strictly a part of the filesystem, but they are
1237** included in the VFS structure for completeness.
1238** The xRandomness() function attempts to return nBytes bytes
1239** of good-quality randomness into zOut.  The return value is
1240** the actual number of bytes of randomness obtained.
1241** The xSleep() method causes the calling thread to sleep for at
1242** least the number of microseconds given.  ^The xCurrentTime()
1243** method returns a Julian Day Number for the current date and time as
1244** a floating point value.
1245** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1246** Day Number multiplied by 86400000 (the number of milliseconds in
1247** a 24-hour day).
1248** ^SQLite will use the xCurrentTimeInt64() method to get the current
1249** date and time if that method is available (if iVersion is 2 or
1250** greater and the function pointer is not NULL) and will fall back
1251** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1252**
1253** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1254** are not used by the SQLite core.  These optional interfaces are provided
1255** by some VFSes to facilitate testing of the VFS code. By overriding
1256** system calls with functions under its control, a test program can
1257** simulate faults and error conditions that would otherwise be difficult
1258** or impossible to induce.  The set of system calls that can be overridden
1259** varies from one VFS to another, and from one version of the same VFS to the
1260** next.  Applications that use these interfaces must be prepared for any
1261** or all of these interfaces to be NULL or for their behavior to change
1262** from one release to the next.  Applications must not attempt to access
1263** any of these methods if the iVersion of the VFS is less than 3.
1264*/
1265typedef struct sqlite3_vfs sqlite3_vfs;
1266typedef void (*sqlite3_syscall_ptr)(void);
1267struct sqlite3_vfs {
1268  int iVersion;            /* Structure version number (currently 3) */
1269  int szOsFile;            /* Size of subclassed sqlite3_file */
1270  int mxPathname;          /* Maximum file pathname length */
1271  sqlite3_vfs *pNext;      /* Next registered VFS */
1272  const char *zName;       /* Name of this virtual file system */
1273  void *pAppData;          /* Pointer to application-specific data */
1274  int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1275               int flags, int *pOutFlags);
1276  int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1277  int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1278  int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1279  void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1280  void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1281  void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1282  void (*xDlClose)(sqlite3_vfs*, void*);
1283  int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1284  int (*xSleep)(sqlite3_vfs*, int microseconds);
1285  int (*xCurrentTime)(sqlite3_vfs*, double*);
1286  int (*xGetLastError)(sqlite3_vfs*, int, char *);
1287  /*
1288  ** The methods above are in version 1 of the sqlite_vfs object
1289  ** definition.  Those that follow are added in version 2 or later
1290  */
1291  int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1292  /*
1293  ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1294  ** Those below are for version 3 and greater.
1295  */
1296  int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1297  sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1298  const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1299  /*
1300  ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1301  ** New fields may be appended in figure versions.  The iVersion
1302  ** value will increment whenever this happens.
1303  */
1304};
1305
1306/*
1307** CAPI3REF: Flags for the xAccess VFS method
1308**
1309** These integer constants can be used as the third parameter to
1310** the xAccess method of an [sqlite3_vfs] object.  They determine
1311** what kind of permissions the xAccess method is looking for.
1312** With SQLITE_ACCESS_EXISTS, the xAccess method
1313** simply checks whether the file exists.
1314** With SQLITE_ACCESS_READWRITE, the xAccess method
1315** checks whether the named directory is both readable and writable
1316** (in other words, if files can be added, removed, and renamed within
1317** the directory).
1318** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1319** [temp_store_directory pragma], though this could change in a future
1320** release of SQLite.
1321** With SQLITE_ACCESS_READ, the xAccess method
1322** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
1323** currently unused, though it might be used in a future release of
1324** SQLite.
1325*/
1326#define SQLITE_ACCESS_EXISTS    0
1327#define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
1328#define SQLITE_ACCESS_READ      2   /* Unused */
1329
1330/*
1331** CAPI3REF: Flags for the xShmLock VFS method
1332**
1333** These integer constants define the various locking operations
1334** allowed by the xShmLock method of [sqlite3_io_methods].  The
1335** following are the only legal combinations of flags to the
1336** xShmLock method:
1337**
1338** <ul>
1339** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1340** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1341** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1342** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1343** </ul>
1344**
1345** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1346** was given no the corresponding lock.
1347**
1348** The xShmLock method can transition between unlocked and SHARED or
1349** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1350** and EXCLUSIVE.
1351*/
1352#define SQLITE_SHM_UNLOCK       1
1353#define SQLITE_SHM_LOCK         2
1354#define SQLITE_SHM_SHARED       4
1355#define SQLITE_SHM_EXCLUSIVE    8
1356
1357/*
1358** CAPI3REF: Maximum xShmLock index
1359**
1360** The xShmLock method on [sqlite3_io_methods] may use values
1361** between 0 and this upper bound as its "offset" argument.
1362** The SQLite core will never attempt to acquire or release a
1363** lock outside of this range
1364*/
1365#define SQLITE_SHM_NLOCK        8
1366
1367
1368/*
1369** CAPI3REF: Initialize The SQLite Library
1370**
1371** ^The sqlite3_initialize() routine initializes the
1372** SQLite library.  ^The sqlite3_shutdown() routine
1373** deallocates any resources that were allocated by sqlite3_initialize().
1374** These routines are designed to aid in process initialization and
1375** shutdown on embedded systems.  Workstation applications using
1376** SQLite normally do not need to invoke either of these routines.
1377**
1378** A call to sqlite3_initialize() is an "effective" call if it is
1379** the first time sqlite3_initialize() is invoked during the lifetime of
1380** the process, or if it is the first time sqlite3_initialize() is invoked
1381** following a call to sqlite3_shutdown().  ^(Only an effective call
1382** of sqlite3_initialize() does any initialization.  All other calls
1383** are harmless no-ops.)^
1384**
1385** A call to sqlite3_shutdown() is an "effective" call if it is the first
1386** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1387** an effective call to sqlite3_shutdown() does any deinitialization.
1388** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1389**
1390** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1391** is not.  The sqlite3_shutdown() interface must only be called from a
1392** single thread.  All open [database connections] must be closed and all
1393** other SQLite resources must be deallocated prior to invoking
1394** sqlite3_shutdown().
1395**
1396** Among other things, ^sqlite3_initialize() will invoke
1397** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1398** will invoke sqlite3_os_end().
1399**
1400** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1401** ^If for some reason, sqlite3_initialize() is unable to initialize
1402** the library (perhaps it is unable to allocate a needed resource such
1403** as a mutex) it returns an [error code] other than [SQLITE_OK].
1404**
1405** ^The sqlite3_initialize() routine is called internally by many other
1406** SQLite interfaces so that an application usually does not need to
1407** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1408** calls sqlite3_initialize() so the SQLite library will be automatically
1409** initialized when [sqlite3_open()] is called if it has not be initialized
1410** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1411** compile-time option, then the automatic calls to sqlite3_initialize()
1412** are omitted and the application must call sqlite3_initialize() directly
1413** prior to using any other SQLite interface.  For maximum portability,
1414** it is recommended that applications always invoke sqlite3_initialize()
1415** directly prior to using any other SQLite interface.  Future releases
1416** of SQLite may require this.  In other words, the behavior exhibited
1417** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1418** default behavior in some future release of SQLite.
1419**
1420** The sqlite3_os_init() routine does operating-system specific
1421** initialization of the SQLite library.  The sqlite3_os_end()
1422** routine undoes the effect of sqlite3_os_init().  Typical tasks
1423** performed by these routines include allocation or deallocation
1424** of static resources, initialization of global variables,
1425** setting up a default [sqlite3_vfs] module, or setting up
1426** a default configuration using [sqlite3_config()].
1427**
1428** The application should never invoke either sqlite3_os_init()
1429** or sqlite3_os_end() directly.  The application should only invoke
1430** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1431** interface is called automatically by sqlite3_initialize() and
1432** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1433** implementations for sqlite3_os_init() and sqlite3_os_end()
1434** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1435** When [custom builds | built for other platforms]
1436** (using the [SQLITE_OS_OTHER=1] compile-time
1437** option) the application must supply a suitable implementation for
1438** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1439** implementation of sqlite3_os_init() or sqlite3_os_end()
1440** must return [SQLITE_OK] on success and some other [error code] upon
1441** failure.
1442*/
1443SQLITE_API int sqlite3_initialize(void);
1444SQLITE_API int sqlite3_shutdown(void);
1445SQLITE_API int sqlite3_os_init(void);
1446SQLITE_API int sqlite3_os_end(void);
1447
1448/*
1449** CAPI3REF: Configuring The SQLite Library
1450**
1451** The sqlite3_config() interface is used to make global configuration
1452** changes to SQLite in order to tune SQLite to the specific needs of
1453** the application.  The default configuration is recommended for most
1454** applications and so this routine is usually not necessary.  It is
1455** provided to support rare applications with unusual needs.
1456**
1457** The sqlite3_config() interface is not threadsafe.  The application
1458** must insure that no other SQLite interfaces are invoked by other
1459** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1460** may only be invoked prior to library initialization using
1461** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1462** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1463** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1464** Note, however, that ^sqlite3_config() can be called as part of the
1465** implementation of an application-defined [sqlite3_os_init()].
1466**
1467** The first argument to sqlite3_config() is an integer
1468** [configuration option] that determines
1469** what property of SQLite is to be configured.  Subsequent arguments
1470** vary depending on the [configuration option]
1471** in the first argument.
1472**
1473** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1474** ^If the option is unknown or SQLite is unable to set the option
1475** then this routine returns a non-zero [error code].
1476*/
1477SQLITE_API int sqlite3_config(int, ...);
1478
1479/*
1480** CAPI3REF: Configure database connections
1481**
1482** The sqlite3_db_config() interface is used to make configuration
1483** changes to a [database connection].  The interface is similar to
1484** [sqlite3_config()] except that the changes apply to a single
1485** [database connection] (specified in the first argument).
1486**
1487** The second argument to sqlite3_db_config(D,V,...)  is the
1488** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
1489** that indicates what aspect of the [database connection] is being configured.
1490** Subsequent arguments vary depending on the configuration verb.
1491**
1492** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1493** the call is considered successful.
1494*/
1495SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1496
1497/*
1498** CAPI3REF: Memory Allocation Routines
1499**
1500** An instance of this object defines the interface between SQLite
1501** and low-level memory allocation routines.
1502**
1503** This object is used in only one place in the SQLite interface.
1504** A pointer to an instance of this object is the argument to
1505** [sqlite3_config()] when the configuration option is
1506** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
1507** By creating an instance of this object
1508** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1509** during configuration, an application can specify an alternative
1510** memory allocation subsystem for SQLite to use for all of its
1511** dynamic memory needs.
1512**
1513** Note that SQLite comes with several [built-in memory allocators]
1514** that are perfectly adequate for the overwhelming majority of applications
1515** and that this object is only useful to a tiny minority of applications
1516** with specialized memory allocation requirements.  This object is
1517** also used during testing of SQLite in order to specify an alternative
1518** memory allocator that simulates memory out-of-memory conditions in
1519** order to verify that SQLite recovers gracefully from such
1520** conditions.
1521**
1522** The xMalloc, xRealloc, and xFree methods must work like the
1523** malloc(), realloc() and free() functions from the standard C library.
1524** ^SQLite guarantees that the second argument to
1525** xRealloc is always a value returned by a prior call to xRoundup.
1526**
1527** xSize should return the allocated size of a memory allocation
1528** previously obtained from xMalloc or xRealloc.  The allocated size
1529** is always at least as big as the requested size but may be larger.
1530**
1531** The xRoundup method returns what would be the allocated size of
1532** a memory allocation given a particular requested size.  Most memory
1533** allocators round up memory allocations at least to the next multiple
1534** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1535** Every memory allocation request coming in through [sqlite3_malloc()]
1536** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0,
1537** that causes the corresponding memory allocation to fail.
1538**
1539** The xInit method initializes the memory allocator.  For example,
1540** it might allocate any require mutexes or initialize internal data
1541** structures.  The xShutdown method is invoked (indirectly) by
1542** [sqlite3_shutdown()] and should deallocate any resources acquired
1543** by xInit.  The pAppData pointer is used as the only parameter to
1544** xInit and xShutdown.
1545**
1546** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1547** the xInit method, so the xInit method need not be threadsafe.  The
1548** xShutdown method is only called from [sqlite3_shutdown()] so it does
1549** not need to be threadsafe either.  For all other methods, SQLite
1550** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1551** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1552** it is by default) and so the methods are automatically serialized.
1553** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1554** methods must be threadsafe or else make their own arrangements for
1555** serialization.
1556**
1557** SQLite will never invoke xInit() more than once without an intervening
1558** call to xShutdown().
1559*/
1560typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1561struct sqlite3_mem_methods {
1562  void *(*xMalloc)(int);         /* Memory allocation function */
1563  void (*xFree)(void*);          /* Free a prior allocation */
1564  void *(*xRealloc)(void*,int);  /* Resize an allocation */
1565  int (*xSize)(void*);           /* Return the size of an allocation */
1566  int (*xRoundup)(int);          /* Round up request size to allocation size */
1567  int (*xInit)(void*);           /* Initialize the memory allocator */
1568  void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1569  void *pAppData;                /* Argument to xInit() and xShutdown() */
1570};
1571
1572/*
1573** CAPI3REF: Configuration Options
1574** KEYWORDS: {configuration option}
1575**
1576** These constants are the available integer configuration options that
1577** can be passed as the first argument to the [sqlite3_config()] interface.
1578**
1579** New configuration options may be added in future releases of SQLite.
1580** Existing configuration options might be discontinued.  Applications
1581** should check the return code from [sqlite3_config()] to make sure that
1582** the call worked.  The [sqlite3_config()] interface will return a
1583** non-zero [error code] if a discontinued or unsupported configuration option
1584** is invoked.
1585**
1586** <dl>
1587** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1588** <dd>There are no arguments to this option.  ^This option sets the
1589** [threading mode] to Single-thread.  In other words, it disables
1590** all mutexing and puts SQLite into a mode where it can only be used
1591** by a single thread.   ^If SQLite is compiled with
1592** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1593** it is not possible to change the [threading mode] from its default
1594** value of Single-thread and so [sqlite3_config()] will return
1595** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1596** configuration option.</dd>
1597**
1598** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1599** <dd>There are no arguments to this option.  ^This option sets the
1600** [threading mode] to Multi-thread.  In other words, it disables
1601** mutexing on [database connection] and [prepared statement] objects.
1602** The application is responsible for serializing access to
1603** [database connections] and [prepared statements].  But other mutexes
1604** are enabled so that SQLite will be safe to use in a multi-threaded
1605** environment as long as no two threads attempt to use the same
1606** [database connection] at the same time.  ^If SQLite is compiled with
1607** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1608** it is not possible to set the Multi-thread [threading mode] and
1609** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1610** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1611**
1612** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
1613** <dd>There are no arguments to this option.  ^This option sets the
1614** [threading mode] to Serialized. In other words, this option enables
1615** all mutexes including the recursive
1616** mutexes on [database connection] and [prepared statement] objects.
1617** In this mode (which is the default when SQLite is compiled with
1618** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1619** to [database connections] and [prepared statements] so that the
1620** application is free to use the same [database connection] or the
1621** same [prepared statement] in different threads at the same time.
1622** ^If SQLite is compiled with
1623** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1624** it is not possible to set the Serialized [threading mode] and
1625** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1626** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1627**
1628** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
1629** <dd> ^(This option takes a single argument which is a pointer to an
1630** instance of the [sqlite3_mem_methods] structure.  The argument specifies
1631** alternative low-level memory allocation routines to be used in place of
1632** the memory allocation routines built into SQLite.)^ ^SQLite makes
1633** its own private copy of the content of the [sqlite3_mem_methods] structure
1634** before the [sqlite3_config()] call returns.</dd>
1635**
1636** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
1637** <dd> ^(This option takes a single argument which is a pointer to an
1638** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
1639** structure is filled with the currently defined memory allocation routines.)^
1640** This option can be used to overload the default memory allocation
1641** routines with a wrapper that simulations memory allocation failure or
1642** tracks memory usage, for example. </dd>
1643**
1644** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1645** <dd> ^This option takes single argument of type int, interpreted as a
1646** boolean, which enables or disables the collection of memory allocation
1647** statistics. ^(When memory allocation statistics are disabled, the
1648** following SQLite interfaces become non-operational:
1649**   <ul>
1650**   <li> [sqlite3_memory_used()]
1651**   <li> [sqlite3_memory_highwater()]
1652**   <li> [sqlite3_soft_heap_limit64()]
1653**   <li> [sqlite3_status()]
1654**   </ul>)^
1655** ^Memory allocation statistics are enabled by default unless SQLite is
1656** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1657** allocation statistics are disabled by default.
1658** </dd>
1659**
1660** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
1661** <dd> ^This option specifies a static memory buffer that SQLite can use for
1662** scratch memory.  There are three arguments:  A pointer an 8-byte
1663** aligned memory buffer from which the scratch allocations will be
1664** drawn, the size of each scratch allocation (sz),
1665** and the maximum number of scratch allocations (N).  The sz
1666** argument must be a multiple of 16.
1667** The first argument must be a pointer to an 8-byte aligned buffer
1668** of at least sz*N bytes of memory.
1669** ^SQLite will use no more than two scratch buffers per thread.  So
1670** N should be set to twice the expected maximum number of threads.
1671** ^SQLite will never require a scratch buffer that is more than 6
1672** times the database page size. ^If SQLite needs needs additional
1673** scratch memory beyond what is provided by this configuration option, then
1674** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
1675**
1676** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
1677** <dd> ^This option specifies a static memory buffer that SQLite can use for
1678** the database page cache with the default page cache implementation.
1679** This configuration should not be used if an application-define page
1680** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option.
1681** There are three arguments to this option: A pointer to 8-byte aligned
1682** memory, the size of each page buffer (sz), and the number of pages (N).
1683** The sz argument should be the size of the largest database page
1684** (a power of two between 512 and 32768) plus a little extra for each
1685** page header.  ^The page header size is 20 to 40 bytes depending on
1686** the host architecture.  ^It is harmless, apart from the wasted memory,
1687** to make sz a little too large.  The first
1688** argument should point to an allocation of at least sz*N bytes of memory.
1689** ^SQLite will use the memory provided by the first argument to satisfy its
1690** memory needs for the first N pages that it adds to cache.  ^If additional
1691** page cache memory is needed beyond what is provided by this option, then
1692** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1693** The pointer in the first argument must
1694** be aligned to an 8-byte boundary or subsequent behavior of SQLite
1695** will be undefined.</dd>
1696**
1697** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
1698** <dd> ^This option specifies a static memory buffer that SQLite will use
1699** for all of its dynamic memory allocation needs beyond those provided
1700** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
1701** There are three arguments: An 8-byte aligned pointer to the memory,
1702** the number of bytes in the memory buffer, and the minimum allocation size.
1703** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1704** to using its default memory allocator (the system malloc() implementation),
1705** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
1706** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
1707** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
1708** allocator is engaged to handle all of SQLites memory allocation needs.
1709** The first pointer (the memory pointer) must be aligned to an 8-byte
1710** boundary or subsequent behavior of SQLite will be undefined.
1711** The minimum allocation size is capped at 2**12. Reasonable values
1712** for the minimum allocation size are 2**5 through 2**8.</dd>
1713**
1714** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
1715** <dd> ^(This option takes a single argument which is a pointer to an
1716** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
1717** alternative low-level mutex routines to be used in place
1718** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
1719** content of the [sqlite3_mutex_methods] structure before the call to
1720** [sqlite3_config()] returns. ^If SQLite is compiled with
1721** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1722** the entire mutexing subsystem is omitted from the build and hence calls to
1723** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1724** return [SQLITE_ERROR].</dd>
1725**
1726** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
1727** <dd> ^(This option takes a single argument which is a pointer to an
1728** instance of the [sqlite3_mutex_methods] structure.  The
1729** [sqlite3_mutex_methods]
1730** structure is filled with the currently defined mutex routines.)^
1731** This option can be used to overload the default mutex allocation
1732** routines with a wrapper used to track mutex usage for performance
1733** profiling or testing, for example.   ^If SQLite is compiled with
1734** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1735** the entire mutexing subsystem is omitted from the build and hence calls to
1736** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1737** return [SQLITE_ERROR].</dd>
1738**
1739** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1740** <dd> ^(This option takes two arguments that determine the default
1741** memory allocation for the lookaside memory allocator on each
1742** [database connection].  The first argument is the
1743** size of each lookaside buffer slot and the second is the number of
1744** slots allocated to each database connection.)^  ^(This option sets the
1745** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1746** verb to [sqlite3_db_config()] can be used to change the lookaside
1747** configuration on individual connections.)^ </dd>
1748**
1749** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
1750** <dd> ^(This option takes a single argument which is a pointer to
1751** an [sqlite3_pcache_methods2] object.  This object specifies the interface
1752** to a custom page cache implementation.)^  ^SQLite makes a copy of the
1753** object and uses it for page cache memory allocations.</dd>
1754**
1755** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
1756** <dd> ^(This option takes a single argument which is a pointer to an
1757** [sqlite3_pcache_methods2] object.  SQLite copies of the current
1758** page cache implementation into that object.)^ </dd>
1759**
1760** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
1761** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
1762** global [error log].
1763** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
1764** function with a call signature of void(*)(void*,int,const char*),
1765** and a pointer to void. ^If the function pointer is not NULL, it is
1766** invoked by [sqlite3_log()] to process each logging event.  ^If the
1767** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
1768** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
1769** passed through as the first parameter to the application-defined logger
1770** function whenever that function is invoked.  ^The second parameter to
1771** the logger function is a copy of the first parameter to the corresponding
1772** [sqlite3_log()] call and is intended to be a [result code] or an
1773** [extended result code].  ^The third parameter passed to the logger is
1774** log message after formatting via [sqlite3_snprintf()].
1775** The SQLite logging interface is not reentrant; the logger function
1776** supplied by the application must not invoke any SQLite interface.
1777** In a multi-threaded application, the application-defined logger
1778** function must be threadsafe. </dd>
1779**
1780** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
1781** <dd>^(This option takes a single argument of type int. If non-zero, then
1782** URI handling is globally enabled. If the parameter is zero, then URI handling
1783** is globally disabled.)^ ^If URI handling is globally enabled, all filenames
1784** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
1785** specified as part of [ATTACH] commands are interpreted as URIs, regardless
1786** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
1787** connection is opened. ^If it is globally disabled, filenames are
1788** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
1789** database connection is opened. ^(By default, URI handling is globally
1790** disabled. The default value may be changed by compiling with the
1791** [SQLITE_USE_URI] symbol defined.)^
1792**
1793** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
1794** <dd>^This option takes a single integer argument which is interpreted as
1795** a boolean in order to enable or disable the use of covering indices for
1796** full table scans in the query optimizer.  ^The default setting is determined
1797** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
1798** if that compile-time option is omitted.
1799** The ability to disable the use of covering indices for full table scans
1800** is because some incorrectly coded legacy applications might malfunction
1801** when the optimization is enabled.  Providing the ability to
1802** disable the optimization allows the older, buggy application code to work
1803** without change even with newer versions of SQLite.
1804**
1805** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
1806** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
1807** <dd> These options are obsolete and should not be used by new code.
1808** They are retained for backwards compatibility but are now no-ops.
1809** </dd>
1810**
1811** [[SQLITE_CONFIG_SQLLOG]]
1812** <dt>SQLITE_CONFIG_SQLLOG
1813** <dd>This option is only available if sqlite is compiled with the
1814** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
1815** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
1816** The second should be of type (void*). The callback is invoked by the library
1817** in three separate circumstances, identified by the value passed as the
1818** fourth parameter. If the fourth parameter is 0, then the database connection
1819** passed as the second argument has just been opened. The third argument
1820** points to a buffer containing the name of the main database file. If the
1821** fourth parameter is 1, then the SQL statement that the third parameter
1822** points to has just been executed. Or, if the fourth parameter is 2, then
1823** the connection being passed as the second parameter is being closed. The
1824** third parameter is passed NULL In this case.  An example of using this
1825** configuration option can be seen in the "test_sqllog.c" source file in
1826** the canonical SQLite source tree.</dd>
1827**
1828** [[SQLITE_CONFIG_MMAP_SIZE]]
1829** <dt>SQLITE_CONFIG_MMAP_SIZE
1830** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
1831** that are the default mmap size limit (the default setting for
1832** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
1833** ^The default setting can be overridden by each database connection using
1834** either the [PRAGMA mmap_size] command, or by using the
1835** [SQLITE_FCNTL_MMAP_SIZE] file control.  ^(The maximum allowed mmap size
1836** cannot be changed at run-time.  Nor may the maximum allowed mmap size
1837** exceed the compile-time maximum mmap size set by the
1838** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
1839** ^If either argument to this option is negative, then that argument is
1840** changed to its compile-time default.
1841**
1842** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
1843** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
1844** <dd>^This option is only available if SQLite is compiled for Windows
1845** with the [SQLITE_WIN32_MALLOC] pre-processor macro defined.
1846** SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
1847** that specifies the maximum size of the created heap.
1848** </dl>
1849*/
1850#define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
1851#define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
1852#define SQLITE_CONFIG_SERIALIZED    3  /* nil */
1853#define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
1854#define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
1855#define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
1856#define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
1857#define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
1858#define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
1859#define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
1860#define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
1861/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
1862#define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
1863#define SQLITE_CONFIG_PCACHE       14  /* no-op */
1864#define SQLITE_CONFIG_GETPCACHE    15  /* no-op */
1865#define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
1866#define SQLITE_CONFIG_URI          17  /* int */
1867#define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */
1868#define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */
1869#define SQLITE_CONFIG_COVERING_INDEX_SCAN 20  /* int */
1870#define SQLITE_CONFIG_SQLLOG       21  /* xSqllog, void* */
1871#define SQLITE_CONFIG_MMAP_SIZE    22  /* sqlite3_int64, sqlite3_int64 */
1872#define SQLITE_CONFIG_WIN32_HEAPSIZE      23  /* int nByte */
1873
1874/*
1875** CAPI3REF: Database Connection Configuration Options
1876**
1877** These constants are the available integer configuration options that
1878** can be passed as the second argument to the [sqlite3_db_config()] interface.
1879**
1880** New configuration options may be added in future releases of SQLite.
1881** Existing configuration options might be discontinued.  Applications
1882** should check the return code from [sqlite3_db_config()] to make sure that
1883** the call worked.  ^The [sqlite3_db_config()] interface will return a
1884** non-zero [error code] if a discontinued or unsupported configuration option
1885** is invoked.
1886**
1887** <dl>
1888** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
1889** <dd> ^This option takes three additional arguments that determine the
1890** [lookaside memory allocator] configuration for the [database connection].
1891** ^The first argument (the third parameter to [sqlite3_db_config()] is a
1892** pointer to a memory buffer to use for lookaside memory.
1893** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
1894** may be NULL in which case SQLite will allocate the
1895** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
1896** size of each lookaside buffer slot.  ^The third argument is the number of
1897** slots.  The size of the buffer in the first argument must be greater than
1898** or equal to the product of the second and third arguments.  The buffer
1899** must be aligned to an 8-byte boundary.  ^If the second argument to
1900** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
1901** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
1902** configuration for a database connection can only be changed when that
1903** connection is not currently using lookaside memory, or in other words
1904** when the "current value" returned by
1905** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
1906** Any attempt to change the lookaside memory configuration when lookaside
1907** memory is in use leaves the configuration unchanged and returns
1908** [SQLITE_BUSY].)^</dd>
1909**
1910** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
1911** <dd> ^This option is used to enable or disable the enforcement of
1912** [foreign key constraints].  There should be two additional arguments.
1913** The first argument is an integer which is 0 to disable FK enforcement,
1914** positive to enable FK enforcement or negative to leave FK enforcement
1915** unchanged.  The second parameter is a pointer to an integer into which
1916** is written 0 or 1 to indicate whether FK enforcement is off or on
1917** following this call.  The second parameter may be a NULL pointer, in
1918** which case the FK enforcement setting is not reported back. </dd>
1919**
1920** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
1921** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
1922** There should be two additional arguments.
1923** The first argument is an integer which is 0 to disable triggers,
1924** positive to enable triggers or negative to leave the setting unchanged.
1925** The second parameter is a pointer to an integer into which
1926** is written 0 or 1 to indicate whether triggers are disabled or enabled
1927** following this call.  The second parameter may be a NULL pointer, in
1928** which case the trigger setting is not reported back. </dd>
1929**
1930** </dl>
1931*/
1932#define SQLITE_DBCONFIG_LOOKASIDE       1001  /* void* int int */
1933#define SQLITE_DBCONFIG_ENABLE_FKEY     1002  /* int int* */
1934#define SQLITE_DBCONFIG_ENABLE_TRIGGER  1003  /* int int* */
1935
1936
1937/*
1938** CAPI3REF: Enable Or Disable Extended Result Codes
1939**
1940** ^The sqlite3_extended_result_codes() routine enables or disables the
1941** [extended result codes] feature of SQLite. ^The extended result
1942** codes are disabled by default for historical compatibility.
1943*/
1944SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
1945
1946/*
1947** CAPI3REF: Last Insert Rowid
1948**
1949** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
1950** has a unique 64-bit signed
1951** integer key called the [ROWID | "rowid"]. ^The rowid is always available
1952** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
1953** names are not also used by explicitly declared columns. ^If
1954** the table has a column of type [INTEGER PRIMARY KEY] then that column
1955** is another alias for the rowid.
1956**
1957** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the
1958** most recent successful [INSERT] into a rowid table or [virtual table]
1959** on database connection D.
1960** ^Inserts into [WITHOUT ROWID] tables are not recorded.
1961** ^If no successful [INSERT]s into rowid tables
1962** have ever occurred on the database connection D,
1963** then sqlite3_last_insert_rowid(D) returns zero.
1964**
1965** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
1966** method, then this routine will return the [rowid] of the inserted
1967** row as long as the trigger or virtual table method is running.
1968** But once the trigger or virtual table method ends, the value returned
1969** by this routine reverts to what it was before the trigger or virtual
1970** table method began.)^
1971**
1972** ^An [INSERT] that fails due to a constraint violation is not a
1973** successful [INSERT] and does not change the value returned by this
1974** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
1975** and INSERT OR ABORT make no changes to the return value of this
1976** routine when their insertion fails.  ^(When INSERT OR REPLACE
1977** encounters a constraint violation, it does not fail.  The
1978** INSERT continues to completion after deleting rows that caused
1979** the constraint problem so INSERT OR REPLACE will always change
1980** the return value of this interface.)^
1981**
1982** ^For the purposes of this routine, an [INSERT] is considered to
1983** be successful even if it is subsequently rolled back.
1984**
1985** This function is accessible to SQL statements via the
1986** [last_insert_rowid() SQL function].
1987**
1988** If a separate thread performs a new [INSERT] on the same
1989** database connection while the [sqlite3_last_insert_rowid()]
1990** function is running and thus changes the last insert [rowid],
1991** then the value returned by [sqlite3_last_insert_rowid()] is
1992** unpredictable and might not equal either the old or the new
1993** last insert [rowid].
1994*/
1995SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
1996
1997/*
1998** CAPI3REF: Count The Number Of Rows Modified
1999**
2000** ^This function returns the number of database rows that were changed
2001** or inserted or deleted by the most recently completed SQL statement
2002** on the [database connection] specified by the first parameter.
2003** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
2004** or [DELETE] statement are counted.  Auxiliary changes caused by
2005** triggers or [foreign key actions] are not counted.)^ Use the
2006** [sqlite3_total_changes()] function to find the total number of changes
2007** including changes caused by triggers and foreign key actions.
2008**
2009** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
2010** are not counted.  Only real table changes are counted.
2011**
2012** ^(A "row change" is a change to a single row of a single table
2013** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
2014** are changed as side effects of [REPLACE] constraint resolution,
2015** rollback, ABORT processing, [DROP TABLE], or by any other
2016** mechanisms do not count as direct row changes.)^
2017**
2018** A "trigger context" is a scope of execution that begins and
2019** ends with the script of a [CREATE TRIGGER | trigger].
2020** Most SQL statements are
2021** evaluated outside of any trigger.  This is the "top level"
2022** trigger context.  If a trigger fires from the top level, a
2023** new trigger context is entered for the duration of that one
2024** trigger.  Subtriggers create subcontexts for their duration.
2025**
2026** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
2027** not create a new trigger context.
2028**
2029** ^This function returns the number of direct row changes in the
2030** most recent INSERT, UPDATE, or DELETE statement within the same
2031** trigger context.
2032**
2033** ^Thus, when called from the top level, this function returns the
2034** number of changes in the most recent INSERT, UPDATE, or DELETE
2035** that also occurred at the top level.  ^(Within the body of a trigger,
2036** the sqlite3_changes() interface can be called to find the number of
2037** changes in the most recently completed INSERT, UPDATE, or DELETE
2038** statement within the body of the same trigger.
2039** However, the number returned does not include changes
2040** caused by subtriggers since those have their own context.)^
2041**
2042** See also the [sqlite3_total_changes()] interface, the
2043** [count_changes pragma], and the [changes() SQL function].
2044**
2045** If a separate thread makes changes on the same database connection
2046** while [sqlite3_changes()] is running then the value returned
2047** is unpredictable and not meaningful.
2048*/
2049SQLITE_API int sqlite3_changes(sqlite3*);
2050
2051/*
2052** CAPI3REF: Total Number Of Rows Modified
2053**
2054** ^This function returns the number of row changes caused by [INSERT],
2055** [UPDATE] or [DELETE] statements since the [database connection] was opened.
2056** ^(The count returned by sqlite3_total_changes() includes all changes
2057** from all [CREATE TRIGGER | trigger] contexts and changes made by
2058** [foreign key actions]. However,
2059** the count does not include changes used to implement [REPLACE] constraints,
2060** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
2061** count does not include rows of views that fire an [INSTEAD OF trigger],
2062** though if the INSTEAD OF trigger makes changes of its own, those changes
2063** are counted.)^
2064** ^The sqlite3_total_changes() function counts the changes as soon as
2065** the statement that makes them is completed (when the statement handle
2066** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
2067**
2068** See also the [sqlite3_changes()] interface, the
2069** [count_changes pragma], and the [total_changes() SQL function].
2070**
2071** If a separate thread makes changes on the same database connection
2072** while [sqlite3_total_changes()] is running then the value
2073** returned is unpredictable and not meaningful.
2074*/
2075SQLITE_API int sqlite3_total_changes(sqlite3*);
2076
2077/*
2078** CAPI3REF: Interrupt A Long-Running Query
2079**
2080** ^This function causes any pending database operation to abort and
2081** return at its earliest opportunity. This routine is typically
2082** called in response to a user action such as pressing "Cancel"
2083** or Ctrl-C where the user wants a long query operation to halt
2084** immediately.
2085**
2086** ^It is safe to call this routine from a thread different from the
2087** thread that is currently running the database operation.  But it
2088** is not safe to call this routine with a [database connection] that
2089** is closed or might close before sqlite3_interrupt() returns.
2090**
2091** ^If an SQL operation is very nearly finished at the time when
2092** sqlite3_interrupt() is called, then it might not have an opportunity
2093** to be interrupted and might continue to completion.
2094**
2095** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2096** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2097** that is inside an explicit transaction, then the entire transaction
2098** will be rolled back automatically.
2099**
2100** ^The sqlite3_interrupt(D) call is in effect until all currently running
2101** SQL statements on [database connection] D complete.  ^Any new SQL statements
2102** that are started after the sqlite3_interrupt() call and before the
2103** running statements reaches zero are interrupted as if they had been
2104** running prior to the sqlite3_interrupt() call.  ^New SQL statements
2105** that are started after the running statement count reaches zero are
2106** not effected by the sqlite3_interrupt().
2107** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2108** SQL statements is a no-op and has no effect on SQL statements
2109** that are started after the sqlite3_interrupt() call returns.
2110**
2111** If the database connection closes while [sqlite3_interrupt()]
2112** is running then bad things will likely happen.
2113*/
2114SQLITE_API void sqlite3_interrupt(sqlite3*);
2115
2116/*
2117** CAPI3REF: Determine If An SQL Statement Is Complete
2118**
2119** These routines are useful during command-line input to determine if the
2120** currently entered text seems to form a complete SQL statement or
2121** if additional input is needed before sending the text into
2122** SQLite for parsing.  ^These routines return 1 if the input string
2123** appears to be a complete SQL statement.  ^A statement is judged to be
2124** complete if it ends with a semicolon token and is not a prefix of a
2125** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2126** string literals or quoted identifier names or comments are not
2127** independent tokens (they are part of the token in which they are
2128** embedded) and thus do not count as a statement terminator.  ^Whitespace
2129** and comments that follow the final semicolon are ignored.
2130**
2131** ^These routines return 0 if the statement is incomplete.  ^If a
2132** memory allocation fails, then SQLITE_NOMEM is returned.
2133**
2134** ^These routines do not parse the SQL statements thus
2135** will not detect syntactically incorrect SQL.
2136**
2137** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
2138** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2139** automatically by sqlite3_complete16().  If that initialization fails,
2140** then the return value from sqlite3_complete16() will be non-zero
2141** regardless of whether or not the input SQL is complete.)^
2142**
2143** The input to [sqlite3_complete()] must be a zero-terminated
2144** UTF-8 string.
2145**
2146** The input to [sqlite3_complete16()] must be a zero-terminated
2147** UTF-16 string in native byte order.
2148*/
2149SQLITE_API int sqlite3_complete(const char *sql);
2150SQLITE_API int sqlite3_complete16(const void *sql);
2151
2152/*
2153** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2154**
2155** ^This routine sets a callback function that might be invoked whenever
2156** an attempt is made to open a database table that another thread
2157** or process has locked.
2158**
2159** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2160** is returned immediately upon encountering the lock.  ^If the busy callback
2161** is not NULL, then the callback might be invoked with two arguments.
2162**
2163** ^The first argument to the busy handler is a copy of the void* pointer which
2164** is the third argument to sqlite3_busy_handler().  ^The second argument to
2165** the busy handler callback is the number of times that the busy handler has
2166** been invoked for this locking event.  ^If the
2167** busy callback returns 0, then no additional attempts are made to
2168** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2169** ^If the callback returns non-zero, then another attempt
2170** is made to open the database for reading and the cycle repeats.
2171**
2172** The presence of a busy handler does not guarantee that it will be invoked
2173** when there is lock contention. ^If SQLite determines that invoking the busy
2174** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2175** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2176** Consider a scenario where one process is holding a read lock that
2177** it is trying to promote to a reserved lock and
2178** a second process is holding a reserved lock that it is trying
2179** to promote to an exclusive lock.  The first process cannot proceed
2180** because it is blocked by the second and the second process cannot
2181** proceed because it is blocked by the first.  If both processes
2182** invoke the busy handlers, neither will make any progress.  Therefore,
2183** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2184** will induce the first process to release its read lock and allow
2185** the second process to proceed.
2186**
2187** ^The default busy callback is NULL.
2188**
2189** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2190** when SQLite is in the middle of a large transaction where all the
2191** changes will not fit into the in-memory cache.  SQLite will
2192** already hold a RESERVED lock on the database file, but it needs
2193** to promote this lock to EXCLUSIVE so that it can spill cache
2194** pages into the database file without harm to concurrent
2195** readers.  ^If it is unable to promote the lock, then the in-memory
2196** cache will be left in an inconsistent state and so the error
2197** code is promoted from the relatively benign [SQLITE_BUSY] to
2198** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
2199** forces an automatic rollback of the changes.  See the
2200** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2201** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2202** this is important.
2203**
2204** ^(There can only be a single busy handler defined for each
2205** [database connection].  Setting a new busy handler clears any
2206** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2207** will also set or clear the busy handler.
2208**
2209** The busy callback should not take any actions which modify the
2210** database connection that invoked the busy handler.  Any such actions
2211** result in undefined behavior.
2212**
2213** A busy handler must not close the database connection
2214** or [prepared statement] that invoked the busy handler.
2215*/
2216SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2217
2218/*
2219** CAPI3REF: Set A Busy Timeout
2220**
2221** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2222** for a specified amount of time when a table is locked.  ^The handler
2223** will sleep multiple times until at least "ms" milliseconds of sleeping
2224** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2225** the handler returns 0 which causes [sqlite3_step()] to return
2226** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2227**
2228** ^Calling this routine with an argument less than or equal to zero
2229** turns off all busy handlers.
2230**
2231** ^(There can only be a single busy handler for a particular
2232** [database connection] any any given moment.  If another busy handler
2233** was defined  (using [sqlite3_busy_handler()]) prior to calling
2234** this routine, that other busy handler is cleared.)^
2235*/
2236SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2237
2238/*
2239** CAPI3REF: Convenience Routines For Running Queries
2240**
2241** This is a legacy interface that is preserved for backwards compatibility.
2242** Use of this interface is not recommended.
2243**
2244** Definition: A <b>result table</b> is memory data structure created by the
2245** [sqlite3_get_table()] interface.  A result table records the
2246** complete query results from one or more queries.
2247**
2248** The table conceptually has a number of rows and columns.  But
2249** these numbers are not part of the result table itself.  These
2250** numbers are obtained separately.  Let N be the number of rows
2251** and M be the number of columns.
2252**
2253** A result table is an array of pointers to zero-terminated UTF-8 strings.
2254** There are (N+1)*M elements in the array.  The first M pointers point
2255** to zero-terminated strings that  contain the names of the columns.
2256** The remaining entries all point to query results.  NULL values result
2257** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2258** string representation as returned by [sqlite3_column_text()].
2259**
2260** A result table might consist of one or more memory allocations.
2261** It is not safe to pass a result table directly to [sqlite3_free()].
2262** A result table should be deallocated using [sqlite3_free_table()].
2263**
2264** ^(As an example of the result table format, suppose a query result
2265** is as follows:
2266**
2267** <blockquote><pre>
2268**        Name        | Age
2269**        -----------------------
2270**        Alice       | 43
2271**        Bob         | 28
2272**        Cindy       | 21
2273** </pre></blockquote>
2274**
2275** There are two column (M==2) and three rows (N==3).  Thus the
2276** result table has 8 entries.  Suppose the result table is stored
2277** in an array names azResult.  Then azResult holds this content:
2278**
2279** <blockquote><pre>
2280**        azResult&#91;0] = "Name";
2281**        azResult&#91;1] = "Age";
2282**        azResult&#91;2] = "Alice";
2283**        azResult&#91;3] = "43";
2284**        azResult&#91;4] = "Bob";
2285**        azResult&#91;5] = "28";
2286**        azResult&#91;6] = "Cindy";
2287**        azResult&#91;7] = "21";
2288** </pre></blockquote>)^
2289**
2290** ^The sqlite3_get_table() function evaluates one or more
2291** semicolon-separated SQL statements in the zero-terminated UTF-8
2292** string of its 2nd parameter and returns a result table to the
2293** pointer given in its 3rd parameter.
2294**
2295** After the application has finished with the result from sqlite3_get_table(),
2296** it must pass the result table pointer to sqlite3_free_table() in order to
2297** release the memory that was malloced.  Because of the way the
2298** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2299** function must not try to call [sqlite3_free()] directly.  Only
2300** [sqlite3_free_table()] is able to release the memory properly and safely.
2301**
2302** The sqlite3_get_table() interface is implemented as a wrapper around
2303** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2304** to any internal data structures of SQLite.  It uses only the public
2305** interface defined here.  As a consequence, errors that occur in the
2306** wrapper layer outside of the internal [sqlite3_exec()] call are not
2307** reflected in subsequent calls to [sqlite3_errcode()] or
2308** [sqlite3_errmsg()].
2309*/
2310SQLITE_API int sqlite3_get_table(
2311  sqlite3 *db,          /* An open database */
2312  const char *zSql,     /* SQL to be evaluated */
2313  char ***pazResult,    /* Results of the query */
2314  int *pnRow,           /* Number of result rows written here */
2315  int *pnColumn,        /* Number of result columns written here */
2316  char **pzErrmsg       /* Error msg written here */
2317);
2318SQLITE_API void sqlite3_free_table(char **result);
2319
2320/*
2321** CAPI3REF: Formatted String Printing Functions
2322**
2323** These routines are work-alikes of the "printf()" family of functions
2324** from the standard C library.
2325**
2326** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2327** results into memory obtained from [sqlite3_malloc()].
2328** The strings returned by these two routines should be
2329** released by [sqlite3_free()].  ^Both routines return a
2330** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2331** memory to hold the resulting string.
2332**
2333** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2334** the standard C library.  The result is written into the
2335** buffer supplied as the second parameter whose size is given by
2336** the first parameter. Note that the order of the
2337** first two parameters is reversed from snprintf().)^  This is an
2338** historical accident that cannot be fixed without breaking
2339** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2340** returns a pointer to its buffer instead of the number of
2341** characters actually written into the buffer.)^  We admit that
2342** the number of characters written would be a more useful return
2343** value but we cannot change the implementation of sqlite3_snprintf()
2344** now without breaking compatibility.
2345**
2346** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2347** guarantees that the buffer is always zero-terminated.  ^The first
2348** parameter "n" is the total size of the buffer, including space for
2349** the zero terminator.  So the longest string that can be completely
2350** written will be n-1 characters.
2351**
2352** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2353**
2354** These routines all implement some additional formatting
2355** options that are useful for constructing SQL statements.
2356** All of the usual printf() formatting options apply.  In addition, there
2357** is are "%q", "%Q", and "%z" options.
2358**
2359** ^(The %q option works like %s in that it substitutes a nul-terminated
2360** string from the argument list.  But %q also doubles every '\'' character.
2361** %q is designed for use inside a string literal.)^  By doubling each '\''
2362** character it escapes that character and allows it to be inserted into
2363** the string.
2364**
2365** For example, assume the string variable zText contains text as follows:
2366**
2367** <blockquote><pre>
2368**  char *zText = "It's a happy day!";
2369** </pre></blockquote>
2370**
2371** One can use this text in an SQL statement as follows:
2372**
2373** <blockquote><pre>
2374**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2375**  sqlite3_exec(db, zSQL, 0, 0, 0);
2376**  sqlite3_free(zSQL);
2377** </pre></blockquote>
2378**
2379** Because the %q format string is used, the '\'' character in zText
2380** is escaped and the SQL generated is as follows:
2381**
2382** <blockquote><pre>
2383**  INSERT INTO table1 VALUES('It''s a happy day!')
2384** </pre></blockquote>
2385**
2386** This is correct.  Had we used %s instead of %q, the generated SQL
2387** would have looked like this:
2388**
2389** <blockquote><pre>
2390**  INSERT INTO table1 VALUES('It's a happy day!');
2391** </pre></blockquote>
2392**
2393** This second example is an SQL syntax error.  As a general rule you should
2394** always use %q instead of %s when inserting text into a string literal.
2395**
2396** ^(The %Q option works like %q except it also adds single quotes around
2397** the outside of the total string.  Additionally, if the parameter in the
2398** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2399** single quotes).)^  So, for example, one could say:
2400**
2401** <blockquote><pre>
2402**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2403**  sqlite3_exec(db, zSQL, 0, 0, 0);
2404**  sqlite3_free(zSQL);
2405** </pre></blockquote>
2406**
2407** The code above will render a correct SQL statement in the zSQL
2408** variable even if the zText variable is a NULL pointer.
2409**
2410** ^(The "%z" formatting option works like "%s" but with the
2411** addition that after the string has been read and copied into
2412** the result, [sqlite3_free()] is called on the input string.)^
2413*/
2414SQLITE_API char *sqlite3_mprintf(const char*,...);
2415SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2416SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2417SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
2418
2419/*
2420** CAPI3REF: Memory Allocation Subsystem
2421**
2422** The SQLite core uses these three routines for all of its own
2423** internal memory allocation needs. "Core" in the previous sentence
2424** does not include operating-system specific VFS implementation.  The
2425** Windows VFS uses native malloc() and free() for some operations.
2426**
2427** ^The sqlite3_malloc() routine returns a pointer to a block
2428** of memory at least N bytes in length, where N is the parameter.
2429** ^If sqlite3_malloc() is unable to obtain sufficient free
2430** memory, it returns a NULL pointer.  ^If the parameter N to
2431** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2432** a NULL pointer.
2433**
2434** ^Calling sqlite3_free() with a pointer previously returned
2435** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2436** that it might be reused.  ^The sqlite3_free() routine is
2437** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2438** to sqlite3_free() is harmless.  After being freed, memory
2439** should neither be read nor written.  Even reading previously freed
2440** memory might result in a segmentation fault or other severe error.
2441** Memory corruption, a segmentation fault, or other severe error
2442** might result if sqlite3_free() is called with a non-NULL pointer that
2443** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2444**
2445** ^(The sqlite3_realloc() interface attempts to resize a
2446** prior memory allocation to be at least N bytes, where N is the
2447** second parameter.  The memory allocation to be resized is the first
2448** parameter.)^ ^ If the first parameter to sqlite3_realloc()
2449** is a NULL pointer then its behavior is identical to calling
2450** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2451** ^If the second parameter to sqlite3_realloc() is zero or
2452** negative then the behavior is exactly the same as calling
2453** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2454** ^sqlite3_realloc() returns a pointer to a memory allocation
2455** of at least N bytes in size or NULL if sufficient memory is unavailable.
2456** ^If M is the size of the prior allocation, then min(N,M) bytes
2457** of the prior allocation are copied into the beginning of buffer returned
2458** by sqlite3_realloc() and the prior allocation is freed.
2459** ^If sqlite3_realloc() returns NULL, then the prior allocation
2460** is not freed.
2461**
2462** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2463** is always aligned to at least an 8 byte boundary, or to a
2464** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2465** option is used.
2466**
2467** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2468** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2469** implementation of these routines to be omitted.  That capability
2470** is no longer provided.  Only built-in memory allocators can be used.
2471**
2472** Prior to SQLite version 3.7.10, the Windows OS interface layer called
2473** the system malloc() and free() directly when converting
2474** filenames between the UTF-8 encoding used by SQLite
2475** and whatever filename encoding is used by the particular Windows
2476** installation.  Memory allocation errors were detected, but
2477** they were reported back as [SQLITE_CANTOPEN] or
2478** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2479**
2480** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2481** must be either NULL or else pointers obtained from a prior
2482** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2483** not yet been released.
2484**
2485** The application must not read or write any part of
2486** a block of memory after it has been released using
2487** [sqlite3_free()] or [sqlite3_realloc()].
2488*/
2489SQLITE_API void *sqlite3_malloc(int);
2490SQLITE_API void *sqlite3_realloc(void*, int);
2491SQLITE_API void sqlite3_free(void*);
2492
2493/*
2494** CAPI3REF: Memory Allocator Statistics
2495**
2496** SQLite provides these two interfaces for reporting on the status
2497** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2498** routines, which form the built-in memory allocation subsystem.
2499**
2500** ^The [sqlite3_memory_used()] routine returns the number of bytes
2501** of memory currently outstanding (malloced but not freed).
2502** ^The [sqlite3_memory_highwater()] routine returns the maximum
2503** value of [sqlite3_memory_used()] since the high-water mark
2504** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2505** [sqlite3_memory_highwater()] include any overhead
2506** added by SQLite in its implementation of [sqlite3_malloc()],
2507** but not overhead added by the any underlying system library
2508** routines that [sqlite3_malloc()] may call.
2509**
2510** ^The memory high-water mark is reset to the current value of
2511** [sqlite3_memory_used()] if and only if the parameter to
2512** [sqlite3_memory_highwater()] is true.  ^The value returned
2513** by [sqlite3_memory_highwater(1)] is the high-water mark
2514** prior to the reset.
2515*/
2516SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2517SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2518
2519/*
2520** CAPI3REF: Pseudo-Random Number Generator
2521**
2522** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2523** select random [ROWID | ROWIDs] when inserting new records into a table that
2524** already uses the largest possible [ROWID].  The PRNG is also used for
2525** the build-in random() and randomblob() SQL functions.  This interface allows
2526** applications to access the same PRNG for other purposes.
2527**
2528** ^A call to this routine stores N bytes of randomness into buffer P.
2529** ^If N is less than one, then P can be a NULL pointer.
2530**
2531** ^If this routine has not been previously called or if the previous
2532** call had N less than one, then the PRNG is seeded using randomness
2533** obtained from the xRandomness method of the default [sqlite3_vfs] object.
2534** ^If the previous call to this routine had an N of 1 or more then
2535** the pseudo-randomness is generated
2536** internally and without recourse to the [sqlite3_vfs] xRandomness
2537** method.
2538*/
2539SQLITE_API void sqlite3_randomness(int N, void *P);
2540
2541/*
2542** CAPI3REF: Compile-Time Authorization Callbacks
2543**
2544** ^This routine registers an authorizer callback with a particular
2545** [database connection], supplied in the first argument.
2546** ^The authorizer callback is invoked as SQL statements are being compiled
2547** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2548** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2549** points during the compilation process, as logic is being created
2550** to perform various actions, the authorizer callback is invoked to
2551** see if those actions are allowed.  ^The authorizer callback should
2552** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2553** specific action but allow the SQL statement to continue to be
2554** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2555** rejected with an error.  ^If the authorizer callback returns
2556** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2557** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2558** the authorizer will fail with an error message.
2559**
2560** When the callback returns [SQLITE_OK], that means the operation
2561** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2562** [sqlite3_prepare_v2()] or equivalent call that triggered the
2563** authorizer will fail with an error message explaining that
2564** access is denied.
2565**
2566** ^The first parameter to the authorizer callback is a copy of the third
2567** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2568** to the callback is an integer [SQLITE_COPY | action code] that specifies
2569** the particular action to be authorized. ^The third through sixth parameters
2570** to the callback are zero-terminated strings that contain additional
2571** details about the action to be authorized.
2572**
2573** ^If the action code is [SQLITE_READ]
2574** and the callback returns [SQLITE_IGNORE] then the
2575** [prepared statement] statement is constructed to substitute
2576** a NULL value in place of the table column that would have
2577** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2578** return can be used to deny an untrusted user access to individual
2579** columns of a table.
2580** ^If the action code is [SQLITE_DELETE] and the callback returns
2581** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2582** [truncate optimization] is disabled and all rows are deleted individually.
2583**
2584** An authorizer is used when [sqlite3_prepare | preparing]
2585** SQL statements from an untrusted source, to ensure that the SQL statements
2586** do not try to access data they are not allowed to see, or that they do not
2587** try to execute malicious statements that damage the database.  For
2588** example, an application may allow a user to enter arbitrary
2589** SQL queries for evaluation by a database.  But the application does
2590** not want the user to be able to make arbitrary changes to the
2591** database.  An authorizer could then be put in place while the
2592** user-entered SQL is being [sqlite3_prepare | prepared] that
2593** disallows everything except [SELECT] statements.
2594**
2595** Applications that need to process SQL from untrusted sources
2596** might also consider lowering resource limits using [sqlite3_limit()]
2597** and limiting database size using the [max_page_count] [PRAGMA]
2598** in addition to using an authorizer.
2599**
2600** ^(Only a single authorizer can be in place on a database connection
2601** at a time.  Each call to sqlite3_set_authorizer overrides the
2602** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2603** The authorizer is disabled by default.
2604**
2605** The authorizer callback must not do anything that will modify
2606** the database connection that invoked the authorizer callback.
2607** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2608** database connections for the meaning of "modify" in this paragraph.
2609**
2610** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2611** statement might be re-prepared during [sqlite3_step()] due to a
2612** schema change.  Hence, the application should ensure that the
2613** correct authorizer callback remains in place during the [sqlite3_step()].
2614**
2615** ^Note that the authorizer callback is invoked only during
2616** [sqlite3_prepare()] or its variants.  Authorization is not
2617** performed during statement evaluation in [sqlite3_step()], unless
2618** as stated in the previous paragraph, sqlite3_step() invokes
2619** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2620*/
2621SQLITE_API int sqlite3_set_authorizer(
2622  sqlite3*,
2623  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2624  void *pUserData
2625);
2626
2627/*
2628** CAPI3REF: Authorizer Return Codes
2629**
2630** The [sqlite3_set_authorizer | authorizer callback function] must
2631** return either [SQLITE_OK] or one of these two constants in order
2632** to signal SQLite whether or not the action is permitted.  See the
2633** [sqlite3_set_authorizer | authorizer documentation] for additional
2634** information.
2635**
2636** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code]
2637** from the [sqlite3_vtab_on_conflict()] interface.
2638*/
2639#define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2640#define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2641
2642/*
2643** CAPI3REF: Authorizer Action Codes
2644**
2645** The [sqlite3_set_authorizer()] interface registers a callback function
2646** that is invoked to authorize certain SQL statement actions.  The
2647** second parameter to the callback is an integer code that specifies
2648** what action is being authorized.  These are the integer action codes that
2649** the authorizer callback may be passed.
2650**
2651** These action code values signify what kind of operation is to be
2652** authorized.  The 3rd and 4th parameters to the authorization
2653** callback function will be parameters or NULL depending on which of these
2654** codes is used as the second parameter.  ^(The 5th parameter to the
2655** authorizer callback is the name of the database ("main", "temp",
2656** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
2657** is the name of the inner-most trigger or view that is responsible for
2658** the access attempt or NULL if this access attempt is directly from
2659** top-level SQL code.
2660*/
2661/******************************************* 3rd ************ 4th ***********/
2662#define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2663#define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2664#define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2665#define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2666#define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2667#define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2668#define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2669#define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2670#define SQLITE_DELETE                9   /* Table Name      NULL            */
2671#define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2672#define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2673#define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2674#define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2675#define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2676#define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2677#define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2678#define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2679#define SQLITE_INSERT               18   /* Table Name      NULL            */
2680#define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2681#define SQLITE_READ                 20   /* Table Name      Column Name     */
2682#define SQLITE_SELECT               21   /* NULL            NULL            */
2683#define SQLITE_TRANSACTION          22   /* Operation       NULL            */
2684#define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2685#define SQLITE_ATTACH               24   /* Filename        NULL            */
2686#define SQLITE_DETACH               25   /* Database Name   NULL            */
2687#define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2688#define SQLITE_REINDEX              27   /* Index Name      NULL            */
2689#define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2690#define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2691#define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2692#define SQLITE_FUNCTION             31   /* NULL            Function Name   */
2693#define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
2694#define SQLITE_COPY                  0   /* No longer used */
2695#define SQLITE_RECURSIVE            33   /* NULL            NULL            */
2696
2697/*
2698** CAPI3REF: Tracing And Profiling Functions
2699**
2700** These routines register callback functions that can be used for
2701** tracing and profiling the execution of SQL statements.
2702**
2703** ^The callback function registered by sqlite3_trace() is invoked at
2704** various times when an SQL statement is being run by [sqlite3_step()].
2705** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
2706** SQL statement text as the statement first begins executing.
2707** ^(Additional sqlite3_trace() callbacks might occur
2708** as each triggered subprogram is entered.  The callbacks for triggers
2709** contain a UTF-8 SQL comment that identifies the trigger.)^
2710**
2711** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
2712** the length of [bound parameter] expansion in the output of sqlite3_trace().
2713**
2714** ^The callback function registered by sqlite3_profile() is invoked
2715** as each SQL statement finishes.  ^The profile callback contains
2716** the original statement text and an estimate of wall-clock time
2717** of how long that statement took to run.  ^The profile callback
2718** time is in units of nanoseconds, however the current implementation
2719** is only capable of millisecond resolution so the six least significant
2720** digits in the time are meaningless.  Future versions of SQLite
2721** might provide greater resolution on the profiler callback.  The
2722** sqlite3_profile() function is considered experimental and is
2723** subject to change in future versions of SQLite.
2724*/
2725SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2726SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2727   void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2728
2729/*
2730** CAPI3REF: Query Progress Callbacks
2731**
2732** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
2733** function X to be invoked periodically during long running calls to
2734** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
2735** database connection D.  An example use for this
2736** interface is to keep a GUI updated during a large query.
2737**
2738** ^The parameter P is passed through as the only parameter to the
2739** callback function X.  ^The parameter N is the approximate number of
2740** [virtual machine instructions] that are evaluated between successive
2741** invocations of the callback X.  ^If N is less than one then the progress
2742** handler is disabled.
2743**
2744** ^Only a single progress handler may be defined at one time per
2745** [database connection]; setting a new progress handler cancels the
2746** old one.  ^Setting parameter X to NULL disables the progress handler.
2747** ^The progress handler is also disabled by setting N to a value less
2748** than 1.
2749**
2750** ^If the progress callback returns non-zero, the operation is
2751** interrupted.  This feature can be used to implement a
2752** "Cancel" button on a GUI progress dialog box.
2753**
2754** The progress handler callback must not do anything that will modify
2755** the database connection that invoked the progress handler.
2756** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2757** database connections for the meaning of "modify" in this paragraph.
2758**
2759*/
2760SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2761
2762/*
2763** CAPI3REF: Opening A New Database Connection
2764**
2765** ^These routines open an SQLite database file as specified by the
2766** filename argument. ^The filename argument is interpreted as UTF-8 for
2767** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
2768** order for sqlite3_open16(). ^(A [database connection] handle is usually
2769** returned in *ppDb, even if an error occurs.  The only exception is that
2770** if SQLite is unable to allocate memory to hold the [sqlite3] object,
2771** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
2772** object.)^ ^(If the database is opened (and/or created) successfully, then
2773** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
2774** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
2775** an English language description of the error following a failure of any
2776** of the sqlite3_open() routines.
2777**
2778** ^The default encoding for the database will be UTF-8 if
2779** sqlite3_open() or sqlite3_open_v2() is called and
2780** UTF-16 in the native byte order if sqlite3_open16() is used.
2781**
2782** Whether or not an error occurs when it is opened, resources
2783** associated with the [database connection] handle should be released by
2784** passing it to [sqlite3_close()] when it is no longer required.
2785**
2786** The sqlite3_open_v2() interface works like sqlite3_open()
2787** except that it accepts two additional parameters for additional control
2788** over the new database connection.  ^(The flags parameter to
2789** sqlite3_open_v2() can take one of
2790** the following three values, optionally combined with the
2791** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
2792** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
2793**
2794** <dl>
2795** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
2796** <dd>The database is opened in read-only mode.  If the database does not
2797** already exist, an error is returned.</dd>)^
2798**
2799** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
2800** <dd>The database is opened for reading and writing if possible, or reading
2801** only if the file is write protected by the operating system.  In either
2802** case the database must already exist, otherwise an error is returned.</dd>)^
2803**
2804** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
2805** <dd>The database is opened for reading and writing, and is created if
2806** it does not already exist. This is the behavior that is always used for
2807** sqlite3_open() and sqlite3_open16().</dd>)^
2808** </dl>
2809**
2810** If the 3rd parameter to sqlite3_open_v2() is not one of the
2811** combinations shown above optionally combined with other
2812** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
2813** then the behavior is undefined.
2814**
2815** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
2816** opens in the multi-thread [threading mode] as long as the single-thread
2817** mode has not been set at compile-time or start-time.  ^If the
2818** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
2819** in the serialized [threading mode] unless single-thread was
2820** previously selected at compile-time or start-time.
2821** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
2822** eligible to use [shared cache mode], regardless of whether or not shared
2823** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
2824** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
2825** participate in [shared cache mode] even if it is enabled.
2826**
2827** ^The fourth parameter to sqlite3_open_v2() is the name of the
2828** [sqlite3_vfs] object that defines the operating system interface that
2829** the new database connection should use.  ^If the fourth parameter is
2830** a NULL pointer then the default [sqlite3_vfs] object is used.
2831**
2832** ^If the filename is ":memory:", then a private, temporary in-memory database
2833** is created for the connection.  ^This in-memory database will vanish when
2834** the database connection is closed.  Future versions of SQLite might
2835** make use of additional special filenames that begin with the ":" character.
2836** It is recommended that when a database filename actually does begin with
2837** a ":" character you should prefix the filename with a pathname such as
2838** "./" to avoid ambiguity.
2839**
2840** ^If the filename is an empty string, then a private, temporary
2841** on-disk database will be created.  ^This private database will be
2842** automatically deleted as soon as the database connection is closed.
2843**
2844** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
2845**
2846** ^If [URI filename] interpretation is enabled, and the filename argument
2847** begins with "file:", then the filename is interpreted as a URI. ^URI
2848** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
2849** set in the fourth argument to sqlite3_open_v2(), or if it has
2850** been enabled globally using the [SQLITE_CONFIG_URI] option with the
2851** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
2852** As of SQLite version 3.7.7, URI filename interpretation is turned off
2853** by default, but future releases of SQLite might enable URI filename
2854** interpretation by default.  See "[URI filenames]" for additional
2855** information.
2856**
2857** URI filenames are parsed according to RFC 3986. ^If the URI contains an
2858** authority, then it must be either an empty string or the string
2859** "localhost". ^If the authority is not an empty string or "localhost", an
2860** error is returned to the caller. ^The fragment component of a URI, if
2861** present, is ignored.
2862**
2863** ^SQLite uses the path component of the URI as the name of the disk file
2864** which contains the database. ^If the path begins with a '/' character,
2865** then it is interpreted as an absolute path. ^If the path does not begin
2866** with a '/' (meaning that the authority section is omitted from the URI)
2867** then the path is interpreted as a relative path.
2868** ^On windows, the first component of an absolute path
2869** is a drive specification (e.g. "C:").
2870**
2871** [[core URI query parameters]]
2872** The query component of a URI may contain parameters that are interpreted
2873** either by SQLite itself, or by a [VFS | custom VFS implementation].
2874** SQLite interprets the following three query parameters:
2875**
2876** <ul>
2877**   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
2878**     a VFS object that provides the operating system interface that should
2879**     be used to access the database file on disk. ^If this option is set to
2880**     an empty string the default VFS object is used. ^Specifying an unknown
2881**     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
2882**     present, then the VFS specified by the option takes precedence over
2883**     the value passed as the fourth parameter to sqlite3_open_v2().
2884**
2885**   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
2886**     "rwc", or "memory". Attempting to set it to any other value is
2887**     an error)^.
2888**     ^If "ro" is specified, then the database is opened for read-only
2889**     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
2890**     third argument to sqlite3_open_v2(). ^If the mode option is set to
2891**     "rw", then the database is opened for read-write (but not create)
2892**     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
2893**     been set. ^Value "rwc" is equivalent to setting both
2894**     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is
2895**     set to "memory" then a pure [in-memory database] that never reads
2896**     or writes from disk is used. ^It is an error to specify a value for
2897**     the mode parameter that is less restrictive than that specified by
2898**     the flags passed in the third parameter to sqlite3_open_v2().
2899**
2900**   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
2901**     "private". ^Setting it to "shared" is equivalent to setting the
2902**     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
2903**     sqlite3_open_v2(). ^Setting the cache parameter to "private" is
2904**     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
2905**     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
2906**     a URI filename, its value overrides any behavior requested by setting
2907**     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
2908**
2909**  <li> <b>psow</b>: ^The psow parameter may be "true" (or "on" or "yes" or
2910**     "1") or "false" (or "off" or "no" or "0") to indicate that the
2911**     [powersafe overwrite] property does or does not apply to the
2912**     storage media on which the database file resides.  ^The psow query
2913**     parameter only works for the built-in unix and Windows VFSes.
2914**
2915**  <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
2916**     which if set disables file locking in rollback journal modes.  This
2917**     is useful for accessing a database on a filesystem that does not
2918**     support locking.  Caution:  Database corruption might result if two
2919**     or more processes write to the same database and any one of those
2920**     processes uses nolock=1.
2921**
2922**  <li> <b>immutable</b>: ^The immutable parameter is a boolean query
2923**     parameter that indicates that the database file is stored on
2924**     read-only media.  ^When immutable is set, SQLite assumes that the
2925**     database file cannot be changed, even by a process with higher
2926**     privilege, and so the database is opened read-only and all locking
2927**     and change detection is disabled.  Caution: Setting the immutable
2928**     property on a database file that does in fact change can result
2929**     in incorrect query results and/or [SQLITE_CORRUPT] errors.
2930**     See also: [SQLITE_IOCAP_IMMUTABLE].
2931**
2932** </ul>
2933**
2934** ^Specifying an unknown parameter in the query component of a URI is not an
2935** error.  Future versions of SQLite might understand additional query
2936** parameters.  See "[query parameters with special meaning to SQLite]" for
2937** additional information.
2938**
2939** [[URI filename examples]] <h3>URI filename examples</h3>
2940**
2941** <table border="1" align=center cellpadding=5>
2942** <tr><th> URI filenames <th> Results
2943** <tr><td> file:data.db <td>
2944**          Open the file "data.db" in the current directory.
2945** <tr><td> file:/home/fred/data.db<br>
2946**          file:///home/fred/data.db <br>
2947**          file://localhost/home/fred/data.db <br> <td>
2948**          Open the database file "/home/fred/data.db".
2949** <tr><td> file://darkstar/home/fred/data.db <td>
2950**          An error. "darkstar" is not a recognized authority.
2951** <tr><td style="white-space:nowrap">
2952**          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
2953**     <td> Windows only: Open the file "data.db" on fred's desktop on drive
2954**          C:. Note that the %20 escaping in this example is not strictly
2955**          necessary - space characters can be used literally
2956**          in URI filenames.
2957** <tr><td> file:data.db?mode=ro&cache=private <td>
2958**          Open file "data.db" in the current directory for read-only access.
2959**          Regardless of whether or not shared-cache mode is enabled by
2960**          default, use a private cache.
2961** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
2962**          Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
2963**          that uses dot-files in place of posix advisory locking.
2964** <tr><td> file:data.db?mode=readonly <td>
2965**          An error. "readonly" is not a valid option for the "mode" parameter.
2966** </table>
2967**
2968** ^URI hexadecimal escape sequences (%HH) are supported within the path and
2969** query components of a URI. A hexadecimal escape sequence consists of a
2970** percent sign - "%" - followed by exactly two hexadecimal digits
2971** specifying an octet value. ^Before the path or query components of a
2972** URI filename are interpreted, they are encoded using UTF-8 and all
2973** hexadecimal escape sequences replaced by a single byte containing the
2974** corresponding octet. If this process generates an invalid UTF-8 encoding,
2975** the results are undefined.
2976**
2977** <b>Note to Windows users:</b>  The encoding used for the filename argument
2978** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
2979** codepage is currently defined.  Filenames containing international
2980** characters must be converted to UTF-8 prior to passing them into
2981** sqlite3_open() or sqlite3_open_v2().
2982**
2983** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
2984** prior to calling sqlite3_open() or sqlite3_open_v2().  Otherwise, various
2985** features that require the use of temporary files may fail.
2986**
2987** See also: [sqlite3_temp_directory]
2988*/
2989SQLITE_API int sqlite3_open(
2990  const char *filename,   /* Database filename (UTF-8) */
2991  sqlite3 **ppDb          /* OUT: SQLite db handle */
2992);
2993SQLITE_API int sqlite3_open16(
2994  const void *filename,   /* Database filename (UTF-16) */
2995  sqlite3 **ppDb          /* OUT: SQLite db handle */
2996);
2997SQLITE_API int sqlite3_open_v2(
2998  const char *filename,   /* Database filename (UTF-8) */
2999  sqlite3 **ppDb,         /* OUT: SQLite db handle */
3000  int flags,              /* Flags */
3001  const char *zVfs        /* Name of VFS module to use */
3002);
3003
3004/*
3005** CAPI3REF: Obtain Values For URI Parameters
3006**
3007** These are utility routines, useful to VFS implementations, that check
3008** to see if a database file was a URI that contained a specific query
3009** parameter, and if so obtains the value of that query parameter.
3010**
3011** If F is the database filename pointer passed into the xOpen() method of
3012** a VFS implementation when the flags parameter to xOpen() has one or
3013** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
3014** P is the name of the query parameter, then
3015** sqlite3_uri_parameter(F,P) returns the value of the P
3016** parameter if it exists or a NULL pointer if P does not appear as a
3017** query parameter on F.  If P is a query parameter of F
3018** has no explicit value, then sqlite3_uri_parameter(F,P) returns
3019** a pointer to an empty string.
3020**
3021** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
3022** parameter and returns true (1) or false (0) according to the value
3023** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
3024** value of query parameter P is one of "yes", "true", or "on" in any
3025** case or if the value begins with a non-zero number.  The
3026** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
3027** query parameter P is one of "no", "false", or "off" in any case or
3028** if the value begins with a numeric zero.  If P is not a query
3029** parameter on F or if the value of P is does not match any of the
3030** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
3031**
3032** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
3033** 64-bit signed integer and returns that integer, or D if P does not
3034** exist.  If the value of P is something other than an integer, then
3035** zero is returned.
3036**
3037** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
3038** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and
3039** is not a database file pathname pointer that SQLite passed into the xOpen
3040** VFS method, then the behavior of this routine is undefined and probably
3041** undesirable.
3042*/
3043SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
3044SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
3045SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
3046
3047
3048/*
3049** CAPI3REF: Error Codes And Messages
3050**
3051** ^The sqlite3_errcode() interface returns the numeric [result code] or
3052** [extended result code] for the most recent failed sqlite3_* API call
3053** associated with a [database connection]. If a prior API call failed
3054** but the most recent API call succeeded, the return value from
3055** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
3056** interface is the same except that it always returns the
3057** [extended result code] even when extended result codes are
3058** disabled.
3059**
3060** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
3061** text that describes the error, as either UTF-8 or UTF-16 respectively.
3062** ^(Memory to hold the error message string is managed internally.
3063** The application does not need to worry about freeing the result.
3064** However, the error string might be overwritten or deallocated by
3065** subsequent calls to other SQLite interface functions.)^
3066**
3067** ^The sqlite3_errstr() interface returns the English-language text
3068** that describes the [result code], as UTF-8.
3069** ^(Memory to hold the error message string is managed internally
3070** and must not be freed by the application)^.
3071**
3072** When the serialized [threading mode] is in use, it might be the
3073** case that a second error occurs on a separate thread in between
3074** the time of the first error and the call to these interfaces.
3075** When that happens, the second error will be reported since these
3076** interfaces always report the most recent result.  To avoid
3077** this, each thread can obtain exclusive use of the [database connection] D
3078** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
3079** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
3080** all calls to the interfaces listed here are completed.
3081**
3082** If an interface fails with SQLITE_MISUSE, that means the interface
3083** was invoked incorrectly by the application.  In that case, the
3084** error code and message may or may not be set.
3085*/
3086SQLITE_API int sqlite3_errcode(sqlite3 *db);
3087SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
3088SQLITE_API const char *sqlite3_errmsg(sqlite3*);
3089SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
3090SQLITE_API const char *sqlite3_errstr(int);
3091
3092/*
3093** CAPI3REF: SQL Statement Object
3094** KEYWORDS: {prepared statement} {prepared statements}
3095**
3096** An instance of this object represents a single SQL statement.
3097** This object is variously known as a "prepared statement" or a
3098** "compiled SQL statement" or simply as a "statement".
3099**
3100** The life of a statement object goes something like this:
3101**
3102** <ol>
3103** <li> Create the object using [sqlite3_prepare_v2()] or a related
3104**      function.
3105** <li> Bind values to [host parameters] using the sqlite3_bind_*()
3106**      interfaces.
3107** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3108** <li> Reset the statement using [sqlite3_reset()] then go back
3109**      to step 2.  Do this zero or more times.
3110** <li> Destroy the object using [sqlite3_finalize()].
3111** </ol>
3112**
3113** Refer to documentation on individual methods above for additional
3114** information.
3115*/
3116typedef struct sqlite3_stmt sqlite3_stmt;
3117
3118/*
3119** CAPI3REF: Run-time Limits
3120**
3121** ^(This interface allows the size of various constructs to be limited
3122** on a connection by connection basis.  The first parameter is the
3123** [database connection] whose limit is to be set or queried.  The
3124** second parameter is one of the [limit categories] that define a
3125** class of constructs to be size limited.  The third parameter is the
3126** new limit for that construct.)^
3127**
3128** ^If the new limit is a negative number, the limit is unchanged.
3129** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
3130** [limits | hard upper bound]
3131** set at compile-time by a C preprocessor macro called
3132** [limits | SQLITE_MAX_<i>NAME</i>].
3133** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3134** ^Attempts to increase a limit above its hard upper bound are
3135** silently truncated to the hard upper bound.
3136**
3137** ^Regardless of whether or not the limit was changed, the
3138** [sqlite3_limit()] interface returns the prior value of the limit.
3139** ^Hence, to find the current value of a limit without changing it,
3140** simply invoke this interface with the third parameter set to -1.
3141**
3142** Run-time limits are intended for use in applications that manage
3143** both their own internal database and also databases that are controlled
3144** by untrusted external sources.  An example application might be a
3145** web browser that has its own databases for storing history and
3146** separate databases controlled by JavaScript applications downloaded
3147** off the Internet.  The internal databases can be given the
3148** large, default limits.  Databases managed by external sources can
3149** be given much smaller limits designed to prevent a denial of service
3150** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
3151** interface to further control untrusted SQL.  The size of the database
3152** created by an untrusted script can be contained using the
3153** [max_page_count] [PRAGMA].
3154**
3155** New run-time limit categories may be added in future releases.
3156*/
3157SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
3158
3159/*
3160** CAPI3REF: Run-Time Limit Categories
3161** KEYWORDS: {limit category} {*limit categories}
3162**
3163** These constants define various performance limits
3164** that can be lowered at run-time using [sqlite3_limit()].
3165** The synopsis of the meanings of the various limits is shown below.
3166** Additional information is available at [limits | Limits in SQLite].
3167**
3168** <dl>
3169** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3170** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3171**
3172** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3173** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3174**
3175** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3176** <dd>The maximum number of columns in a table definition or in the
3177** result set of a [SELECT] or the maximum number of columns in an index
3178** or in an ORDER BY or GROUP BY clause.</dd>)^
3179**
3180** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3181** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3182**
3183** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3184** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3185**
3186** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3187** <dd>The maximum number of instructions in a virtual machine program
3188** used to implement an SQL statement.  This limit is not currently
3189** enforced, though that might be added in some future release of
3190** SQLite.</dd>)^
3191**
3192** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3193** <dd>The maximum number of arguments on a function.</dd>)^
3194**
3195** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3196** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3197**
3198** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
3199** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3200** <dd>The maximum length of the pattern argument to the [LIKE] or
3201** [GLOB] operators.</dd>)^
3202**
3203** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
3204** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3205** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3206**
3207** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3208** <dd>The maximum depth of recursion for triggers.</dd>)^
3209** </dl>
3210*/
3211#define SQLITE_LIMIT_LENGTH                    0
3212#define SQLITE_LIMIT_SQL_LENGTH                1
3213#define SQLITE_LIMIT_COLUMN                    2
3214#define SQLITE_LIMIT_EXPR_DEPTH                3
3215#define SQLITE_LIMIT_COMPOUND_SELECT           4
3216#define SQLITE_LIMIT_VDBE_OP                   5
3217#define SQLITE_LIMIT_FUNCTION_ARG              6
3218#define SQLITE_LIMIT_ATTACHED                  7
3219#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3220#define SQLITE_LIMIT_VARIABLE_NUMBER           9
3221#define SQLITE_LIMIT_TRIGGER_DEPTH            10
3222
3223/*
3224** CAPI3REF: Compiling An SQL Statement
3225** KEYWORDS: {SQL statement compiler}
3226**
3227** To execute an SQL query, it must first be compiled into a byte-code
3228** program using one of these routines.
3229**
3230** The first argument, "db", is a [database connection] obtained from a
3231** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3232** [sqlite3_open16()].  The database connection must not have been closed.
3233**
3234** The second argument, "zSql", is the statement to be compiled, encoded
3235** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3236** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3237** use UTF-16.
3238**
3239** ^If the nByte argument is less than zero, then zSql is read up to the
3240** first zero terminator. ^If nByte is non-negative, then it is the maximum
3241** number of  bytes read from zSql.  ^When nByte is non-negative, the
3242** zSql string ends at either the first '\000' or '\u0000' character or
3243** the nByte-th byte, whichever comes first. If the caller knows
3244** that the supplied string is nul-terminated, then there is a small
3245** performance advantage to be gained by passing an nByte parameter that
3246** is equal to the number of bytes in the input string <i>including</i>
3247** the nul-terminator bytes as this saves SQLite from having to
3248** make a copy of the input string.
3249**
3250** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3251** past the end of the first SQL statement in zSql.  These routines only
3252** compile the first statement in zSql, so *pzTail is left pointing to
3253** what remains uncompiled.
3254**
3255** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3256** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
3257** to NULL.  ^If the input text contains no SQL (if the input is an empty
3258** string or a comment) then *ppStmt is set to NULL.
3259** The calling procedure is responsible for deleting the compiled
3260** SQL statement using [sqlite3_finalize()] after it has finished with it.
3261** ppStmt may not be NULL.
3262**
3263** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3264** otherwise an [error code] is returned.
3265**
3266** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3267** recommended for all new programs. The two older interfaces are retained
3268** for backwards compatibility, but their use is discouraged.
3269** ^In the "v2" interfaces, the prepared statement
3270** that is returned (the [sqlite3_stmt] object) contains a copy of the
3271** original SQL text. This causes the [sqlite3_step()] interface to
3272** behave differently in three ways:
3273**
3274** <ol>
3275** <li>
3276** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3277** always used to do, [sqlite3_step()] will automatically recompile the SQL
3278** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
3279** retries will occur before sqlite3_step() gives up and returns an error.
3280** </li>
3281**
3282** <li>
3283** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3284** [error codes] or [extended error codes].  ^The legacy behavior was that
3285** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3286** and the application would have to make a second call to [sqlite3_reset()]
3287** in order to find the underlying cause of the problem. With the "v2" prepare
3288** interfaces, the underlying reason for the error is returned immediately.
3289** </li>
3290**
3291** <li>
3292** ^If the specific value bound to [parameter | host parameter] in the
3293** WHERE clause might influence the choice of query plan for a statement,
3294** then the statement will be automatically recompiled, as if there had been
3295** a schema change, on the first  [sqlite3_step()] call following any change
3296** to the [sqlite3_bind_text | bindings] of that [parameter].
3297** ^The specific value of WHERE-clause [parameter] might influence the
3298** choice of query plan if the parameter is the left-hand side of a [LIKE]
3299** or [GLOB] operator or if the parameter is compared to an indexed column
3300** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
3301** </li>
3302** </ol>
3303*/
3304SQLITE_API int sqlite3_prepare(
3305  sqlite3 *db,            /* Database handle */
3306  const char *zSql,       /* SQL statement, UTF-8 encoded */
3307  int nByte,              /* Maximum length of zSql in bytes. */
3308  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3309  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3310);
3311SQLITE_API int sqlite3_prepare_v2(
3312  sqlite3 *db,            /* Database handle */
3313  const char *zSql,       /* SQL statement, UTF-8 encoded */
3314  int nByte,              /* Maximum length of zSql in bytes. */
3315  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3316  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3317);
3318SQLITE_API int sqlite3_prepare16(
3319  sqlite3 *db,            /* Database handle */
3320  const void *zSql,       /* SQL statement, UTF-16 encoded */
3321  int nByte,              /* Maximum length of zSql in bytes. */
3322  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3323  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3324);
3325SQLITE_API int sqlite3_prepare16_v2(
3326  sqlite3 *db,            /* Database handle */
3327  const void *zSql,       /* SQL statement, UTF-16 encoded */
3328  int nByte,              /* Maximum length of zSql in bytes. */
3329  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3330  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3331);
3332
3333/*
3334** CAPI3REF: Retrieving Statement SQL
3335**
3336** ^This interface can be used to retrieve a saved copy of the original
3337** SQL text used to create a [prepared statement] if that statement was
3338** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3339*/
3340SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3341
3342/*
3343** CAPI3REF: Determine If An SQL Statement Writes The Database
3344**
3345** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3346** and only if the [prepared statement] X makes no direct changes to
3347** the content of the database file.
3348**
3349** Note that [application-defined SQL functions] or
3350** [virtual tables] might change the database indirectly as a side effect.
3351** ^(For example, if an application defines a function "eval()" that
3352** calls [sqlite3_exec()], then the following SQL statement would
3353** change the database file through side-effects:
3354**
3355** <blockquote><pre>
3356**    SELECT eval('DELETE FROM t1') FROM t2;
3357** </pre></blockquote>
3358**
3359** But because the [SELECT] statement does not change the database file
3360** directly, sqlite3_stmt_readonly() would still return true.)^
3361**
3362** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3363** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3364** since the statements themselves do not actually modify the database but
3365** rather they control the timing of when other statements modify the
3366** database.  ^The [ATTACH] and [DETACH] statements also cause
3367** sqlite3_stmt_readonly() to return true since, while those statements
3368** change the configuration of a database connection, they do not make
3369** changes to the content of the database files on disk.
3370*/
3371SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
3372
3373/*
3374** CAPI3REF: Determine If A Prepared Statement Has Been Reset
3375**
3376** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
3377** [prepared statement] S has been stepped at least once using
3378** [sqlite3_step(S)] but has not run to completion and/or has not
3379** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)
3380** interface returns false if S is a NULL pointer.  If S is not a
3381** NULL pointer and is not a pointer to a valid [prepared statement]
3382** object, then the behavior is undefined and probably undesirable.
3383**
3384** This interface can be used in combination [sqlite3_next_stmt()]
3385** to locate all prepared statements associated with a database
3386** connection that are in need of being reset.  This can be used,
3387** for example, in diagnostic routines to search for prepared
3388** statements that are holding a transaction open.
3389*/
3390SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
3391
3392/*
3393** CAPI3REF: Dynamically Typed Value Object
3394** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3395**
3396** SQLite uses the sqlite3_value object to represent all values
3397** that can be stored in a database table. SQLite uses dynamic typing
3398** for the values it stores.  ^Values stored in sqlite3_value objects
3399** can be integers, floating point values, strings, BLOBs, or NULL.
3400**
3401** An sqlite3_value object may be either "protected" or "unprotected".
3402** Some interfaces require a protected sqlite3_value.  Other interfaces
3403** will accept either a protected or an unprotected sqlite3_value.
3404** Every interface that accepts sqlite3_value arguments specifies
3405** whether or not it requires a protected sqlite3_value.
3406**
3407** The terms "protected" and "unprotected" refer to whether or not
3408** a mutex is held.  An internal mutex is held for a protected
3409** sqlite3_value object but no mutex is held for an unprotected
3410** sqlite3_value object.  If SQLite is compiled to be single-threaded
3411** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3412** or if SQLite is run in one of reduced mutex modes
3413** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3414** then there is no distinction between protected and unprotected
3415** sqlite3_value objects and they can be used interchangeably.  However,
3416** for maximum code portability it is recommended that applications
3417** still make the distinction between protected and unprotected
3418** sqlite3_value objects even when not strictly required.
3419**
3420** ^The sqlite3_value objects that are passed as parameters into the
3421** implementation of [application-defined SQL functions] are protected.
3422** ^The sqlite3_value object returned by
3423** [sqlite3_column_value()] is unprotected.
3424** Unprotected sqlite3_value objects may only be used with
3425** [sqlite3_result_value()] and [sqlite3_bind_value()].
3426** The [sqlite3_value_blob | sqlite3_value_type()] family of
3427** interfaces require protected sqlite3_value objects.
3428*/
3429typedef struct Mem sqlite3_value;
3430
3431/*
3432** CAPI3REF: SQL Function Context Object
3433**
3434** The context in which an SQL function executes is stored in an
3435** sqlite3_context object.  ^A pointer to an sqlite3_context object
3436** is always first parameter to [application-defined SQL functions].
3437** The application-defined SQL function implementation will pass this
3438** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3439** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3440** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3441** and/or [sqlite3_set_auxdata()].
3442*/
3443typedef struct sqlite3_context sqlite3_context;
3444
3445/*
3446** CAPI3REF: Binding Values To Prepared Statements
3447** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3448** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3449**
3450** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3451** literals may be replaced by a [parameter] that matches one of following
3452** templates:
3453**
3454** <ul>
3455** <li>  ?
3456** <li>  ?NNN
3457** <li>  :VVV
3458** <li>  @VVV
3459** <li>  $VVV
3460** </ul>
3461**
3462** In the templates above, NNN represents an integer literal,
3463** and VVV represents an alphanumeric identifier.)^  ^The values of these
3464** parameters (also called "host parameter names" or "SQL parameters")
3465** can be set using the sqlite3_bind_*() routines defined here.
3466**
3467** ^The first argument to the sqlite3_bind_*() routines is always
3468** a pointer to the [sqlite3_stmt] object returned from
3469** [sqlite3_prepare_v2()] or its variants.
3470**
3471** ^The second argument is the index of the SQL parameter to be set.
3472** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3473** SQL parameter is used more than once, second and subsequent
3474** occurrences have the same index as the first occurrence.
3475** ^The index for named parameters can be looked up using the
3476** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3477** for "?NNN" parameters is the value of NNN.
3478** ^The NNN value must be between 1 and the [sqlite3_limit()]
3479** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3480**
3481** ^The third argument is the value to bind to the parameter.
3482** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3483** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
3484** is ignored and the end result is the same as sqlite3_bind_null().
3485**
3486** ^(In those routines that have a fourth argument, its value is the
3487** number of bytes in the parameter.  To be clear: the value is the
3488** number of <u>bytes</u> in the value, not the number of characters.)^
3489** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3490** is negative, then the length of the string is
3491** the number of bytes up to the first zero terminator.
3492** If the fourth parameter to sqlite3_bind_blob() is negative, then
3493** the behavior is undefined.
3494** If a non-negative fourth parameter is provided to sqlite3_bind_text()
3495** or sqlite3_bind_text16() then that parameter must be the byte offset
3496** where the NUL terminator would occur assuming the string were NUL
3497** terminated.  If any NUL characters occur at byte offsets less than
3498** the value of the fourth parameter then the resulting string value will
3499** contain embedded NULs.  The result of expressions involving strings
3500** with embedded NULs is undefined.
3501**
3502** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3503** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3504** string after SQLite has finished with it.  ^The destructor is called
3505** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
3506** sqlite3_bind_text(), or sqlite3_bind_text16() fails.
3507** ^If the fifth argument is
3508** the special value [SQLITE_STATIC], then SQLite assumes that the
3509** information is in static, unmanaged space and does not need to be freed.
3510** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3511** SQLite makes its own private copy of the data immediately, before
3512** the sqlite3_bind_*() routine returns.
3513**
3514** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3515** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3516** (just an integer to hold its size) while it is being processed.
3517** Zeroblobs are intended to serve as placeholders for BLOBs whose
3518** content is later written using
3519** [sqlite3_blob_open | incremental BLOB I/O] routines.
3520** ^A negative value for the zeroblob results in a zero-length BLOB.
3521**
3522** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3523** for the [prepared statement] or with a prepared statement for which
3524** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3525** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
3526** routine is passed a [prepared statement] that has been finalized, the
3527** result is undefined and probably harmful.
3528**
3529** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3530** ^Unbound parameters are interpreted as NULL.
3531**
3532** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3533** [error code] if anything goes wrong.
3534** ^[SQLITE_RANGE] is returned if the parameter
3535** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
3536**
3537** See also: [sqlite3_bind_parameter_count()],
3538** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3539*/
3540SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3541SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3542SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3543SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3544SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3545SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3546SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3547SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3548SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3549
3550/*
3551** CAPI3REF: Number Of SQL Parameters
3552**
3553** ^This routine can be used to find the number of [SQL parameters]
3554** in a [prepared statement].  SQL parameters are tokens of the
3555** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3556** placeholders for values that are [sqlite3_bind_blob | bound]
3557** to the parameters at a later time.
3558**
3559** ^(This routine actually returns the index of the largest (rightmost)
3560** parameter. For all forms except ?NNN, this will correspond to the
3561** number of unique parameters.  If parameters of the ?NNN form are used,
3562** there may be gaps in the list.)^
3563**
3564** See also: [sqlite3_bind_blob|sqlite3_bind()],
3565** [sqlite3_bind_parameter_name()], and
3566** [sqlite3_bind_parameter_index()].
3567*/
3568SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3569
3570/*
3571** CAPI3REF: Name Of A Host Parameter
3572**
3573** ^The sqlite3_bind_parameter_name(P,N) interface returns
3574** the name of the N-th [SQL parameter] in the [prepared statement] P.
3575** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3576** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3577** respectively.
3578** In other words, the initial ":" or "$" or "@" or "?"
3579** is included as part of the name.)^
3580** ^Parameters of the form "?" without a following integer have no name
3581** and are referred to as "nameless" or "anonymous parameters".
3582**
3583** ^The first host parameter has an index of 1, not 0.
3584**
3585** ^If the value N is out of range or if the N-th parameter is
3586** nameless, then NULL is returned.  ^The returned string is
3587** always in UTF-8 encoding even if the named parameter was
3588** originally specified as UTF-16 in [sqlite3_prepare16()] or
3589** [sqlite3_prepare16_v2()].
3590**
3591** See also: [sqlite3_bind_blob|sqlite3_bind()],
3592** [sqlite3_bind_parameter_count()], and
3593** [sqlite3_bind_parameter_index()].
3594*/
3595SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3596
3597/*
3598** CAPI3REF: Index Of A Parameter With A Given Name
3599**
3600** ^Return the index of an SQL parameter given its name.  ^The
3601** index value returned is suitable for use as the second
3602** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
3603** is returned if no matching parameter is found.  ^The parameter
3604** name must be given in UTF-8 even if the original statement
3605** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3606**
3607** See also: [sqlite3_bind_blob|sqlite3_bind()],
3608** [sqlite3_bind_parameter_count()], and
3609** [sqlite3_bind_parameter_index()].
3610*/
3611SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3612
3613/*
3614** CAPI3REF: Reset All Bindings On A Prepared Statement
3615**
3616** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3617** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3618** ^Use this routine to reset all host parameters to NULL.
3619*/
3620SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3621
3622/*
3623** CAPI3REF: Number Of Columns In A Result Set
3624**
3625** ^Return the number of columns in the result set returned by the
3626** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3627** statement that does not return data (for example an [UPDATE]).
3628**
3629** See also: [sqlite3_data_count()]
3630*/
3631SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3632
3633/*
3634** CAPI3REF: Column Names In A Result Set
3635**
3636** ^These routines return the name assigned to a particular column
3637** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
3638** interface returns a pointer to a zero-terminated UTF-8 string
3639** and sqlite3_column_name16() returns a pointer to a zero-terminated
3640** UTF-16 string.  ^The first parameter is the [prepared statement]
3641** that implements the [SELECT] statement. ^The second parameter is the
3642** column number.  ^The leftmost column is number 0.
3643**
3644** ^The returned string pointer is valid until either the [prepared statement]
3645** is destroyed by [sqlite3_finalize()] or until the statement is automatically
3646** reprepared by the first call to [sqlite3_step()] for a particular run
3647** or until the next call to
3648** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3649**
3650** ^If sqlite3_malloc() fails during the processing of either routine
3651** (for example during a conversion from UTF-8 to UTF-16) then a
3652** NULL pointer is returned.
3653**
3654** ^The name of a result column is the value of the "AS" clause for
3655** that column, if there is an AS clause.  If there is no AS clause
3656** then the name of the column is unspecified and may change from
3657** one release of SQLite to the next.
3658*/
3659SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3660SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3661
3662/*
3663** CAPI3REF: Source Of Data In A Query Result
3664**
3665** ^These routines provide a means to determine the database, table, and
3666** table column that is the origin of a particular result column in
3667** [SELECT] statement.
3668** ^The name of the database or table or column can be returned as
3669** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
3670** the database name, the _table_ routines return the table name, and
3671** the origin_ routines return the column name.
3672** ^The returned string is valid until the [prepared statement] is destroyed
3673** using [sqlite3_finalize()] or until the statement is automatically
3674** reprepared by the first call to [sqlite3_step()] for a particular run
3675** or until the same information is requested
3676** again in a different encoding.
3677**
3678** ^The names returned are the original un-aliased names of the
3679** database, table, and column.
3680**
3681** ^The first argument to these interfaces is a [prepared statement].
3682** ^These functions return information about the Nth result column returned by
3683** the statement, where N is the second function argument.
3684** ^The left-most column is column 0 for these routines.
3685**
3686** ^If the Nth column returned by the statement is an expression or
3687** subquery and is not a column value, then all of these functions return
3688** NULL.  ^These routine might also return NULL if a memory allocation error
3689** occurs.  ^Otherwise, they return the name of the attached database, table,
3690** or column that query result column was extracted from.
3691**
3692** ^As with all other SQLite APIs, those whose names end with "16" return
3693** UTF-16 encoded strings and the other functions return UTF-8.
3694**
3695** ^These APIs are only available if the library was compiled with the
3696** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3697**
3698** If two or more threads call one or more of these routines against the same
3699** prepared statement and column at the same time then the results are
3700** undefined.
3701**
3702** If two or more threads call one or more
3703** [sqlite3_column_database_name | column metadata interfaces]
3704** for the same [prepared statement] and result column
3705** at the same time then the results are undefined.
3706*/
3707SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3708SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3709SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3710SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3711SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3712SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3713
3714/*
3715** CAPI3REF: Declared Datatype Of A Query Result
3716**
3717** ^(The first parameter is a [prepared statement].
3718** If this statement is a [SELECT] statement and the Nth column of the
3719** returned result set of that [SELECT] is a table column (not an
3720** expression or subquery) then the declared type of the table
3721** column is returned.)^  ^If the Nth column of the result set is an
3722** expression or subquery, then a NULL pointer is returned.
3723** ^The returned string is always UTF-8 encoded.
3724**
3725** ^(For example, given the database schema:
3726**
3727** CREATE TABLE t1(c1 VARIANT);
3728**
3729** and the following statement to be compiled:
3730**
3731** SELECT c1 + 1, c1 FROM t1;
3732**
3733** this routine would return the string "VARIANT" for the second result
3734** column (i==1), and a NULL pointer for the first result column (i==0).)^
3735**
3736** ^SQLite uses dynamic run-time typing.  ^So just because a column
3737** is declared to contain a particular type does not mean that the
3738** data stored in that column is of the declared type.  SQLite is
3739** strongly typed, but the typing is dynamic not static.  ^Type
3740** is associated with individual values, not with the containers
3741** used to hold those values.
3742*/
3743SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3744SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3745
3746/*
3747** CAPI3REF: Evaluate An SQL Statement
3748**
3749** After a [prepared statement] has been prepared using either
3750** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3751** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3752** must be called one or more times to evaluate the statement.
3753**
3754** The details of the behavior of the sqlite3_step() interface depend
3755** on whether the statement was prepared using the newer "v2" interface
3756** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3757** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
3758** new "v2" interface is recommended for new applications but the legacy
3759** interface will continue to be supported.
3760**
3761** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
3762** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3763** ^With the "v2" interface, any of the other [result codes] or
3764** [extended result codes] might be returned as well.
3765**
3766** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
3767** database locks it needs to do its job.  ^If the statement is a [COMMIT]
3768** or occurs outside of an explicit transaction, then you can retry the
3769** statement.  If the statement is not a [COMMIT] and occurs within an
3770** explicit transaction then you should rollback the transaction before
3771** continuing.
3772**
3773** ^[SQLITE_DONE] means that the statement has finished executing
3774** successfully.  sqlite3_step() should not be called again on this virtual
3775** machine without first calling [sqlite3_reset()] to reset the virtual
3776** machine back to its initial state.
3777**
3778** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
3779** is returned each time a new row of data is ready for processing by the
3780** caller. The values may be accessed using the [column access functions].
3781** sqlite3_step() is called again to retrieve the next row of data.
3782**
3783** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
3784** violation) has occurred.  sqlite3_step() should not be called again on
3785** the VM. More information may be found by calling [sqlite3_errmsg()].
3786** ^With the legacy interface, a more specific error code (for example,
3787** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
3788** can be obtained by calling [sqlite3_reset()] on the
3789** [prepared statement].  ^In the "v2" interface,
3790** the more specific error code is returned directly by sqlite3_step().
3791**
3792** [SQLITE_MISUSE] means that the this routine was called inappropriately.
3793** Perhaps it was called on a [prepared statement] that has
3794** already been [sqlite3_finalize | finalized] or on one that had
3795** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
3796** be the case that the same database connection is being used by two or
3797** more threads at the same moment in time.
3798**
3799** For all versions of SQLite up to and including 3.6.23.1, a call to
3800** [sqlite3_reset()] was required after sqlite3_step() returned anything
3801** other than [SQLITE_ROW] before any subsequent invocation of
3802** sqlite3_step().  Failure to reset the prepared statement using
3803** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
3804** sqlite3_step().  But after version 3.6.23.1, sqlite3_step() began
3805** calling [sqlite3_reset()] automatically in this circumstance rather
3806** than returning [SQLITE_MISUSE].  This is not considered a compatibility
3807** break because any application that ever receives an SQLITE_MISUSE error
3808** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
3809** can be used to restore the legacy behavior.
3810**
3811** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
3812** API always returns a generic error code, [SQLITE_ERROR], following any
3813** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
3814** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
3815** specific [error codes] that better describes the error.
3816** We admit that this is a goofy design.  The problem has been fixed
3817** with the "v2" interface.  If you prepare all of your SQL statements
3818** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
3819** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
3820** then the more specific [error codes] are returned directly
3821** by sqlite3_step().  The use of the "v2" interface is recommended.
3822*/
3823SQLITE_API int sqlite3_step(sqlite3_stmt*);
3824
3825/*
3826** CAPI3REF: Number of columns in a result set
3827**
3828** ^The sqlite3_data_count(P) interface returns the number of columns in the
3829** current row of the result set of [prepared statement] P.
3830** ^If prepared statement P does not have results ready to return
3831** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
3832** interfaces) then sqlite3_data_count(P) returns 0.
3833** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
3834** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
3835** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)
3836** will return non-zero if previous call to [sqlite3_step](P) returned
3837** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
3838** where it always returns zero since each step of that multi-step
3839** pragma returns 0 columns of data.
3840**
3841** See also: [sqlite3_column_count()]
3842*/
3843SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
3844
3845/*
3846** CAPI3REF: Fundamental Datatypes
3847** KEYWORDS: SQLITE_TEXT
3848**
3849** ^(Every value in SQLite has one of five fundamental datatypes:
3850**
3851** <ul>
3852** <li> 64-bit signed integer
3853** <li> 64-bit IEEE floating point number
3854** <li> string
3855** <li> BLOB
3856** <li> NULL
3857** </ul>)^
3858**
3859** These constants are codes for each of those types.
3860**
3861** Note that the SQLITE_TEXT constant was also used in SQLite version 2
3862** for a completely different meaning.  Software that links against both
3863** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
3864** SQLITE_TEXT.
3865*/
3866#define SQLITE_INTEGER  1
3867#define SQLITE_FLOAT    2
3868#define SQLITE_BLOB     4
3869#define SQLITE_NULL     5
3870#ifdef SQLITE_TEXT
3871# undef SQLITE_TEXT
3872#else
3873# define SQLITE_TEXT     3
3874#endif
3875#define SQLITE3_TEXT     3
3876
3877/*
3878** CAPI3REF: Result Values From A Query
3879** KEYWORDS: {column access functions}
3880**
3881** These routines form the "result set" interface.
3882**
3883** ^These routines return information about a single column of the current
3884** result row of a query.  ^In every case the first argument is a pointer
3885** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
3886** that was returned from [sqlite3_prepare_v2()] or one of its variants)
3887** and the second argument is the index of the column for which information
3888** should be returned. ^The leftmost column of the result set has the index 0.
3889** ^The number of columns in the result can be determined using
3890** [sqlite3_column_count()].
3891**
3892** If the SQL statement does not currently point to a valid row, or if the
3893** column index is out of range, the result is undefined.
3894** These routines may only be called when the most recent call to
3895** [sqlite3_step()] has returned [SQLITE_ROW] and neither
3896** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
3897** If any of these routines are called after [sqlite3_reset()] or
3898** [sqlite3_finalize()] or after [sqlite3_step()] has returned
3899** something other than [SQLITE_ROW], the results are undefined.
3900** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
3901** are called from a different thread while any of these routines
3902** are pending, then the results are undefined.
3903**
3904** ^The sqlite3_column_type() routine returns the
3905** [SQLITE_INTEGER | datatype code] for the initial data type
3906** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
3907** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
3908** returned by sqlite3_column_type() is only meaningful if no type
3909** conversions have occurred as described below.  After a type conversion,
3910** the value returned by sqlite3_column_type() is undefined.  Future
3911** versions of SQLite may change the behavior of sqlite3_column_type()
3912** following a type conversion.
3913**
3914** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
3915** routine returns the number of bytes in that BLOB or string.
3916** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
3917** the string to UTF-8 and then returns the number of bytes.
3918** ^If the result is a numeric value then sqlite3_column_bytes() uses
3919** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
3920** the number of bytes in that string.
3921** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
3922**
3923** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
3924** routine returns the number of bytes in that BLOB or string.
3925** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
3926** the string to UTF-16 and then returns the number of bytes.
3927** ^If the result is a numeric value then sqlite3_column_bytes16() uses
3928** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
3929** the number of bytes in that string.
3930** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
3931**
3932** ^The values returned by [sqlite3_column_bytes()] and
3933** [sqlite3_column_bytes16()] do not include the zero terminators at the end
3934** of the string.  ^For clarity: the values returned by
3935** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
3936** bytes in the string, not the number of characters.
3937**
3938** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
3939** even empty strings, are always zero-terminated.  ^The return
3940** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
3941**
3942** ^The object returned by [sqlite3_column_value()] is an
3943** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
3944** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
3945** If the [unprotected sqlite3_value] object returned by
3946** [sqlite3_column_value()] is used in any other way, including calls
3947** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
3948** or [sqlite3_value_bytes()], then the behavior is undefined.
3949**
3950** These routines attempt to convert the value where appropriate.  ^For
3951** example, if the internal representation is FLOAT and a text result
3952** is requested, [sqlite3_snprintf()] is used internally to perform the
3953** conversion automatically.  ^(The following table details the conversions
3954** that are applied:
3955**
3956** <blockquote>
3957** <table border="1">
3958** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
3959**
3960** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
3961** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
3962** <tr><td>  NULL    <td>   TEXT    <td> Result is a NULL pointer
3963** <tr><td>  NULL    <td>   BLOB    <td> Result is a NULL pointer
3964** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
3965** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
3966** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
3967** <tr><td>  FLOAT   <td> INTEGER   <td> [CAST] to INTEGER
3968** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
3969** <tr><td>  FLOAT   <td>   BLOB    <td> [CAST] to BLOB
3970** <tr><td>  TEXT    <td> INTEGER   <td> [CAST] to INTEGER
3971** <tr><td>  TEXT    <td>  FLOAT    <td> [CAST] to REAL
3972** <tr><td>  TEXT    <td>   BLOB    <td> No change
3973** <tr><td>  BLOB    <td> INTEGER   <td> [CAST] to INTEGER
3974** <tr><td>  BLOB    <td>  FLOAT    <td> [CAST] to REAL
3975** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
3976** </table>
3977** </blockquote>)^
3978**
3979** The table above makes reference to standard C library functions atoi()
3980** and atof().  SQLite does not really use these functions.  It has its
3981** own equivalent internal routines.  The atoi() and atof() names are
3982** used in the table for brevity and because they are familiar to most
3983** C programmers.
3984**
3985** Note that when type conversions occur, pointers returned by prior
3986** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
3987** sqlite3_column_text16() may be invalidated.
3988** Type conversions and pointer invalidations might occur
3989** in the following cases:
3990**
3991** <ul>
3992** <li> The initial content is a BLOB and sqlite3_column_text() or
3993**      sqlite3_column_text16() is called.  A zero-terminator might
3994**      need to be added to the string.</li>
3995** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
3996**      sqlite3_column_text16() is called.  The content must be converted
3997**      to UTF-16.</li>
3998** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
3999**      sqlite3_column_text() is called.  The content must be converted
4000**      to UTF-8.</li>
4001** </ul>
4002**
4003** ^Conversions between UTF-16be and UTF-16le are always done in place and do
4004** not invalidate a prior pointer, though of course the content of the buffer
4005** that the prior pointer references will have been modified.  Other kinds
4006** of conversion are done in place when it is possible, but sometimes they
4007** are not possible and in those cases prior pointers are invalidated.
4008**
4009** The safest and easiest to remember policy is to invoke these routines
4010** in one of the following ways:
4011**
4012** <ul>
4013**  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
4014**  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
4015**  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
4016** </ul>
4017**
4018** In other words, you should call sqlite3_column_text(),
4019** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
4020** into the desired format, then invoke sqlite3_column_bytes() or
4021** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
4022** to sqlite3_column_text() or sqlite3_column_blob() with calls to
4023** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
4024** with calls to sqlite3_column_bytes().
4025**
4026** ^The pointers returned are valid until a type conversion occurs as
4027** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
4028** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
4029** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
4030** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
4031** [sqlite3_free()].
4032**
4033** ^(If a memory allocation error occurs during the evaluation of any
4034** of these routines, a default value is returned.  The default value
4035** is either the integer 0, the floating point number 0.0, or a NULL
4036** pointer.  Subsequent calls to [sqlite3_errcode()] will return
4037** [SQLITE_NOMEM].)^
4038*/
4039SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
4040SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
4041SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
4042SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
4043SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
4044SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
4045SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
4046SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
4047SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
4048SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
4049
4050/*
4051** CAPI3REF: Destroy A Prepared Statement Object
4052**
4053** ^The sqlite3_finalize() function is called to delete a [prepared statement].
4054** ^If the most recent evaluation of the statement encountered no errors
4055** or if the statement is never been evaluated, then sqlite3_finalize() returns
4056** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
4057** sqlite3_finalize(S) returns the appropriate [error code] or
4058** [extended error code].
4059**
4060** ^The sqlite3_finalize(S) routine can be called at any point during
4061** the life cycle of [prepared statement] S:
4062** before statement S is ever evaluated, after
4063** one or more calls to [sqlite3_reset()], or after any call
4064** to [sqlite3_step()] regardless of whether or not the statement has
4065** completed execution.
4066**
4067** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
4068**
4069** The application must finalize every [prepared statement] in order to avoid
4070** resource leaks.  It is a grievous error for the application to try to use
4071** a prepared statement after it has been finalized.  Any use of a prepared
4072** statement after it has been finalized can result in undefined and
4073** undesirable behavior such as segfaults and heap corruption.
4074*/
4075SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
4076
4077/*
4078** CAPI3REF: Reset A Prepared Statement Object
4079**
4080** The sqlite3_reset() function is called to reset a [prepared statement]
4081** object back to its initial state, ready to be re-executed.
4082** ^Any SQL statement variables that had values bound to them using
4083** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
4084** Use [sqlite3_clear_bindings()] to reset the bindings.
4085**
4086** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
4087** back to the beginning of its program.
4088**
4089** ^If the most recent call to [sqlite3_step(S)] for the
4090** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
4091** or if [sqlite3_step(S)] has never before been called on S,
4092** then [sqlite3_reset(S)] returns [SQLITE_OK].
4093**
4094** ^If the most recent call to [sqlite3_step(S)] for the
4095** [prepared statement] S indicated an error, then
4096** [sqlite3_reset(S)] returns an appropriate [error code].
4097**
4098** ^The [sqlite3_reset(S)] interface does not change the values
4099** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
4100*/
4101SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
4102
4103/*
4104** CAPI3REF: Create Or Redefine SQL Functions
4105** KEYWORDS: {function creation routines}
4106** KEYWORDS: {application-defined SQL function}
4107** KEYWORDS: {application-defined SQL functions}
4108**
4109** ^These functions (collectively known as "function creation routines")
4110** are used to add SQL functions or aggregates or to redefine the behavior
4111** of existing SQL functions or aggregates.  The only differences between
4112** these routines are the text encoding expected for
4113** the second parameter (the name of the function being created)
4114** and the presence or absence of a destructor callback for
4115** the application data pointer.
4116**
4117** ^The first parameter is the [database connection] to which the SQL
4118** function is to be added.  ^If an application uses more than one database
4119** connection then application-defined SQL functions must be added
4120** to each database connection separately.
4121**
4122** ^The second parameter is the name of the SQL function to be created or
4123** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
4124** representation, exclusive of the zero-terminator.  ^Note that the name
4125** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
4126** ^Any attempt to create a function with a longer name
4127** will result in [SQLITE_MISUSE] being returned.
4128**
4129** ^The third parameter (nArg)
4130** is the number of arguments that the SQL function or
4131** aggregate takes. ^If this parameter is -1, then the SQL function or
4132** aggregate may take any number of arguments between 0 and the limit
4133** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
4134** parameter is less than -1 or greater than 127 then the behavior is
4135** undefined.
4136**
4137** ^The fourth parameter, eTextRep, specifies what
4138** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4139** its parameters.  The application should set this parameter to
4140** [SQLITE_UTF16LE] if the function implementation invokes
4141** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
4142** implementation invokes [sqlite3_value_text16be()] on an input, or
4143** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
4144** otherwise.  ^The same SQL function may be registered multiple times using
4145** different preferred text encodings, with different implementations for
4146** each encoding.
4147** ^When multiple implementations of the same function are available, SQLite
4148** will pick the one that involves the least amount of data conversion.
4149**
4150** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
4151** to signal that the function will always return the same result given
4152** the same inputs within a single SQL statement.  Most SQL functions are
4153** deterministic.  The built-in [random()] SQL function is an example of a
4154** function that is not deterministic.  The SQLite query planner is able to
4155** perform additional optimizations on deterministic functions, so use
4156** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
4157**
4158** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
4159** function can gain access to this pointer using [sqlite3_user_data()].)^
4160**
4161** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4162** pointers to C-language functions that implement the SQL function or
4163** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4164** callback only; NULL pointers must be passed as the xStep and xFinal
4165** parameters. ^An aggregate SQL function requires an implementation of xStep
4166** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4167** SQL function or aggregate, pass NULL pointers for all three function
4168** callbacks.
4169**
4170** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
4171** then it is destructor for the application data pointer.
4172** The destructor is invoked when the function is deleted, either by being
4173** overloaded or when the database connection closes.)^
4174** ^The destructor is also invoked if the call to
4175** sqlite3_create_function_v2() fails.
4176** ^When the destructor callback of the tenth parameter is invoked, it
4177** is passed a single argument which is a copy of the application data
4178** pointer which was the fifth parameter to sqlite3_create_function_v2().
4179**
4180** ^It is permitted to register multiple implementations of the same
4181** functions with the same name but with either differing numbers of
4182** arguments or differing preferred text encodings.  ^SQLite will use
4183** the implementation that most closely matches the way in which the
4184** SQL function is used.  ^A function implementation with a non-negative
4185** nArg parameter is a better match than a function implementation with
4186** a negative nArg.  ^A function where the preferred text encoding
4187** matches the database encoding is a better
4188** match than a function where the encoding is different.
4189** ^A function where the encoding difference is between UTF16le and UTF16be
4190** is a closer match than a function where the encoding difference is
4191** between UTF8 and UTF16.
4192**
4193** ^Built-in functions may be overloaded by new application-defined functions.
4194**
4195** ^An application-defined function is permitted to call other
4196** SQLite interfaces.  However, such calls must not
4197** close the database connection nor finalize or reset the prepared
4198** statement in which the function is running.
4199*/
4200SQLITE_API int sqlite3_create_function(
4201  sqlite3 *db,
4202  const char *zFunctionName,
4203  int nArg,
4204  int eTextRep,
4205  void *pApp,
4206  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4207  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4208  void (*xFinal)(sqlite3_context*)
4209);
4210SQLITE_API int sqlite3_create_function16(
4211  sqlite3 *db,
4212  const void *zFunctionName,
4213  int nArg,
4214  int eTextRep,
4215  void *pApp,
4216  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4217  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4218  void (*xFinal)(sqlite3_context*)
4219);
4220SQLITE_API int sqlite3_create_function_v2(
4221  sqlite3 *db,
4222  const char *zFunctionName,
4223  int nArg,
4224  int eTextRep,
4225  void *pApp,
4226  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4227  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4228  void (*xFinal)(sqlite3_context*),
4229  void(*xDestroy)(void*)
4230);
4231
4232/*
4233** CAPI3REF: Text Encodings
4234**
4235** These constant define integer codes that represent the various
4236** text encodings supported by SQLite.
4237*/
4238#define SQLITE_UTF8           1
4239#define SQLITE_UTF16LE        2
4240#define SQLITE_UTF16BE        3
4241#define SQLITE_UTF16          4    /* Use native byte order */
4242#define SQLITE_ANY            5    /* Deprecated */
4243#define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
4244
4245/*
4246** CAPI3REF: Function Flags
4247**
4248** These constants may be ORed together with the
4249** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
4250** to [sqlite3_create_function()], [sqlite3_create_function16()], or
4251** [sqlite3_create_function_v2()].
4252*/
4253#define SQLITE_DETERMINISTIC    0x800
4254
4255/*
4256** CAPI3REF: Deprecated Functions
4257** DEPRECATED
4258**
4259** These functions are [deprecated].  In order to maintain
4260** backwards compatibility with older code, these functions continue
4261** to be supported.  However, new applications should avoid
4262** the use of these functions.  To help encourage people to avoid
4263** using these functions, we are not going to tell you what they do.
4264*/
4265#ifndef SQLITE_OMIT_DEPRECATED
4266SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
4267SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
4268SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4269SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
4270SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
4271SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
4272                      void*,sqlite3_int64);
4273#endif
4274
4275/*
4276** CAPI3REF: Obtaining SQL Function Parameter Values
4277**
4278** The C-language implementation of SQL functions and aggregates uses
4279** this set of interface routines to access the parameter values on
4280** the function or aggregate.
4281**
4282** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4283** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4284** define callbacks that implement the SQL functions and aggregates.
4285** The 3rd parameter to these callbacks is an array of pointers to
4286** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
4287** each parameter to the SQL function.  These routines are used to
4288** extract values from the [sqlite3_value] objects.
4289**
4290** These routines work only with [protected sqlite3_value] objects.
4291** Any attempt to use these routines on an [unprotected sqlite3_value]
4292** object results in undefined behavior.
4293**
4294** ^These routines work just like the corresponding [column access functions]
4295** except that  these routines take a single [protected sqlite3_value] object
4296** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4297**
4298** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4299** in the native byte-order of the host machine.  ^The
4300** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4301** extract UTF-16 strings as big-endian and little-endian respectively.
4302**
4303** ^(The sqlite3_value_numeric_type() interface attempts to apply
4304** numeric affinity to the value.  This means that an attempt is
4305** made to convert the value to an integer or floating point.  If
4306** such a conversion is possible without loss of information (in other
4307** words, if the value is a string that looks like a number)
4308** then the conversion is performed.  Otherwise no conversion occurs.
4309** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4310**
4311** Please pay particular attention to the fact that the pointer returned
4312** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4313** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4314** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4315** or [sqlite3_value_text16()].
4316**
4317** These routines must be called from the same thread as
4318** the SQL function that supplied the [sqlite3_value*] parameters.
4319*/
4320SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4321SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4322SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4323SQLITE_API double sqlite3_value_double(sqlite3_value*);
4324SQLITE_API int sqlite3_value_int(sqlite3_value*);
4325SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4326SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4327SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4328SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4329SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4330SQLITE_API int sqlite3_value_type(sqlite3_value*);
4331SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4332
4333/*
4334** CAPI3REF: Obtain Aggregate Function Context
4335**
4336** Implementations of aggregate SQL functions use this
4337** routine to allocate memory for storing their state.
4338**
4339** ^The first time the sqlite3_aggregate_context(C,N) routine is called
4340** for a particular aggregate function, SQLite
4341** allocates N of memory, zeroes out that memory, and returns a pointer
4342** to the new memory. ^On second and subsequent calls to
4343** sqlite3_aggregate_context() for the same aggregate function instance,
4344** the same buffer is returned.  Sqlite3_aggregate_context() is normally
4345** called once for each invocation of the xStep callback and then one
4346** last time when the xFinal callback is invoked.  ^(When no rows match
4347** an aggregate query, the xStep() callback of the aggregate function
4348** implementation is never called and xFinal() is called exactly once.
4349** In those cases, sqlite3_aggregate_context() might be called for the
4350** first time from within xFinal().)^
4351**
4352** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
4353** when first called if N is less than or equal to zero or if a memory
4354** allocate error occurs.
4355**
4356** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4357** determined by the N parameter on first successful call.  Changing the
4358** value of N in subsequent call to sqlite3_aggregate_context() within
4359** the same aggregate function instance will not resize the memory
4360** allocation.)^  Within the xFinal callback, it is customary to set
4361** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
4362** pointless memory allocations occur.
4363**
4364** ^SQLite automatically frees the memory allocated by
4365** sqlite3_aggregate_context() when the aggregate query concludes.
4366**
4367** The first parameter must be a copy of the
4368** [sqlite3_context | SQL function context] that is the first parameter
4369** to the xStep or xFinal callback routine that implements the aggregate
4370** function.
4371**
4372** This routine must be called from the same thread in which
4373** the aggregate SQL function is running.
4374*/
4375SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4376
4377/*
4378** CAPI3REF: User Data For Functions
4379**
4380** ^The sqlite3_user_data() interface returns a copy of
4381** the pointer that was the pUserData parameter (the 5th parameter)
4382** of the [sqlite3_create_function()]
4383** and [sqlite3_create_function16()] routines that originally
4384** registered the application defined function.
4385**
4386** This routine must be called from the same thread in which
4387** the application-defined function is running.
4388*/
4389SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4390
4391/*
4392** CAPI3REF: Database Connection For Functions
4393**
4394** ^The sqlite3_context_db_handle() interface returns a copy of
4395** the pointer to the [database connection] (the 1st parameter)
4396** of the [sqlite3_create_function()]
4397** and [sqlite3_create_function16()] routines that originally
4398** registered the application defined function.
4399*/
4400SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4401
4402/*
4403** CAPI3REF: Function Auxiliary Data
4404**
4405** These functions may be used by (non-aggregate) SQL functions to
4406** associate metadata with argument values. If the same value is passed to
4407** multiple invocations of the same SQL function during query execution, under
4408** some circumstances the associated metadata may be preserved.  An example
4409** of where this might be useful is in a regular-expression matching
4410** function. The compiled version of the regular expression can be stored as
4411** metadata associated with the pattern string.
4412** Then as long as the pattern string remains the same,
4413** the compiled regular expression can be reused on multiple
4414** invocations of the same function.
4415**
4416** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4417** associated by the sqlite3_set_auxdata() function with the Nth argument
4418** value to the application-defined function. ^If there is no metadata
4419** associated with the function argument, this sqlite3_get_auxdata() interface
4420** returns a NULL pointer.
4421**
4422** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
4423** argument of the application-defined function.  ^Subsequent
4424** calls to sqlite3_get_auxdata(C,N) return P from the most recent
4425** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
4426** NULL if the metadata has been discarded.
4427** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
4428** SQLite will invoke the destructor function X with parameter P exactly
4429** once, when the metadata is discarded.
4430** SQLite is free to discard the metadata at any time, including: <ul>
4431** <li> when the corresponding function parameter changes, or
4432** <li> when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
4433**      SQL statement, or
4434** <li> when sqlite3_set_auxdata() is invoked again on the same parameter, or
4435** <li> during the original sqlite3_set_auxdata() call when a memory
4436**      allocation error occurs. </ul>)^
4437**
4438** Note the last bullet in particular.  The destructor X in
4439** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
4440** sqlite3_set_auxdata() interface even returns.  Hence sqlite3_set_auxdata()
4441** should be called near the end of the function implementation and the
4442** function implementation should not make any use of P after
4443** sqlite3_set_auxdata() has been called.
4444**
4445** ^(In practice, metadata is preserved between function calls for
4446** function parameters that are compile-time constants, including literal
4447** values and [parameters] and expressions composed from the same.)^
4448**
4449** These routines must be called from the same thread in which
4450** the SQL function is running.
4451*/
4452SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4453SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4454
4455
4456/*
4457** CAPI3REF: Constants Defining Special Destructor Behavior
4458**
4459** These are special values for the destructor that is passed in as the
4460** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
4461** argument is SQLITE_STATIC, it means that the content pointer is constant
4462** and will never change.  It does not need to be destroyed.  ^The
4463** SQLITE_TRANSIENT value means that the content will likely change in
4464** the near future and that SQLite should make its own private copy of
4465** the content before returning.
4466**
4467** The typedef is necessary to work around problems in certain
4468** C++ compilers.
4469*/
4470typedef void (*sqlite3_destructor_type)(void*);
4471#define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4472#define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4473
4474/*
4475** CAPI3REF: Setting The Result Of An SQL Function
4476**
4477** These routines are used by the xFunc or xFinal callbacks that
4478** implement SQL functions and aggregates.  See
4479** [sqlite3_create_function()] and [sqlite3_create_function16()]
4480** for additional information.
4481**
4482** These functions work very much like the [parameter binding] family of
4483** functions used to bind values to host parameters in prepared statements.
4484** Refer to the [SQL parameter] documentation for additional information.
4485**
4486** ^The sqlite3_result_blob() interface sets the result from
4487** an application-defined function to be the BLOB whose content is pointed
4488** to by the second parameter and which is N bytes long where N is the
4489** third parameter.
4490**
4491** ^The sqlite3_result_zeroblob() interfaces set the result of
4492** the application-defined function to be a BLOB containing all zero
4493** bytes and N bytes in size, where N is the value of the 2nd parameter.
4494**
4495** ^The sqlite3_result_double() interface sets the result from
4496** an application-defined function to be a floating point value specified
4497** by its 2nd argument.
4498**
4499** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4500** cause the implemented SQL function to throw an exception.
4501** ^SQLite uses the string pointed to by the
4502** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4503** as the text of an error message.  ^SQLite interprets the error
4504** message string from sqlite3_result_error() as UTF-8. ^SQLite
4505** interprets the string from sqlite3_result_error16() as UTF-16 in native
4506** byte order.  ^If the third parameter to sqlite3_result_error()
4507** or sqlite3_result_error16() is negative then SQLite takes as the error
4508** message all text up through the first zero character.
4509** ^If the third parameter to sqlite3_result_error() or
4510** sqlite3_result_error16() is non-negative then SQLite takes that many
4511** bytes (not characters) from the 2nd parameter as the error message.
4512** ^The sqlite3_result_error() and sqlite3_result_error16()
4513** routines make a private copy of the error message text before
4514** they return.  Hence, the calling function can deallocate or
4515** modify the text after they return without harm.
4516** ^The sqlite3_result_error_code() function changes the error code
4517** returned by SQLite as a result of an error in a function.  ^By default,
4518** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
4519** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4520**
4521** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
4522** error indicating that a string or BLOB is too long to represent.
4523**
4524** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
4525** error indicating that a memory allocation failed.
4526**
4527** ^The sqlite3_result_int() interface sets the return value
4528** of the application-defined function to be the 32-bit signed integer
4529** value given in the 2nd argument.
4530** ^The sqlite3_result_int64() interface sets the return value
4531** of the application-defined function to be the 64-bit signed integer
4532** value given in the 2nd argument.
4533**
4534** ^The sqlite3_result_null() interface sets the return value
4535** of the application-defined function to be NULL.
4536**
4537** ^The sqlite3_result_text(), sqlite3_result_text16(),
4538** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4539** set the return value of the application-defined function to be
4540** a text string which is represented as UTF-8, UTF-16 native byte order,
4541** UTF-16 little endian, or UTF-16 big endian, respectively.
4542** ^SQLite takes the text result from the application from
4543** the 2nd parameter of the sqlite3_result_text* interfaces.
4544** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4545** is negative, then SQLite takes result text from the 2nd parameter
4546** through the first zero character.
4547** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4548** is non-negative, then as many bytes (not characters) of the text
4549** pointed to by the 2nd parameter are taken as the application-defined
4550** function result.  If the 3rd parameter is non-negative, then it
4551** must be the byte offset into the string where the NUL terminator would
4552** appear if the string where NUL terminated.  If any NUL characters occur
4553** in the string at a byte offset that is less than the value of the 3rd
4554** parameter, then the resulting string will contain embedded NULs and the
4555** result of expressions operating on strings with embedded NULs is undefined.
4556** ^If the 4th parameter to the sqlite3_result_text* interfaces
4557** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4558** function as the destructor on the text or BLOB result when it has
4559** finished using that result.
4560** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4561** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4562** assumes that the text or BLOB result is in constant space and does not
4563** copy the content of the parameter nor call a destructor on the content
4564** when it has finished using that result.
4565** ^If the 4th parameter to the sqlite3_result_text* interfaces
4566** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4567** then SQLite makes a copy of the result into space obtained from
4568** from [sqlite3_malloc()] before it returns.
4569**
4570** ^The sqlite3_result_value() interface sets the result of
4571** the application-defined function to be a copy the
4572** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
4573** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4574** so that the [sqlite3_value] specified in the parameter may change or
4575** be deallocated after sqlite3_result_value() returns without harm.
4576** ^A [protected sqlite3_value] object may always be used where an
4577** [unprotected sqlite3_value] object is required, so either
4578** kind of [sqlite3_value] object can be used with this interface.
4579**
4580** If these routines are called from within the different thread
4581** than the one containing the application-defined function that received
4582** the [sqlite3_context] pointer, the results are undefined.
4583*/
4584SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4585SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4586SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4587SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4588SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4589SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4590SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4591SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4592SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4593SQLITE_API void sqlite3_result_null(sqlite3_context*);
4594SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4595SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4596SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4597SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4598SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4599SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4600
4601/*
4602** CAPI3REF: Define New Collating Sequences
4603**
4604** ^These functions add, remove, or modify a [collation] associated
4605** with the [database connection] specified as the first argument.
4606**
4607** ^The name of the collation is a UTF-8 string
4608** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4609** and a UTF-16 string in native byte order for sqlite3_create_collation16().
4610** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
4611** considered to be the same name.
4612**
4613** ^(The third argument (eTextRep) must be one of the constants:
4614** <ul>
4615** <li> [SQLITE_UTF8],
4616** <li> [SQLITE_UTF16LE],
4617** <li> [SQLITE_UTF16BE],
4618** <li> [SQLITE_UTF16], or
4619** <li> [SQLITE_UTF16_ALIGNED].
4620** </ul>)^
4621** ^The eTextRep argument determines the encoding of strings passed
4622** to the collating function callback, xCallback.
4623** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
4624** force strings to be UTF16 with native byte order.
4625** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
4626** on an even byte address.
4627**
4628** ^The fourth argument, pArg, is an application data pointer that is passed
4629** through as the first argument to the collating function callback.
4630**
4631** ^The fifth argument, xCallback, is a pointer to the collating function.
4632** ^Multiple collating functions can be registered using the same name but
4633** with different eTextRep parameters and SQLite will use whichever
4634** function requires the least amount of data transformation.
4635** ^If the xCallback argument is NULL then the collating function is
4636** deleted.  ^When all collating functions having the same name are deleted,
4637** that collation is no longer usable.
4638**
4639** ^The collating function callback is invoked with a copy of the pArg
4640** application data pointer and with two strings in the encoding specified
4641** by the eTextRep argument.  The collating function must return an
4642** integer that is negative, zero, or positive
4643** if the first string is less than, equal to, or greater than the second,
4644** respectively.  A collating function must always return the same answer
4645** given the same inputs.  If two or more collating functions are registered
4646** to the same collation name (using different eTextRep values) then all
4647** must give an equivalent answer when invoked with equivalent strings.
4648** The collating function must obey the following properties for all
4649** strings A, B, and C:
4650**
4651** <ol>
4652** <li> If A==B then B==A.
4653** <li> If A==B and B==C then A==C.
4654** <li> If A&lt;B THEN B&gt;A.
4655** <li> If A&lt;B and B&lt;C then A&lt;C.
4656** </ol>
4657**
4658** If a collating function fails any of the above constraints and that
4659** collating function is  registered and used, then the behavior of SQLite
4660** is undefined.
4661**
4662** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4663** with the addition that the xDestroy callback is invoked on pArg when
4664** the collating function is deleted.
4665** ^Collating functions are deleted when they are overridden by later
4666** calls to the collation creation functions or when the
4667** [database connection] is closed using [sqlite3_close()].
4668**
4669** ^The xDestroy callback is <u>not</u> called if the
4670** sqlite3_create_collation_v2() function fails.  Applications that invoke
4671** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
4672** check the return code and dispose of the application data pointer
4673** themselves rather than expecting SQLite to deal with it for them.
4674** This is different from every other SQLite interface.  The inconsistency
4675** is unfortunate but cannot be changed without breaking backwards
4676** compatibility.
4677**
4678** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4679*/
4680SQLITE_API int sqlite3_create_collation(
4681  sqlite3*,
4682  const char *zName,
4683  int eTextRep,
4684  void *pArg,
4685  int(*xCompare)(void*,int,const void*,int,const void*)
4686);
4687SQLITE_API int sqlite3_create_collation_v2(
4688  sqlite3*,
4689  const char *zName,
4690  int eTextRep,
4691  void *pArg,
4692  int(*xCompare)(void*,int,const void*,int,const void*),
4693  void(*xDestroy)(void*)
4694);
4695SQLITE_API int sqlite3_create_collation16(
4696  sqlite3*,
4697  const void *zName,
4698  int eTextRep,
4699  void *pArg,
4700  int(*xCompare)(void*,int,const void*,int,const void*)
4701);
4702
4703/*
4704** CAPI3REF: Collation Needed Callbacks
4705**
4706** ^To avoid having to register all collation sequences before a database
4707** can be used, a single callback function may be registered with the
4708** [database connection] to be invoked whenever an undefined collation
4709** sequence is required.
4710**
4711** ^If the function is registered using the sqlite3_collation_needed() API,
4712** then it is passed the names of undefined collation sequences as strings
4713** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
4714** the names are passed as UTF-16 in machine native byte order.
4715** ^A call to either function replaces the existing collation-needed callback.
4716**
4717** ^(When the callback is invoked, the first argument passed is a copy
4718** of the second argument to sqlite3_collation_needed() or
4719** sqlite3_collation_needed16().  The second argument is the database
4720** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
4721** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
4722** sequence function required.  The fourth parameter is the name of the
4723** required collation sequence.)^
4724**
4725** The callback function should register the desired collation using
4726** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
4727** [sqlite3_create_collation_v2()].
4728*/
4729SQLITE_API int sqlite3_collation_needed(
4730  sqlite3*,
4731  void*,
4732  void(*)(void*,sqlite3*,int eTextRep,const char*)
4733);
4734SQLITE_API int sqlite3_collation_needed16(
4735  sqlite3*,
4736  void*,
4737  void(*)(void*,sqlite3*,int eTextRep,const void*)
4738);
4739
4740#ifdef SQLITE_HAS_CODEC
4741/*
4742** Specify the key for an encrypted database.  This routine should be
4743** called right after sqlite3_open().
4744**
4745** The code to implement this API is not available in the public release
4746** of SQLite.
4747*/
4748SQLITE_API int sqlite3_key(
4749  sqlite3 *db,                   /* Database to be rekeyed */
4750  const void *pKey, int nKey     /* The key */
4751);
4752SQLITE_API int sqlite3_key_v2(
4753  sqlite3 *db,                   /* Database to be rekeyed */
4754  const char *zDbName,           /* Name of the database */
4755  const void *pKey, int nKey     /* The key */
4756);
4757
4758/*
4759** Change the key on an open database.  If the current database is not
4760** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
4761** database is decrypted.
4762**
4763** The code to implement this API is not available in the public release
4764** of SQLite.
4765*/
4766SQLITE_API int sqlite3_rekey(
4767  sqlite3 *db,                   /* Database to be rekeyed */
4768  const void *pKey, int nKey     /* The new key */
4769);
4770SQLITE_API int sqlite3_rekey_v2(
4771  sqlite3 *db,                   /* Database to be rekeyed */
4772  const char *zDbName,           /* Name of the database */
4773  const void *pKey, int nKey     /* The new key */
4774);
4775
4776/*
4777** Specify the activation key for a SEE database.  Unless
4778** activated, none of the SEE routines will work.
4779*/
4780SQLITE_API void sqlite3_activate_see(
4781  const char *zPassPhrase        /* Activation phrase */
4782);
4783#endif
4784
4785#ifdef SQLITE_ENABLE_CEROD
4786/*
4787** Specify the activation key for a CEROD database.  Unless
4788** activated, none of the CEROD routines will work.
4789*/
4790SQLITE_API void sqlite3_activate_cerod(
4791  const char *zPassPhrase        /* Activation phrase */
4792);
4793#endif
4794
4795/*
4796** CAPI3REF: Suspend Execution For A Short Time
4797**
4798** The sqlite3_sleep() function causes the current thread to suspend execution
4799** for at least a number of milliseconds specified in its parameter.
4800**
4801** If the operating system does not support sleep requests with
4802** millisecond time resolution, then the time will be rounded up to
4803** the nearest second. The number of milliseconds of sleep actually
4804** requested from the operating system is returned.
4805**
4806** ^SQLite implements this interface by calling the xSleep()
4807** method of the default [sqlite3_vfs] object.  If the xSleep() method
4808** of the default VFS is not implemented correctly, or not implemented at
4809** all, then the behavior of sqlite3_sleep() may deviate from the description
4810** in the previous paragraphs.
4811*/
4812SQLITE_API int sqlite3_sleep(int);
4813
4814/*
4815** CAPI3REF: Name Of The Folder Holding Temporary Files
4816**
4817** ^(If this global variable is made to point to a string which is
4818** the name of a folder (a.k.a. directory), then all temporary files
4819** created by SQLite when using a built-in [sqlite3_vfs | VFS]
4820** will be placed in that directory.)^  ^If this variable
4821** is a NULL pointer, then SQLite performs a search for an appropriate
4822** temporary file directory.
4823**
4824** It is not safe to read or modify this variable in more than one
4825** thread at a time.  It is not safe to read or modify this variable
4826** if a [database connection] is being used at the same time in a separate
4827** thread.
4828** It is intended that this variable be set once
4829** as part of process initialization and before any SQLite interface
4830** routines have been called and that this variable remain unchanged
4831** thereafter.
4832**
4833** ^The [temp_store_directory pragma] may modify this variable and cause
4834** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
4835** the [temp_store_directory pragma] always assumes that any string
4836** that this variable points to is held in memory obtained from
4837** [sqlite3_malloc] and the pragma may attempt to free that memory
4838** using [sqlite3_free].
4839** Hence, if this variable is modified directly, either it should be
4840** made NULL or made to point to memory obtained from [sqlite3_malloc]
4841** or else the use of the [temp_store_directory pragma] should be avoided.
4842**
4843** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
4844** prior to calling [sqlite3_open] or [sqlite3_open_v2].  Otherwise, various
4845** features that require the use of temporary files may fail.  Here is an
4846** example of how to do this using C++ with the Windows Runtime:
4847**
4848** <blockquote><pre>
4849** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
4850** &nbsp;     TemporaryFolder->Path->Data();
4851** char zPathBuf&#91;MAX_PATH + 1&#93;;
4852** memset(zPathBuf, 0, sizeof(zPathBuf));
4853** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
4854** &nbsp;     NULL, NULL);
4855** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
4856** </pre></blockquote>
4857*/
4858SQLITE_API char *sqlite3_temp_directory;
4859
4860/*
4861** CAPI3REF: Name Of The Folder Holding Database Files
4862**
4863** ^(If this global variable is made to point to a string which is
4864** the name of a folder (a.k.a. directory), then all database files
4865** specified with a relative pathname and created or accessed by
4866** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
4867** to be relative to that directory.)^ ^If this variable is a NULL
4868** pointer, then SQLite assumes that all database files specified
4869** with a relative pathname are relative to the current directory
4870** for the process.  Only the windows VFS makes use of this global
4871** variable; it is ignored by the unix VFS.
4872**
4873** Changing the value of this variable while a database connection is
4874** open can result in a corrupt database.
4875**
4876** It is not safe to read or modify this variable in more than one
4877** thread at a time.  It is not safe to read or modify this variable
4878** if a [database connection] is being used at the same time in a separate
4879** thread.
4880** It is intended that this variable be set once
4881** as part of process initialization and before any SQLite interface
4882** routines have been called and that this variable remain unchanged
4883** thereafter.
4884**
4885** ^The [data_store_directory pragma] may modify this variable and cause
4886** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
4887** the [data_store_directory pragma] always assumes that any string
4888** that this variable points to is held in memory obtained from
4889** [sqlite3_malloc] and the pragma may attempt to free that memory
4890** using [sqlite3_free].
4891** Hence, if this variable is modified directly, either it should be
4892** made NULL or made to point to memory obtained from [sqlite3_malloc]
4893** or else the use of the [data_store_directory pragma] should be avoided.
4894*/
4895SQLITE_API char *sqlite3_data_directory;
4896
4897/*
4898** CAPI3REF: Test For Auto-Commit Mode
4899** KEYWORDS: {autocommit mode}
4900**
4901** ^The sqlite3_get_autocommit() interface returns non-zero or
4902** zero if the given database connection is or is not in autocommit mode,
4903** respectively.  ^Autocommit mode is on by default.
4904** ^Autocommit mode is disabled by a [BEGIN] statement.
4905** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
4906**
4907** If certain kinds of errors occur on a statement within a multi-statement
4908** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
4909** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
4910** transaction might be rolled back automatically.  The only way to
4911** find out whether SQLite automatically rolled back the transaction after
4912** an error is to use this function.
4913**
4914** If another thread changes the autocommit status of the database
4915** connection while this routine is running, then the return value
4916** is undefined.
4917*/
4918SQLITE_API int sqlite3_get_autocommit(sqlite3*);
4919
4920/*
4921** CAPI3REF: Find The Database Handle Of A Prepared Statement
4922**
4923** ^The sqlite3_db_handle interface returns the [database connection] handle
4924** to which a [prepared statement] belongs.  ^The [database connection]
4925** returned by sqlite3_db_handle is the same [database connection]
4926** that was the first argument
4927** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
4928** create the statement in the first place.
4929*/
4930SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
4931
4932/*
4933** CAPI3REF: Return The Filename For A Database Connection
4934**
4935** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
4936** associated with database N of connection D.  ^The main database file
4937** has the name "main".  If there is no attached database N on the database
4938** connection D, or if database N is a temporary or in-memory database, then
4939** a NULL pointer is returned.
4940**
4941** ^The filename returned by this function is the output of the
4942** xFullPathname method of the [VFS].  ^In other words, the filename
4943** will be an absolute pathname, even if the filename used
4944** to open the database originally was a URI or relative pathname.
4945*/
4946SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
4947
4948/*
4949** CAPI3REF: Determine if a database is read-only
4950**
4951** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
4952** of connection D is read-only, 0 if it is read/write, or -1 if N is not
4953** the name of a database on connection D.
4954*/
4955SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
4956
4957/*
4958** CAPI3REF: Find the next prepared statement
4959**
4960** ^This interface returns a pointer to the next [prepared statement] after
4961** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
4962** then this interface returns a pointer to the first prepared statement
4963** associated with the database connection pDb.  ^If no prepared statement
4964** satisfies the conditions of this routine, it returns NULL.
4965**
4966** The [database connection] pointer D in a call to
4967** [sqlite3_next_stmt(D,S)] must refer to an open database
4968** connection and in particular must not be a NULL pointer.
4969*/
4970SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
4971
4972/*
4973** CAPI3REF: Commit And Rollback Notification Callbacks
4974**
4975** ^The sqlite3_commit_hook() interface registers a callback
4976** function to be invoked whenever a transaction is [COMMIT | committed].
4977** ^Any callback set by a previous call to sqlite3_commit_hook()
4978** for the same database connection is overridden.
4979** ^The sqlite3_rollback_hook() interface registers a callback
4980** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
4981** ^Any callback set by a previous call to sqlite3_rollback_hook()
4982** for the same database connection is overridden.
4983** ^The pArg argument is passed through to the callback.
4984** ^If the callback on a commit hook function returns non-zero,
4985** then the commit is converted into a rollback.
4986**
4987** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
4988** return the P argument from the previous call of the same function
4989** on the same [database connection] D, or NULL for
4990** the first call for each function on D.
4991**
4992** The commit and rollback hook callbacks are not reentrant.
4993** The callback implementation must not do anything that will modify
4994** the database connection that invoked the callback.  Any actions
4995** to modify the database connection must be deferred until after the
4996** completion of the [sqlite3_step()] call that triggered the commit
4997** or rollback hook in the first place.
4998** Note that running any other SQL statements, including SELECT statements,
4999** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
5000** the database connections for the meaning of "modify" in this paragraph.
5001**
5002** ^Registering a NULL function disables the callback.
5003**
5004** ^When the commit hook callback routine returns zero, the [COMMIT]
5005** operation is allowed to continue normally.  ^If the commit hook
5006** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
5007** ^The rollback hook is invoked on a rollback that results from a commit
5008** hook returning non-zero, just as it would be with any other rollback.
5009**
5010** ^For the purposes of this API, a transaction is said to have been
5011** rolled back if an explicit "ROLLBACK" statement is executed, or
5012** an error or constraint causes an implicit rollback to occur.
5013** ^The rollback callback is not invoked if a transaction is
5014** automatically rolled back because the database connection is closed.
5015**
5016** See also the [sqlite3_update_hook()] interface.
5017*/
5018SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
5019SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
5020
5021/*
5022** CAPI3REF: Data Change Notification Callbacks
5023**
5024** ^The sqlite3_update_hook() interface registers a callback function
5025** with the [database connection] identified by the first argument
5026** to be invoked whenever a row is updated, inserted or deleted in
5027** a rowid table.
5028** ^Any callback set by a previous call to this function
5029** for the same database connection is overridden.
5030**
5031** ^The second argument is a pointer to the function to invoke when a
5032** row is updated, inserted or deleted in a rowid table.
5033** ^The first argument to the callback is a copy of the third argument
5034** to sqlite3_update_hook().
5035** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
5036** or [SQLITE_UPDATE], depending on the operation that caused the callback
5037** to be invoked.
5038** ^The third and fourth arguments to the callback contain pointers to the
5039** database and table name containing the affected row.
5040** ^The final callback parameter is the [rowid] of the row.
5041** ^In the case of an update, this is the [rowid] after the update takes place.
5042**
5043** ^(The update hook is not invoked when internal system tables are
5044** modified (i.e. sqlite_master and sqlite_sequence).)^
5045** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
5046**
5047** ^In the current implementation, the update hook
5048** is not invoked when duplication rows are deleted because of an
5049** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
5050** invoked when rows are deleted using the [truncate optimization].
5051** The exceptions defined in this paragraph might change in a future
5052** release of SQLite.
5053**
5054** The update hook implementation must not do anything that will modify
5055** the database connection that invoked the update hook.  Any actions
5056** to modify the database connection must be deferred until after the
5057** completion of the [sqlite3_step()] call that triggered the update hook.
5058** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5059** database connections for the meaning of "modify" in this paragraph.
5060**
5061** ^The sqlite3_update_hook(D,C,P) function
5062** returns the P argument from the previous call
5063** on the same [database connection] D, or NULL for
5064** the first call on D.
5065**
5066** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
5067** interfaces.
5068*/
5069SQLITE_API void *sqlite3_update_hook(
5070  sqlite3*,
5071  void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5072  void*
5073);
5074
5075/*
5076** CAPI3REF: Enable Or Disable Shared Pager Cache
5077**
5078** ^(This routine enables or disables the sharing of the database cache
5079** and schema data structures between [database connection | connections]
5080** to the same database. Sharing is enabled if the argument is true
5081** and disabled if the argument is false.)^
5082**
5083** ^Cache sharing is enabled and disabled for an entire process.
5084** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
5085** sharing was enabled or disabled for each thread separately.
5086**
5087** ^(The cache sharing mode set by this interface effects all subsequent
5088** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
5089** Existing database connections continue use the sharing mode
5090** that was in effect at the time they were opened.)^
5091**
5092** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
5093** successfully.  An [error code] is returned otherwise.)^
5094**
5095** ^Shared cache is disabled by default. But this might change in
5096** future releases of SQLite.  Applications that care about shared
5097** cache setting should set it explicitly.
5098**
5099** This interface is threadsafe on processors where writing a
5100** 32-bit integer is atomic.
5101**
5102** See Also:  [SQLite Shared-Cache Mode]
5103*/
5104SQLITE_API int sqlite3_enable_shared_cache(int);
5105
5106/*
5107** CAPI3REF: Attempt To Free Heap Memory
5108**
5109** ^The sqlite3_release_memory() interface attempts to free N bytes
5110** of heap memory by deallocating non-essential memory allocations
5111** held by the database library.   Memory used to cache database
5112** pages to improve performance is an example of non-essential memory.
5113** ^sqlite3_release_memory() returns the number of bytes actually freed,
5114** which might be more or less than the amount requested.
5115** ^The sqlite3_release_memory() routine is a no-op returning zero
5116** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5117**
5118** See also: [sqlite3_db_release_memory()]
5119*/
5120SQLITE_API int sqlite3_release_memory(int);
5121
5122/*
5123** CAPI3REF: Free Memory Used By A Database Connection
5124**
5125** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
5126** memory as possible from database connection D. Unlike the
5127** [sqlite3_release_memory()] interface, this interface is in effect even
5128** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
5129** omitted.
5130**
5131** See also: [sqlite3_release_memory()]
5132*/
5133SQLITE_API int sqlite3_db_release_memory(sqlite3*);
5134
5135/*
5136** CAPI3REF: Impose A Limit On Heap Size
5137**
5138** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
5139** soft limit on the amount of heap memory that may be allocated by SQLite.
5140** ^SQLite strives to keep heap memory utilization below the soft heap
5141** limit by reducing the number of pages held in the page cache
5142** as heap memory usages approaches the limit.
5143** ^The soft heap limit is "soft" because even though SQLite strives to stay
5144** below the limit, it will exceed the limit rather than generate
5145** an [SQLITE_NOMEM] error.  In other words, the soft heap limit
5146** is advisory only.
5147**
5148** ^The return value from sqlite3_soft_heap_limit64() is the size of
5149** the soft heap limit prior to the call, or negative in the case of an
5150** error.  ^If the argument N is negative
5151** then no change is made to the soft heap limit.  Hence, the current
5152** size of the soft heap limit can be determined by invoking
5153** sqlite3_soft_heap_limit64() with a negative argument.
5154**
5155** ^If the argument N is zero then the soft heap limit is disabled.
5156**
5157** ^(The soft heap limit is not enforced in the current implementation
5158** if one or more of following conditions are true:
5159**
5160** <ul>
5161** <li> The soft heap limit is set to zero.
5162** <li> Memory accounting is disabled using a combination of the
5163**      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
5164**      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
5165** <li> An alternative page cache implementation is specified using
5166**      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
5167** <li> The page cache allocates from its own memory pool supplied
5168**      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
5169**      from the heap.
5170** </ul>)^
5171**
5172** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
5173** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
5174** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
5175** the soft heap limit is enforced on every memory allocation.  Without
5176** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
5177** when memory is allocated by the page cache.  Testing suggests that because
5178** the page cache is the predominate memory user in SQLite, most
5179** applications will achieve adequate soft heap limit enforcement without
5180** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5181**
5182** The circumstances under which SQLite will enforce the soft heap limit may
5183** changes in future releases of SQLite.
5184*/
5185SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
5186
5187/*
5188** CAPI3REF: Deprecated Soft Heap Limit Interface
5189** DEPRECATED
5190**
5191** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
5192** interface.  This routine is provided for historical compatibility
5193** only.  All new applications should use the
5194** [sqlite3_soft_heap_limit64()] interface rather than this one.
5195*/
5196SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
5197
5198
5199/*
5200** CAPI3REF: Extract Metadata About A Column Of A Table
5201**
5202** ^This routine returns metadata about a specific column of a specific
5203** database table accessible using the [database connection] handle
5204** passed as the first function argument.
5205**
5206** ^The column is identified by the second, third and fourth parameters to
5207** this function. ^The second parameter is either the name of the database
5208** (i.e. "main", "temp", or an attached database) containing the specified
5209** table or NULL. ^If it is NULL, then all attached databases are searched
5210** for the table using the same algorithm used by the database engine to
5211** resolve unqualified table references.
5212**
5213** ^The third and fourth parameters to this function are the table and column
5214** name of the desired column, respectively. Neither of these parameters
5215** may be NULL.
5216**
5217** ^Metadata is returned by writing to the memory locations passed as the 5th
5218** and subsequent parameters to this function. ^Any of these arguments may be
5219** NULL, in which case the corresponding element of metadata is omitted.
5220**
5221** ^(<blockquote>
5222** <table border="1">
5223** <tr><th> Parameter <th> Output<br>Type <th>  Description
5224**
5225** <tr><td> 5th <td> const char* <td> Data type
5226** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5227** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
5228** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
5229** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
5230** </table>
5231** </blockquote>)^
5232**
5233** ^The memory pointed to by the character pointers returned for the
5234** declaration type and collation sequence is valid only until the next
5235** call to any SQLite API function.
5236**
5237** ^If the specified table is actually a view, an [error code] is returned.
5238**
5239** ^If the specified column is "rowid", "oid" or "_rowid_" and an
5240** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
5241** parameters are set for the explicitly declared column. ^(If there is no
5242** explicitly declared [INTEGER PRIMARY KEY] column, then the output
5243** parameters are set as follows:
5244**
5245** <pre>
5246**     data type: "INTEGER"
5247**     collation sequence: "BINARY"
5248**     not null: 0
5249**     primary key: 1
5250**     auto increment: 0
5251** </pre>)^
5252**
5253** ^(This function may load one or more schemas from database files. If an
5254** error occurs during this process, or if the requested table or column
5255** cannot be found, an [error code] is returned and an error message left
5256** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
5257**
5258** ^This API is only available if the library was compiled with the
5259** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
5260*/
5261SQLITE_API int sqlite3_table_column_metadata(
5262  sqlite3 *db,                /* Connection handle */
5263  const char *zDbName,        /* Database name or NULL */
5264  const char *zTableName,     /* Table name */
5265  const char *zColumnName,    /* Column name */
5266  char const **pzDataType,    /* OUTPUT: Declared data type */
5267  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
5268  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
5269  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
5270  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
5271);
5272
5273/*
5274** CAPI3REF: Load An Extension
5275**
5276** ^This interface loads an SQLite extension library from the named file.
5277**
5278** ^The sqlite3_load_extension() interface attempts to load an
5279** [SQLite extension] library contained in the file zFile.  If
5280** the file cannot be loaded directly, attempts are made to load
5281** with various operating-system specific extensions added.
5282** So for example, if "samplelib" cannot be loaded, then names like
5283** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
5284** be tried also.
5285**
5286** ^The entry point is zProc.
5287** ^(zProc may be 0, in which case SQLite will try to come up with an
5288** entry point name on its own.  It first tries "sqlite3_extension_init".
5289** If that does not work, it constructs a name "sqlite3_X_init" where the
5290** X is consists of the lower-case equivalent of all ASCII alphabetic
5291** characters in the filename from the last "/" to the first following
5292** "." and omitting any initial "lib".)^
5293** ^The sqlite3_load_extension() interface returns
5294** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5295** ^If an error occurs and pzErrMsg is not 0, then the
5296** [sqlite3_load_extension()] interface shall attempt to
5297** fill *pzErrMsg with error message text stored in memory
5298** obtained from [sqlite3_malloc()]. The calling function
5299** should free this memory by calling [sqlite3_free()].
5300**
5301** ^Extension loading must be enabled using
5302** [sqlite3_enable_load_extension()] prior to calling this API,
5303** otherwise an error will be returned.
5304**
5305** See also the [load_extension() SQL function].
5306*/
5307SQLITE_API int sqlite3_load_extension(
5308  sqlite3 *db,          /* Load the extension into this database connection */
5309  const char *zFile,    /* Name of the shared library containing extension */
5310  const char *zProc,    /* Entry point.  Derived from zFile if 0 */
5311  char **pzErrMsg       /* Put error message here if not 0 */
5312);
5313
5314/*
5315** CAPI3REF: Enable Or Disable Extension Loading
5316**
5317** ^So as not to open security holes in older applications that are
5318** unprepared to deal with [extension loading], and as a means of disabling
5319** [extension loading] while evaluating user-entered SQL, the following API
5320** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5321**
5322** ^Extension loading is off by default.
5323** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5324** to turn extension loading on and call it with onoff==0 to turn
5325** it back off again.
5326*/
5327SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5328
5329/*
5330** CAPI3REF: Automatically Load Statically Linked Extensions
5331**
5332** ^This interface causes the xEntryPoint() function to be invoked for
5333** each new [database connection] that is created.  The idea here is that
5334** xEntryPoint() is the entry point for a statically linked [SQLite extension]
5335** that is to be automatically loaded into all new database connections.
5336**
5337** ^(Even though the function prototype shows that xEntryPoint() takes
5338** no arguments and returns void, SQLite invokes xEntryPoint() with three
5339** arguments and expects and integer result as if the signature of the
5340** entry point where as follows:
5341**
5342** <blockquote><pre>
5343** &nbsp;  int xEntryPoint(
5344** &nbsp;    sqlite3 *db,
5345** &nbsp;    const char **pzErrMsg,
5346** &nbsp;    const struct sqlite3_api_routines *pThunk
5347** &nbsp;  );
5348** </pre></blockquote>)^
5349**
5350** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5351** point to an appropriate error message (obtained from [sqlite3_mprintf()])
5352** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
5353** is NULL before calling the xEntryPoint().  ^SQLite will invoke
5354** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
5355** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
5356** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
5357**
5358** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
5359** on the list of automatic extensions is a harmless no-op. ^No entry point
5360** will be called more than once for each database connection that is opened.
5361**
5362** See also: [sqlite3_reset_auto_extension()]
5363** and [sqlite3_cancel_auto_extension()]
5364*/
5365SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
5366
5367/*
5368** CAPI3REF: Cancel Automatic Extension Loading
5369**
5370** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
5371** initialization routine X that was registered using a prior call to
5372** [sqlite3_auto_extension(X)].  ^The [sqlite3_cancel_auto_extension(X)]
5373** routine returns 1 if initialization routine X was successfully
5374** unregistered and it returns 0 if X was not on the list of initialization
5375** routines.
5376*/
5377SQLITE_API int sqlite3_cancel_auto_extension(void (*xEntryPoint)(void));
5378
5379/*
5380** CAPI3REF: Reset Automatic Extension Loading
5381**
5382** ^This interface disables all automatic extensions previously
5383** registered using [sqlite3_auto_extension()].
5384*/
5385SQLITE_API void sqlite3_reset_auto_extension(void);
5386
5387/*
5388** The interface to the virtual-table mechanism is currently considered
5389** to be experimental.  The interface might change in incompatible ways.
5390** If this is a problem for you, do not use the interface at this time.
5391**
5392** When the virtual-table mechanism stabilizes, we will declare the
5393** interface fixed, support it indefinitely, and remove this comment.
5394*/
5395
5396/*
5397** Structures used by the virtual table interface
5398*/
5399typedef struct sqlite3_vtab sqlite3_vtab;
5400typedef struct sqlite3_index_info sqlite3_index_info;
5401typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5402typedef struct sqlite3_module sqlite3_module;
5403
5404/*
5405** CAPI3REF: Virtual Table Object
5406** KEYWORDS: sqlite3_module {virtual table module}
5407**
5408** This structure, sometimes called a "virtual table module",
5409** defines the implementation of a [virtual tables].
5410** This structure consists mostly of methods for the module.
5411**
5412** ^A virtual table module is created by filling in a persistent
5413** instance of this structure and passing a pointer to that instance
5414** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
5415** ^The registration remains valid until it is replaced by a different
5416** module or until the [database connection] closes.  The content
5417** of this structure must not change while it is registered with
5418** any database connection.
5419*/
5420struct sqlite3_module {
5421  int iVersion;
5422  int (*xCreate)(sqlite3*, void *pAux,
5423               int argc, const char *const*argv,
5424               sqlite3_vtab **ppVTab, char**);
5425  int (*xConnect)(sqlite3*, void *pAux,
5426               int argc, const char *const*argv,
5427               sqlite3_vtab **ppVTab, char**);
5428  int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5429  int (*xDisconnect)(sqlite3_vtab *pVTab);
5430  int (*xDestroy)(sqlite3_vtab *pVTab);
5431  int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5432  int (*xClose)(sqlite3_vtab_cursor*);
5433  int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5434                int argc, sqlite3_value **argv);
5435  int (*xNext)(sqlite3_vtab_cursor*);
5436  int (*xEof)(sqlite3_vtab_cursor*);
5437  int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5438  int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5439  int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5440  int (*xBegin)(sqlite3_vtab *pVTab);
5441  int (*xSync)(sqlite3_vtab *pVTab);
5442  int (*xCommit)(sqlite3_vtab *pVTab);
5443  int (*xRollback)(sqlite3_vtab *pVTab);
5444  int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5445                       void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5446                       void **ppArg);
5447  int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5448  /* The methods above are in version 1 of the sqlite_module object. Those
5449  ** below are for version 2 and greater. */
5450  int (*xSavepoint)(sqlite3_vtab *pVTab, int);
5451  int (*xRelease)(sqlite3_vtab *pVTab, int);
5452  int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
5453};
5454
5455/*
5456** CAPI3REF: Virtual Table Indexing Information
5457** KEYWORDS: sqlite3_index_info
5458**
5459** The sqlite3_index_info structure and its substructures is used as part
5460** of the [virtual table] interface to
5461** pass information into and receive the reply from the [xBestIndex]
5462** method of a [virtual table module].  The fields under **Inputs** are the
5463** inputs to xBestIndex and are read-only.  xBestIndex inserts its
5464** results into the **Outputs** fields.
5465**
5466** ^(The aConstraint[] array records WHERE clause constraints of the form:
5467**
5468** <blockquote>column OP expr</blockquote>
5469**
5470** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
5471** stored in aConstraint[].op using one of the
5472** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
5473** ^(The index of the column is stored in
5474** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
5475** expr on the right-hand side can be evaluated (and thus the constraint
5476** is usable) and false if it cannot.)^
5477**
5478** ^The optimizer automatically inverts terms of the form "expr OP column"
5479** and makes other simplifications to the WHERE clause in an attempt to
5480** get as many WHERE clause terms into the form shown above as possible.
5481** ^The aConstraint[] array only reports WHERE clause terms that are
5482** relevant to the particular virtual table being queried.
5483**
5484** ^Information about the ORDER BY clause is stored in aOrderBy[].
5485** ^Each term of aOrderBy records a column of the ORDER BY clause.
5486**
5487** The [xBestIndex] method must fill aConstraintUsage[] with information
5488** about what parameters to pass to xFilter.  ^If argvIndex>0 then
5489** the right-hand side of the corresponding aConstraint[] is evaluated
5490** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
5491** is true, then the constraint is assumed to be fully handled by the
5492** virtual table and is not checked again by SQLite.)^
5493**
5494** ^The idxNum and idxPtr values are recorded and passed into the
5495** [xFilter] method.
5496** ^[sqlite3_free()] is used to free idxPtr if and only if
5497** needToFreeIdxPtr is true.
5498**
5499** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
5500** the correct order to satisfy the ORDER BY clause so that no separate
5501** sorting step is required.
5502**
5503** ^The estimatedCost value is an estimate of the cost of a particular
5504** strategy. A cost of N indicates that the cost of the strategy is similar
5505** to a linear scan of an SQLite table with N rows. A cost of log(N)
5506** indicates that the expense of the operation is similar to that of a
5507** binary search on a unique indexed field of an SQLite table with N rows.
5508**
5509** ^The estimatedRows value is an estimate of the number of rows that
5510** will be returned by the strategy.
5511**
5512** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
5513** structure for SQLite version 3.8.2. If a virtual table extension is
5514** used with an SQLite version earlier than 3.8.2, the results of attempting
5515** to read or write the estimatedRows field are undefined (but are likely
5516** to included crashing the application). The estimatedRows field should
5517** therefore only be used if [sqlite3_libversion_number()] returns a
5518** value greater than or equal to 3008002.
5519*/
5520struct sqlite3_index_info {
5521  /* Inputs */
5522  int nConstraint;           /* Number of entries in aConstraint */
5523  struct sqlite3_index_constraint {
5524     int iColumn;              /* Column on left-hand side of constraint */
5525     unsigned char op;         /* Constraint operator */
5526     unsigned char usable;     /* True if this constraint is usable */
5527     int iTermOffset;          /* Used internally - xBestIndex should ignore */
5528  } *aConstraint;            /* Table of WHERE clause constraints */
5529  int nOrderBy;              /* Number of terms in the ORDER BY clause */
5530  struct sqlite3_index_orderby {
5531     int iColumn;              /* Column number */
5532     unsigned char desc;       /* True for DESC.  False for ASC. */
5533  } *aOrderBy;               /* The ORDER BY clause */
5534  /* Outputs */
5535  struct sqlite3_index_constraint_usage {
5536    int argvIndex;           /* if >0, constraint is part of argv to xFilter */
5537    unsigned char omit;      /* Do not code a test for this constraint */
5538  } *aConstraintUsage;
5539  int idxNum;                /* Number used to identify the index */
5540  char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
5541  int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
5542  int orderByConsumed;       /* True if output is already ordered */
5543  double estimatedCost;           /* Estimated cost of using this index */
5544  /* Fields below are only available in SQLite 3.8.2 and later */
5545  sqlite3_int64 estimatedRows;    /* Estimated number of rows returned */
5546};
5547
5548/*
5549** CAPI3REF: Virtual Table Constraint Operator Codes
5550**
5551** These macros defined the allowed values for the
5552** [sqlite3_index_info].aConstraint[].op field.  Each value represents
5553** an operator that is part of a constraint term in the wHERE clause of
5554** a query that uses a [virtual table].
5555*/
5556#define SQLITE_INDEX_CONSTRAINT_EQ    2
5557#define SQLITE_INDEX_CONSTRAINT_GT    4
5558#define SQLITE_INDEX_CONSTRAINT_LE    8
5559#define SQLITE_INDEX_CONSTRAINT_LT    16
5560#define SQLITE_INDEX_CONSTRAINT_GE    32
5561#define SQLITE_INDEX_CONSTRAINT_MATCH 64
5562
5563/*
5564** CAPI3REF: Register A Virtual Table Implementation
5565**
5566** ^These routines are used to register a new [virtual table module] name.
5567** ^Module names must be registered before
5568** creating a new [virtual table] using the module and before using a
5569** preexisting [virtual table] for the module.
5570**
5571** ^The module name is registered on the [database connection] specified
5572** by the first parameter.  ^The name of the module is given by the
5573** second parameter.  ^The third parameter is a pointer to
5574** the implementation of the [virtual table module].   ^The fourth
5575** parameter is an arbitrary client data pointer that is passed through
5576** into the [xCreate] and [xConnect] methods of the virtual table module
5577** when a new virtual table is be being created or reinitialized.
5578**
5579** ^The sqlite3_create_module_v2() interface has a fifth parameter which
5580** is a pointer to a destructor for the pClientData.  ^SQLite will
5581** invoke the destructor function (if it is not NULL) when SQLite
5582** no longer needs the pClientData pointer.  ^The destructor will also
5583** be invoked if the call to sqlite3_create_module_v2() fails.
5584** ^The sqlite3_create_module()
5585** interface is equivalent to sqlite3_create_module_v2() with a NULL
5586** destructor.
5587*/
5588SQLITE_API int sqlite3_create_module(
5589  sqlite3 *db,               /* SQLite connection to register module with */
5590  const char *zName,         /* Name of the module */
5591  const sqlite3_module *p,   /* Methods for the module */
5592  void *pClientData          /* Client data for xCreate/xConnect */
5593);
5594SQLITE_API int sqlite3_create_module_v2(
5595  sqlite3 *db,               /* SQLite connection to register module with */
5596  const char *zName,         /* Name of the module */
5597  const sqlite3_module *p,   /* Methods for the module */
5598  void *pClientData,         /* Client data for xCreate/xConnect */
5599  void(*xDestroy)(void*)     /* Module destructor function */
5600);
5601
5602/*
5603** CAPI3REF: Virtual Table Instance Object
5604** KEYWORDS: sqlite3_vtab
5605**
5606** Every [virtual table module] implementation uses a subclass
5607** of this object to describe a particular instance
5608** of the [virtual table].  Each subclass will
5609** be tailored to the specific needs of the module implementation.
5610** The purpose of this superclass is to define certain fields that are
5611** common to all module implementations.
5612**
5613** ^Virtual tables methods can set an error message by assigning a
5614** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
5615** take care that any prior string is freed by a call to [sqlite3_free()]
5616** prior to assigning a new string to zErrMsg.  ^After the error message
5617** is delivered up to the client application, the string will be automatically
5618** freed by sqlite3_free() and the zErrMsg field will be zeroed.
5619*/
5620struct sqlite3_vtab {
5621  const sqlite3_module *pModule;  /* The module for this virtual table */
5622  int nRef;                       /* NO LONGER USED */
5623  char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
5624  /* Virtual table implementations will typically add additional fields */
5625};
5626
5627/*
5628** CAPI3REF: Virtual Table Cursor Object
5629** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
5630**
5631** Every [virtual table module] implementation uses a subclass of the
5632** following structure to describe cursors that point into the
5633** [virtual table] and are used
5634** to loop through the virtual table.  Cursors are created using the
5635** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
5636** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
5637** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
5638** of the module.  Each module implementation will define
5639** the content of a cursor structure to suit its own needs.
5640**
5641** This superclass exists in order to define fields of the cursor that
5642** are common to all implementations.
5643*/
5644struct sqlite3_vtab_cursor {
5645  sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
5646  /* Virtual table implementations will typically add additional fields */
5647};
5648
5649/*
5650** CAPI3REF: Declare The Schema Of A Virtual Table
5651**
5652** ^The [xCreate] and [xConnect] methods of a
5653** [virtual table module] call this interface
5654** to declare the format (the names and datatypes of the columns) of
5655** the virtual tables they implement.
5656*/
5657SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
5658
5659/*
5660** CAPI3REF: Overload A Function For A Virtual Table
5661**
5662** ^(Virtual tables can provide alternative implementations of functions
5663** using the [xFindFunction] method of the [virtual table module].
5664** But global versions of those functions
5665** must exist in order to be overloaded.)^
5666**
5667** ^(This API makes sure a global version of a function with a particular
5668** name and number of parameters exists.  If no such function exists
5669** before this API is called, a new function is created.)^  ^The implementation
5670** of the new function always causes an exception to be thrown.  So
5671** the new function is not good for anything by itself.  Its only
5672** purpose is to be a placeholder function that can be overloaded
5673** by a [virtual table].
5674*/
5675SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5676
5677/*
5678** The interface to the virtual-table mechanism defined above (back up
5679** to a comment remarkably similar to this one) is currently considered
5680** to be experimental.  The interface might change in incompatible ways.
5681** If this is a problem for you, do not use the interface at this time.
5682**
5683** When the virtual-table mechanism stabilizes, we will declare the
5684** interface fixed, support it indefinitely, and remove this comment.
5685*/
5686
5687/*
5688** CAPI3REF: A Handle To An Open BLOB
5689** KEYWORDS: {BLOB handle} {BLOB handles}
5690**
5691** An instance of this object represents an open BLOB on which
5692** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
5693** ^Objects of this type are created by [sqlite3_blob_open()]
5694** and destroyed by [sqlite3_blob_close()].
5695** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5696** can be used to read or write small subsections of the BLOB.
5697** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
5698*/
5699typedef struct sqlite3_blob sqlite3_blob;
5700
5701/*
5702** CAPI3REF: Open A BLOB For Incremental I/O
5703**
5704** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
5705** in row iRow, column zColumn, table zTable in database zDb;
5706** in other words, the same BLOB that would be selected by:
5707**
5708** <pre>
5709**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
5710** </pre>)^
5711**
5712** ^If the flags parameter is non-zero, then the BLOB is opened for read
5713** and write access. ^If it is zero, the BLOB is opened for read access.
5714** ^It is not possible to open a column that is part of an index or primary
5715** key for writing. ^If [foreign key constraints] are enabled, it is
5716** not possible to open a column that is part of a [child key] for writing.
5717**
5718** ^Note that the database name is not the filename that contains
5719** the database but rather the symbolic name of the database that
5720** appears after the AS keyword when the database is connected using [ATTACH].
5721** ^For the main database file, the database name is "main".
5722** ^For TEMP tables, the database name is "temp".
5723**
5724** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
5725** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
5726** to be a null pointer.)^
5727** ^This function sets the [database connection] error code and message
5728** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
5729** functions. ^Note that the *ppBlob variable is always initialized in a
5730** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
5731** regardless of the success or failure of this routine.
5732**
5733** ^(If the row that a BLOB handle points to is modified by an
5734** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
5735** then the BLOB handle is marked as "expired".
5736** This is true if any column of the row is changed, even a column
5737** other than the one the BLOB handle is open on.)^
5738** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
5739** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
5740** ^(Changes written into a BLOB prior to the BLOB expiring are not
5741** rolled back by the expiration of the BLOB.  Such changes will eventually
5742** commit if the transaction continues to completion.)^
5743**
5744** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
5745** the opened blob.  ^The size of a blob may not be changed by this
5746** interface.  Use the [UPDATE] SQL command to change the size of a
5747** blob.
5748**
5749** ^The [sqlite3_blob_open()] interface will fail for a [WITHOUT ROWID]
5750** table.  Incremental BLOB I/O is not possible on [WITHOUT ROWID] tables.
5751**
5752** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
5753** and the built-in [zeroblob] SQL function can be used, if desired,
5754** to create an empty, zero-filled blob in which to read or write using
5755** this interface.
5756**
5757** To avoid a resource leak, every open [BLOB handle] should eventually
5758** be released by a call to [sqlite3_blob_close()].
5759*/
5760SQLITE_API int sqlite3_blob_open(
5761  sqlite3*,
5762  const char *zDb,
5763  const char *zTable,
5764  const char *zColumn,
5765  sqlite3_int64 iRow,
5766  int flags,
5767  sqlite3_blob **ppBlob
5768);
5769
5770/*
5771** CAPI3REF: Move a BLOB Handle to a New Row
5772**
5773** ^This function is used to move an existing blob handle so that it points
5774** to a different row of the same database table. ^The new row is identified
5775** by the rowid value passed as the second argument. Only the row can be
5776** changed. ^The database, table and column on which the blob handle is open
5777** remain the same. Moving an existing blob handle to a new row can be
5778** faster than closing the existing handle and opening a new one.
5779**
5780** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
5781** it must exist and there must be either a blob or text value stored in
5782** the nominated column.)^ ^If the new row is not present in the table, or if
5783** it does not contain a blob or text value, or if another error occurs, an
5784** SQLite error code is returned and the blob handle is considered aborted.
5785** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
5786** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
5787** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
5788** always returns zero.
5789**
5790** ^This function sets the database handle error code and message.
5791*/
5792SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
5793
5794/*
5795** CAPI3REF: Close A BLOB Handle
5796**
5797** ^Closes an open [BLOB handle].
5798**
5799** ^Closing a BLOB shall cause the current transaction to commit
5800** if there are no other BLOBs, no pending prepared statements, and the
5801** database connection is in [autocommit mode].
5802** ^If any writes were made to the BLOB, they might be held in cache
5803** until the close operation if they will fit.
5804**
5805** ^(Closing the BLOB often forces the changes
5806** out to disk and so if any I/O errors occur, they will likely occur
5807** at the time when the BLOB is closed.  Any errors that occur during
5808** closing are reported as a non-zero return value.)^
5809**
5810** ^(The BLOB is closed unconditionally.  Even if this routine returns
5811** an error code, the BLOB is still closed.)^
5812**
5813** ^Calling this routine with a null pointer (such as would be returned
5814** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
5815*/
5816SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
5817
5818/*
5819** CAPI3REF: Return The Size Of An Open BLOB
5820**
5821** ^Returns the size in bytes of the BLOB accessible via the
5822** successfully opened [BLOB handle] in its only argument.  ^The
5823** incremental blob I/O routines can only read or overwriting existing
5824** blob content; they cannot change the size of a blob.
5825**
5826** This routine only works on a [BLOB handle] which has been created
5827** by a prior successful call to [sqlite3_blob_open()] and which has not
5828** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5829** to this routine results in undefined and probably undesirable behavior.
5830*/
5831SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
5832
5833/*
5834** CAPI3REF: Read Data From A BLOB Incrementally
5835**
5836** ^(This function is used to read data from an open [BLOB handle] into a
5837** caller-supplied buffer. N bytes of data are copied into buffer Z
5838** from the open BLOB, starting at offset iOffset.)^
5839**
5840** ^If offset iOffset is less than N bytes from the end of the BLOB,
5841** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
5842** less than zero, [SQLITE_ERROR] is returned and no data is read.
5843** ^The size of the blob (and hence the maximum value of N+iOffset)
5844** can be determined using the [sqlite3_blob_bytes()] interface.
5845**
5846** ^An attempt to read from an expired [BLOB handle] fails with an
5847** error code of [SQLITE_ABORT].
5848**
5849** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
5850** Otherwise, an [error code] or an [extended error code] is returned.)^
5851**
5852** This routine only works on a [BLOB handle] which has been created
5853** by a prior successful call to [sqlite3_blob_open()] and which has not
5854** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5855** to this routine results in undefined and probably undesirable behavior.
5856**
5857** See also: [sqlite3_blob_write()].
5858*/
5859SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
5860
5861/*
5862** CAPI3REF: Write Data Into A BLOB Incrementally
5863**
5864** ^This function is used to write data into an open [BLOB handle] from a
5865** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
5866** into the open BLOB, starting at offset iOffset.
5867**
5868** ^If the [BLOB handle] passed as the first argument was not opened for
5869** writing (the flags parameter to [sqlite3_blob_open()] was zero),
5870** this function returns [SQLITE_READONLY].
5871**
5872** ^This function may only modify the contents of the BLOB; it is
5873** not possible to increase the size of a BLOB using this API.
5874** ^If offset iOffset is less than N bytes from the end of the BLOB,
5875** [SQLITE_ERROR] is returned and no data is written.  ^If N is
5876** less than zero [SQLITE_ERROR] is returned and no data is written.
5877** The size of the BLOB (and hence the maximum value of N+iOffset)
5878** can be determined using the [sqlite3_blob_bytes()] interface.
5879**
5880** ^An attempt to write to an expired [BLOB handle] fails with an
5881** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
5882** before the [BLOB handle] expired are not rolled back by the
5883** expiration of the handle, though of course those changes might
5884** have been overwritten by the statement that expired the BLOB handle
5885** or by other independent statements.
5886**
5887** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
5888** Otherwise, an  [error code] or an [extended error code] is returned.)^
5889**
5890** This routine only works on a [BLOB handle] which has been created
5891** by a prior successful call to [sqlite3_blob_open()] and which has not
5892** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5893** to this routine results in undefined and probably undesirable behavior.
5894**
5895** See also: [sqlite3_blob_read()].
5896*/
5897SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
5898
5899/*
5900** CAPI3REF: Virtual File System Objects
5901**
5902** A virtual filesystem (VFS) is an [sqlite3_vfs] object
5903** that SQLite uses to interact
5904** with the underlying operating system.  Most SQLite builds come with a
5905** single default VFS that is appropriate for the host computer.
5906** New VFSes can be registered and existing VFSes can be unregistered.
5907** The following interfaces are provided.
5908**
5909** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
5910** ^Names are case sensitive.
5911** ^Names are zero-terminated UTF-8 strings.
5912** ^If there is no match, a NULL pointer is returned.
5913** ^If zVfsName is NULL then the default VFS is returned.
5914**
5915** ^New VFSes are registered with sqlite3_vfs_register().
5916** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
5917** ^The same VFS can be registered multiple times without injury.
5918** ^To make an existing VFS into the default VFS, register it again
5919** with the makeDflt flag set.  If two different VFSes with the
5920** same name are registered, the behavior is undefined.  If a
5921** VFS is registered with a name that is NULL or an empty string,
5922** then the behavior is undefined.
5923**
5924** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
5925** ^(If the default VFS is unregistered, another VFS is chosen as
5926** the default.  The choice for the new VFS is arbitrary.)^
5927*/
5928SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
5929SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
5930SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
5931
5932/*
5933** CAPI3REF: Mutexes
5934**
5935** The SQLite core uses these routines for thread
5936** synchronization. Though they are intended for internal
5937** use by SQLite, code that links against SQLite is
5938** permitted to use any of these routines.
5939**
5940** The SQLite source code contains multiple implementations
5941** of these mutex routines.  An appropriate implementation
5942** is selected automatically at compile-time.  ^(The following
5943** implementations are available in the SQLite core:
5944**
5945** <ul>
5946** <li>   SQLITE_MUTEX_PTHREADS
5947** <li>   SQLITE_MUTEX_W32
5948** <li>   SQLITE_MUTEX_NOOP
5949** </ul>)^
5950**
5951** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
5952** that does no real locking and is appropriate for use in
5953** a single-threaded application.  ^The SQLITE_MUTEX_PTHREADS and
5954** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
5955** and Windows.
5956**
5957** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
5958** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
5959** implementation is included with the library. In this case the
5960** application must supply a custom mutex implementation using the
5961** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
5962** before calling sqlite3_initialize() or any other public sqlite3_
5963** function that calls sqlite3_initialize().)^
5964**
5965** ^The sqlite3_mutex_alloc() routine allocates a new
5966** mutex and returns a pointer to it. ^If it returns NULL
5967** that means that a mutex could not be allocated.  ^SQLite
5968** will unwind its stack and return an error.  ^(The argument
5969** to sqlite3_mutex_alloc() is one of these integer constants:
5970**
5971** <ul>
5972** <li>  SQLITE_MUTEX_FAST
5973** <li>  SQLITE_MUTEX_RECURSIVE
5974** <li>  SQLITE_MUTEX_STATIC_MASTER
5975** <li>  SQLITE_MUTEX_STATIC_MEM
5976** <li>  SQLITE_MUTEX_STATIC_MEM2
5977** <li>  SQLITE_MUTEX_STATIC_PRNG
5978** <li>  SQLITE_MUTEX_STATIC_LRU
5979** <li>  SQLITE_MUTEX_STATIC_LRU2
5980** </ul>)^
5981**
5982** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
5983** cause sqlite3_mutex_alloc() to create
5984** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
5985** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
5986** The mutex implementation does not need to make a distinction
5987** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
5988** not want to.  ^SQLite will only request a recursive mutex in
5989** cases where it really needs one.  ^If a faster non-recursive mutex
5990** implementation is available on the host platform, the mutex subsystem
5991** might return such a mutex in response to SQLITE_MUTEX_FAST.
5992**
5993** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
5994** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
5995** a pointer to a static preexisting mutex.  ^Six static mutexes are
5996** used by the current version of SQLite.  Future versions of SQLite
5997** may add additional static mutexes.  Static mutexes are for internal
5998** use by SQLite only.  Applications that use SQLite mutexes should
5999** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
6000** SQLITE_MUTEX_RECURSIVE.
6001**
6002** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
6003** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
6004** returns a different mutex on every call.  ^But for the static
6005** mutex types, the same mutex is returned on every call that has
6006** the same type number.
6007**
6008** ^The sqlite3_mutex_free() routine deallocates a previously
6009** allocated dynamic mutex.  ^SQLite is careful to deallocate every
6010** dynamic mutex that it allocates.  The dynamic mutexes must not be in
6011** use when they are deallocated.  Attempting to deallocate a static
6012** mutex results in undefined behavior.  ^SQLite never deallocates
6013** a static mutex.
6014**
6015** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
6016** to enter a mutex.  ^If another thread is already within the mutex,
6017** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
6018** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
6019** upon successful entry.  ^(Mutexes created using
6020** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
6021** In such cases the,
6022** mutex must be exited an equal number of times before another thread
6023** can enter.)^  ^(If the same thread tries to enter any other
6024** kind of mutex more than once, the behavior is undefined.
6025** SQLite will never exhibit
6026** such behavior in its own use of mutexes.)^
6027**
6028** ^(Some systems (for example, Windows 95) do not support the operation
6029** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
6030** will always return SQLITE_BUSY.  The SQLite core only ever uses
6031** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
6032**
6033** ^The sqlite3_mutex_leave() routine exits a mutex that was
6034** previously entered by the same thread.   ^(The behavior
6035** is undefined if the mutex is not currently entered by the
6036** calling thread or is not currently allocated.  SQLite will
6037** never do either.)^
6038**
6039** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
6040** sqlite3_mutex_leave() is a NULL pointer, then all three routines
6041** behave as no-ops.
6042**
6043** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
6044*/
6045SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
6046SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
6047SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
6048SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
6049SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
6050
6051/*
6052** CAPI3REF: Mutex Methods Object
6053**
6054** An instance of this structure defines the low-level routines
6055** used to allocate and use mutexes.
6056**
6057** Usually, the default mutex implementations provided by SQLite are
6058** sufficient, however the user has the option of substituting a custom
6059** implementation for specialized deployments or systems for which SQLite
6060** does not provide a suitable implementation. In this case, the user
6061** creates and populates an instance of this structure to pass
6062** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
6063** Additionally, an instance of this structure can be used as an
6064** output variable when querying the system for the current mutex
6065** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
6066**
6067** ^The xMutexInit method defined by this structure is invoked as
6068** part of system initialization by the sqlite3_initialize() function.
6069** ^The xMutexInit routine is called by SQLite exactly once for each
6070** effective call to [sqlite3_initialize()].
6071**
6072** ^The xMutexEnd method defined by this structure is invoked as
6073** part of system shutdown by the sqlite3_shutdown() function. The
6074** implementation of this method is expected to release all outstanding
6075** resources obtained by the mutex methods implementation, especially
6076** those obtained by the xMutexInit method.  ^The xMutexEnd()
6077** interface is invoked exactly once for each call to [sqlite3_shutdown()].
6078**
6079** ^(The remaining seven methods defined by this structure (xMutexAlloc,
6080** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
6081** xMutexNotheld) implement the following interfaces (respectively):
6082**
6083** <ul>
6084**   <li>  [sqlite3_mutex_alloc()] </li>
6085**   <li>  [sqlite3_mutex_free()] </li>
6086**   <li>  [sqlite3_mutex_enter()] </li>
6087**   <li>  [sqlite3_mutex_try()] </li>
6088**   <li>  [sqlite3_mutex_leave()] </li>
6089**   <li>  [sqlite3_mutex_held()] </li>
6090**   <li>  [sqlite3_mutex_notheld()] </li>
6091** </ul>)^
6092**
6093** The only difference is that the public sqlite3_XXX functions enumerated
6094** above silently ignore any invocations that pass a NULL pointer instead
6095** of a valid mutex handle. The implementations of the methods defined
6096** by this structure are not required to handle this case, the results
6097** of passing a NULL pointer instead of a valid mutex handle are undefined
6098** (i.e. it is acceptable to provide an implementation that segfaults if
6099** it is passed a NULL pointer).
6100**
6101** The xMutexInit() method must be threadsafe.  ^It must be harmless to
6102** invoke xMutexInit() multiple times within the same process and without
6103** intervening calls to xMutexEnd().  Second and subsequent calls to
6104** xMutexInit() must be no-ops.
6105**
6106** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
6107** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
6108** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
6109** memory allocation for a fast or recursive mutex.
6110**
6111** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
6112** called, but only if the prior call to xMutexInit returned SQLITE_OK.
6113** If xMutexInit fails in any way, it is expected to clean up after itself
6114** prior to returning.
6115*/
6116typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
6117struct sqlite3_mutex_methods {
6118  int (*xMutexInit)(void);
6119  int (*xMutexEnd)(void);
6120  sqlite3_mutex *(*xMutexAlloc)(int);
6121  void (*xMutexFree)(sqlite3_mutex *);
6122  void (*xMutexEnter)(sqlite3_mutex *);
6123  int (*xMutexTry)(sqlite3_mutex *);
6124  void (*xMutexLeave)(sqlite3_mutex *);
6125  int (*xMutexHeld)(sqlite3_mutex *);
6126  int (*xMutexNotheld)(sqlite3_mutex *);
6127};
6128
6129/*
6130** CAPI3REF: Mutex Verification Routines
6131**
6132** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
6133** are intended for use inside assert() statements.  ^The SQLite core
6134** never uses these routines except inside an assert() and applications
6135** are advised to follow the lead of the core.  ^The SQLite core only
6136** provides implementations for these routines when it is compiled
6137** with the SQLITE_DEBUG flag.  ^External mutex implementations
6138** are only required to provide these routines if SQLITE_DEBUG is
6139** defined and if NDEBUG is not defined.
6140**
6141** ^These routines should return true if the mutex in their argument
6142** is held or not held, respectively, by the calling thread.
6143**
6144** ^The implementation is not required to provide versions of these
6145** routines that actually work. If the implementation does not provide working
6146** versions of these routines, it should at least provide stubs that always
6147** return true so that one does not get spurious assertion failures.
6148**
6149** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
6150** the routine should return 1.   This seems counter-intuitive since
6151** clearly the mutex cannot be held if it does not exist.  But
6152** the reason the mutex does not exist is because the build is not
6153** using mutexes.  And we do not want the assert() containing the
6154** call to sqlite3_mutex_held() to fail, so a non-zero return is
6155** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
6156** interface should also return 1 when given a NULL pointer.
6157*/
6158#ifndef NDEBUG
6159SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
6160SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
6161#endif
6162
6163/*
6164** CAPI3REF: Mutex Types
6165**
6166** The [sqlite3_mutex_alloc()] interface takes a single argument
6167** which is one of these integer constants.
6168**
6169** The set of static mutexes may change from one SQLite release to the
6170** next.  Applications that override the built-in mutex logic must be
6171** prepared to accommodate additional static mutexes.
6172*/
6173#define SQLITE_MUTEX_FAST             0
6174#define SQLITE_MUTEX_RECURSIVE        1
6175#define SQLITE_MUTEX_STATIC_MASTER    2
6176#define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
6177#define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
6178#define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
6179#define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
6180#define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
6181#define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
6182#define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
6183
6184/*
6185** CAPI3REF: Retrieve the mutex for a database connection
6186**
6187** ^This interface returns a pointer the [sqlite3_mutex] object that
6188** serializes access to the [database connection] given in the argument
6189** when the [threading mode] is Serialized.
6190** ^If the [threading mode] is Single-thread or Multi-thread then this
6191** routine returns a NULL pointer.
6192*/
6193SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
6194
6195/*
6196** CAPI3REF: Low-Level Control Of Database Files
6197**
6198** ^The [sqlite3_file_control()] interface makes a direct call to the
6199** xFileControl method for the [sqlite3_io_methods] object associated
6200** with a particular database identified by the second argument. ^The
6201** name of the database is "main" for the main database or "temp" for the
6202** TEMP database, or the name that appears after the AS keyword for
6203** databases that are added using the [ATTACH] SQL command.
6204** ^A NULL pointer can be used in place of "main" to refer to the
6205** main database file.
6206** ^The third and fourth parameters to this routine
6207** are passed directly through to the second and third parameters of
6208** the xFileControl method.  ^The return value of the xFileControl
6209** method becomes the return value of this routine.
6210**
6211** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
6212** a pointer to the underlying [sqlite3_file] object to be written into
6213** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER
6214** case is a short-circuit path which does not actually invoke the
6215** underlying sqlite3_io_methods.xFileControl method.
6216**
6217** ^If the second parameter (zDbName) does not match the name of any
6218** open database file, then SQLITE_ERROR is returned.  ^This error
6219** code is not remembered and will not be recalled by [sqlite3_errcode()]
6220** or [sqlite3_errmsg()].  The underlying xFileControl method might
6221** also return SQLITE_ERROR.  There is no way to distinguish between
6222** an incorrect zDbName and an SQLITE_ERROR return from the underlying
6223** xFileControl method.
6224**
6225** See also: [SQLITE_FCNTL_LOCKSTATE]
6226*/
6227SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
6228
6229/*
6230** CAPI3REF: Testing Interface
6231**
6232** ^The sqlite3_test_control() interface is used to read out internal
6233** state of SQLite and to inject faults into SQLite for testing
6234** purposes.  ^The first parameter is an operation code that determines
6235** the number, meaning, and operation of all subsequent parameters.
6236**
6237** This interface is not for use by applications.  It exists solely
6238** for verifying the correct operation of the SQLite library.  Depending
6239** on how the SQLite library is compiled, this interface might not exist.
6240**
6241** The details of the operation codes, their meanings, the parameters
6242** they take, and what they do are all subject to change without notice.
6243** Unlike most of the SQLite API, this function is not guaranteed to
6244** operate consistently from one release to the next.
6245*/
6246SQLITE_API int sqlite3_test_control(int op, ...);
6247
6248/*
6249** CAPI3REF: Testing Interface Operation Codes
6250**
6251** These constants are the valid operation code parameters used
6252** as the first argument to [sqlite3_test_control()].
6253**
6254** These parameters and their meanings are subject to change
6255** without notice.  These values are for testing purposes only.
6256** Applications should not use any of these parameters or the
6257** [sqlite3_test_control()] interface.
6258*/
6259#define SQLITE_TESTCTRL_FIRST                    5
6260#define SQLITE_TESTCTRL_PRNG_SAVE                5
6261#define SQLITE_TESTCTRL_PRNG_RESTORE             6
6262#define SQLITE_TESTCTRL_PRNG_RESET               7
6263#define SQLITE_TESTCTRL_BITVEC_TEST              8
6264#define SQLITE_TESTCTRL_FAULT_INSTALL            9
6265#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
6266#define SQLITE_TESTCTRL_PENDING_BYTE            11
6267#define SQLITE_TESTCTRL_ASSERT                  12
6268#define SQLITE_TESTCTRL_ALWAYS                  13
6269#define SQLITE_TESTCTRL_RESERVE                 14
6270#define SQLITE_TESTCTRL_OPTIMIZATIONS           15
6271#define SQLITE_TESTCTRL_ISKEYWORD               16
6272#define SQLITE_TESTCTRL_SCRATCHMALLOC           17
6273#define SQLITE_TESTCTRL_LOCALTIME_FAULT         18
6274#define SQLITE_TESTCTRL_EXPLAIN_STMT            19
6275#define SQLITE_TESTCTRL_NEVER_CORRUPT           20
6276#define SQLITE_TESTCTRL_VDBE_COVERAGE           21
6277#define SQLITE_TESTCTRL_BYTEORDER               22
6278#define SQLITE_TESTCTRL_LAST                    22
6279
6280/*
6281** CAPI3REF: SQLite Runtime Status
6282**
6283** ^This interface is used to retrieve runtime status information
6284** about the performance of SQLite, and optionally to reset various
6285** highwater marks.  ^The first argument is an integer code for
6286** the specific parameter to measure.  ^(Recognized integer codes
6287** are of the form [status parameters | SQLITE_STATUS_...].)^
6288** ^The current value of the parameter is returned into *pCurrent.
6289** ^The highest recorded value is returned in *pHighwater.  ^If the
6290** resetFlag is true, then the highest record value is reset after
6291** *pHighwater is written.  ^(Some parameters do not record the highest
6292** value.  For those parameters
6293** nothing is written into *pHighwater and the resetFlag is ignored.)^
6294** ^(Other parameters record only the highwater mark and not the current
6295** value.  For these latter parameters nothing is written into *pCurrent.)^
6296**
6297** ^The sqlite3_status() routine returns SQLITE_OK on success and a
6298** non-zero [error code] on failure.
6299**
6300** This routine is threadsafe but is not atomic.  This routine can be
6301** called while other threads are running the same or different SQLite
6302** interfaces.  However the values returned in *pCurrent and
6303** *pHighwater reflect the status of SQLite at different points in time
6304** and it is possible that another thread might change the parameter
6305** in between the times when *pCurrent and *pHighwater are written.
6306**
6307** See also: [sqlite3_db_status()]
6308*/
6309SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
6310
6311
6312/*
6313** CAPI3REF: Status Parameters
6314** KEYWORDS: {status parameters}
6315**
6316** These integer constants designate various run-time status parameters
6317** that can be returned by [sqlite3_status()].
6318**
6319** <dl>
6320** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
6321** <dd>This parameter is the current amount of memory checked out
6322** using [sqlite3_malloc()], either directly or indirectly.  The
6323** figure includes calls made to [sqlite3_malloc()] by the application
6324** and internal memory usage by the SQLite library.  Scratch memory
6325** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
6326** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
6327** this parameter.  The amount returned is the sum of the allocation
6328** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
6329**
6330** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
6331** <dd>This parameter records the largest memory allocation request
6332** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
6333** internal equivalents).  Only the value returned in the
6334** *pHighwater parameter to [sqlite3_status()] is of interest.
6335** The value written into the *pCurrent parameter is undefined.</dd>)^
6336**
6337** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
6338** <dd>This parameter records the number of separate memory allocations
6339** currently checked out.</dd>)^
6340**
6341** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
6342** <dd>This parameter returns the number of pages used out of the
6343** [pagecache memory allocator] that was configured using
6344** [SQLITE_CONFIG_PAGECACHE].  The
6345** value returned is in pages, not in bytes.</dd>)^
6346**
6347** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
6348** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
6349** <dd>This parameter returns the number of bytes of page cache
6350** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
6351** buffer and where forced to overflow to [sqlite3_malloc()].  The
6352** returned value includes allocations that overflowed because they
6353** where too large (they were larger than the "sz" parameter to
6354** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
6355** no space was left in the page cache.</dd>)^
6356**
6357** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
6358** <dd>This parameter records the largest memory allocation request
6359** handed to [pagecache memory allocator].  Only the value returned in the
6360** *pHighwater parameter to [sqlite3_status()] is of interest.
6361** The value written into the *pCurrent parameter is undefined.</dd>)^
6362**
6363** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
6364** <dd>This parameter returns the number of allocations used out of the
6365** [scratch memory allocator] configured using
6366** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
6367** in bytes.  Since a single thread may only have one scratch allocation
6368** outstanding at time, this parameter also reports the number of threads
6369** using scratch memory at the same time.</dd>)^
6370**
6371** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6372** <dd>This parameter returns the number of bytes of scratch memory
6373** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
6374** buffer and where forced to overflow to [sqlite3_malloc()].  The values
6375** returned include overflows because the requested allocation was too
6376** larger (that is, because the requested allocation was larger than the
6377** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6378** slots were available.
6379** </dd>)^
6380**
6381** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6382** <dd>This parameter records the largest memory allocation request
6383** handed to [scratch memory allocator].  Only the value returned in the
6384** *pHighwater parameter to [sqlite3_status()] is of interest.
6385** The value written into the *pCurrent parameter is undefined.</dd>)^
6386**
6387** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
6388** <dd>This parameter records the deepest parser stack.  It is only
6389** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
6390** </dl>
6391**
6392** New status parameters may be added from time to time.
6393*/
6394#define SQLITE_STATUS_MEMORY_USED          0
6395#define SQLITE_STATUS_PAGECACHE_USED       1
6396#define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
6397#define SQLITE_STATUS_SCRATCH_USED         3
6398#define SQLITE_STATUS_SCRATCH_OVERFLOW     4
6399#define SQLITE_STATUS_MALLOC_SIZE          5
6400#define SQLITE_STATUS_PARSER_STACK         6
6401#define SQLITE_STATUS_PAGECACHE_SIZE       7
6402#define SQLITE_STATUS_SCRATCH_SIZE         8
6403#define SQLITE_STATUS_MALLOC_COUNT         9
6404
6405/*
6406** CAPI3REF: Database Connection Status
6407**
6408** ^This interface is used to retrieve runtime status information
6409** about a single [database connection].  ^The first argument is the
6410** database connection object to be interrogated.  ^The second argument
6411** is an integer constant, taken from the set of
6412** [SQLITE_DBSTATUS options], that
6413** determines the parameter to interrogate.  The set of
6414** [SQLITE_DBSTATUS options] is likely
6415** to grow in future releases of SQLite.
6416**
6417** ^The current value of the requested parameter is written into *pCur
6418** and the highest instantaneous value is written into *pHiwtr.  ^If
6419** the resetFlg is true, then the highest instantaneous value is
6420** reset back down to the current value.
6421**
6422** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
6423** non-zero [error code] on failure.
6424**
6425** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
6426*/
6427SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6428
6429/*
6430** CAPI3REF: Status Parameters for database connections
6431** KEYWORDS: {SQLITE_DBSTATUS options}
6432**
6433** These constants are the available integer "verbs" that can be passed as
6434** the second argument to the [sqlite3_db_status()] interface.
6435**
6436** New verbs may be added in future releases of SQLite. Existing verbs
6437** might be discontinued. Applications should check the return code from
6438** [sqlite3_db_status()] to make sure that the call worked.
6439** The [sqlite3_db_status()] interface will return a non-zero error code
6440** if a discontinued or unsupported verb is invoked.
6441**
6442** <dl>
6443** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6444** <dd>This parameter returns the number of lookaside memory slots currently
6445** checked out.</dd>)^
6446**
6447** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
6448** <dd>This parameter returns the number malloc attempts that were
6449** satisfied using lookaside memory. Only the high-water value is meaningful;
6450** the current value is always zero.)^
6451**
6452** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
6453** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
6454** <dd>This parameter returns the number malloc attempts that might have
6455** been satisfied using lookaside memory but failed due to the amount of
6456** memory requested being larger than the lookaside slot size.
6457** Only the high-water value is meaningful;
6458** the current value is always zero.)^
6459**
6460** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
6461** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
6462** <dd>This parameter returns the number malloc attempts that might have
6463** been satisfied using lookaside memory but failed due to all lookaside
6464** memory already being in use.
6465** Only the high-water value is meaningful;
6466** the current value is always zero.)^
6467**
6468** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
6469** <dd>This parameter returns the approximate number of of bytes of heap
6470** memory used by all pager caches associated with the database connection.)^
6471** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
6472**
6473** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
6474** <dd>This parameter returns the approximate number of of bytes of heap
6475** memory used to store the schema for all databases associated
6476** with the connection - main, temp, and any [ATTACH]-ed databases.)^
6477** ^The full amount of memory used by the schemas is reported, even if the
6478** schema memory is shared with other database connections due to
6479** [shared cache mode] being enabled.
6480** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
6481**
6482** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
6483** <dd>This parameter returns the approximate number of of bytes of heap
6484** and lookaside memory used by all prepared statements associated with
6485** the database connection.)^
6486** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
6487** </dd>
6488**
6489** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
6490** <dd>This parameter returns the number of pager cache hits that have
6491** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
6492** is always 0.
6493** </dd>
6494**
6495** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
6496** <dd>This parameter returns the number of pager cache misses that have
6497** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
6498** is always 0.
6499** </dd>
6500**
6501** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
6502** <dd>This parameter returns the number of dirty cache entries that have
6503** been written to disk. Specifically, the number of pages written to the
6504** wal file in wal mode databases, or the number of pages written to the
6505** database file in rollback mode databases. Any pages written as part of
6506** transaction rollback or database recovery operations are not included.
6507** If an IO or other error occurs while writing a page to disk, the effect
6508** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
6509** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
6510** </dd>
6511**
6512** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
6513** <dd>This parameter returns zero for the current value if and only if
6514** all foreign key constraints (deferred or immediate) have been
6515** resolved.)^  ^The highwater mark is always 0.
6516** </dd>
6517** </dl>
6518*/
6519#define SQLITE_DBSTATUS_LOOKASIDE_USED       0
6520#define SQLITE_DBSTATUS_CACHE_USED           1
6521#define SQLITE_DBSTATUS_SCHEMA_USED          2
6522#define SQLITE_DBSTATUS_STMT_USED            3
6523#define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
6524#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
6525#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
6526#define SQLITE_DBSTATUS_CACHE_HIT            7
6527#define SQLITE_DBSTATUS_CACHE_MISS           8
6528#define SQLITE_DBSTATUS_CACHE_WRITE          9
6529#define SQLITE_DBSTATUS_DEFERRED_FKS        10
6530#define SQLITE_DBSTATUS_MAX                 10   /* Largest defined DBSTATUS */
6531
6532
6533/*
6534** CAPI3REF: Prepared Statement Status
6535**
6536** ^(Each prepared statement maintains various
6537** [SQLITE_STMTSTATUS counters] that measure the number
6538** of times it has performed specific operations.)^  These counters can
6539** be used to monitor the performance characteristics of the prepared
6540** statements.  For example, if the number of table steps greatly exceeds
6541** the number of table searches or result rows, that would tend to indicate
6542** that the prepared statement is using a full table scan rather than
6543** an index.
6544**
6545** ^(This interface is used to retrieve and reset counter values from
6546** a [prepared statement].  The first argument is the prepared statement
6547** object to be interrogated.  The second argument
6548** is an integer code for a specific [SQLITE_STMTSTATUS counter]
6549** to be interrogated.)^
6550** ^The current value of the requested counter is returned.
6551** ^If the resetFlg is true, then the counter is reset to zero after this
6552** interface call returns.
6553**
6554** See also: [sqlite3_status()] and [sqlite3_db_status()].
6555*/
6556SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
6557
6558/*
6559** CAPI3REF: Status Parameters for prepared statements
6560** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
6561**
6562** These preprocessor macros define integer codes that name counter
6563** values associated with the [sqlite3_stmt_status()] interface.
6564** The meanings of the various counters are as follows:
6565**
6566** <dl>
6567** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
6568** <dd>^This is the number of times that SQLite has stepped forward in
6569** a table as part of a full table scan.  Large numbers for this counter
6570** may indicate opportunities for performance improvement through
6571** careful use of indices.</dd>
6572**
6573** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
6574** <dd>^This is the number of sort operations that have occurred.
6575** A non-zero value in this counter may indicate an opportunity to
6576** improvement performance through careful use of indices.</dd>
6577**
6578** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
6579** <dd>^This is the number of rows inserted into transient indices that
6580** were created automatically in order to help joins run faster.
6581** A non-zero value in this counter may indicate an opportunity to
6582** improvement performance by adding permanent indices that do not
6583** need to be reinitialized each time the statement is run.</dd>
6584**
6585** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
6586** <dd>^This is the number of virtual machine operations executed
6587** by the prepared statement if that number is less than or equal
6588** to 2147483647.  The number of virtual machine operations can be
6589** used as a proxy for the total work done by the prepared statement.
6590** If the number of virtual machine operations exceeds 2147483647
6591** then the value returned by this statement status code is undefined.
6592** </dd>
6593** </dl>
6594*/
6595#define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
6596#define SQLITE_STMTSTATUS_SORT              2
6597#define SQLITE_STMTSTATUS_AUTOINDEX         3
6598#define SQLITE_STMTSTATUS_VM_STEP           4
6599
6600/*
6601** CAPI3REF: Custom Page Cache Object
6602**
6603** The sqlite3_pcache type is opaque.  It is implemented by
6604** the pluggable module.  The SQLite core has no knowledge of
6605** its size or internal structure and never deals with the
6606** sqlite3_pcache object except by holding and passing pointers
6607** to the object.
6608**
6609** See [sqlite3_pcache_methods2] for additional information.
6610*/
6611typedef struct sqlite3_pcache sqlite3_pcache;
6612
6613/*
6614** CAPI3REF: Custom Page Cache Object
6615**
6616** The sqlite3_pcache_page object represents a single page in the
6617** page cache.  The page cache will allocate instances of this
6618** object.  Various methods of the page cache use pointers to instances
6619** of this object as parameters or as their return value.
6620**
6621** See [sqlite3_pcache_methods2] for additional information.
6622*/
6623typedef struct sqlite3_pcache_page sqlite3_pcache_page;
6624struct sqlite3_pcache_page {
6625  void *pBuf;        /* The content of the page */
6626  void *pExtra;      /* Extra information associated with the page */
6627};
6628
6629/*
6630** CAPI3REF: Application Defined Page Cache.
6631** KEYWORDS: {page cache}
6632**
6633** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
6634** register an alternative page cache implementation by passing in an
6635** instance of the sqlite3_pcache_methods2 structure.)^
6636** In many applications, most of the heap memory allocated by
6637** SQLite is used for the page cache.
6638** By implementing a
6639** custom page cache using this API, an application can better control
6640** the amount of memory consumed by SQLite, the way in which
6641** that memory is allocated and released, and the policies used to
6642** determine exactly which parts of a database file are cached and for
6643** how long.
6644**
6645** The alternative page cache mechanism is an
6646** extreme measure that is only needed by the most demanding applications.
6647** The built-in page cache is recommended for most uses.
6648**
6649** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
6650** internal buffer by SQLite within the call to [sqlite3_config].  Hence
6651** the application may discard the parameter after the call to
6652** [sqlite3_config()] returns.)^
6653**
6654** [[the xInit() page cache method]]
6655** ^(The xInit() method is called once for each effective
6656** call to [sqlite3_initialize()])^
6657** (usually only once during the lifetime of the process). ^(The xInit()
6658** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
6659** The intent of the xInit() method is to set up global data structures
6660** required by the custom page cache implementation.
6661** ^(If the xInit() method is NULL, then the
6662** built-in default page cache is used instead of the application defined
6663** page cache.)^
6664**
6665** [[the xShutdown() page cache method]]
6666** ^The xShutdown() method is called by [sqlite3_shutdown()].
6667** It can be used to clean up
6668** any outstanding resources before process shutdown, if required.
6669** ^The xShutdown() method may be NULL.
6670**
6671** ^SQLite automatically serializes calls to the xInit method,
6672** so the xInit method need not be threadsafe.  ^The
6673** xShutdown method is only called from [sqlite3_shutdown()] so it does
6674** not need to be threadsafe either.  All other methods must be threadsafe
6675** in multithreaded applications.
6676**
6677** ^SQLite will never invoke xInit() more than once without an intervening
6678** call to xShutdown().
6679**
6680** [[the xCreate() page cache methods]]
6681** ^SQLite invokes the xCreate() method to construct a new cache instance.
6682** SQLite will typically create one cache instance for each open database file,
6683** though this is not guaranteed. ^The
6684** first parameter, szPage, is the size in bytes of the pages that must
6685** be allocated by the cache.  ^szPage will always a power of two.  ^The
6686** second parameter szExtra is a number of bytes of extra storage
6687** associated with each page cache entry.  ^The szExtra parameter will
6688** a number less than 250.  SQLite will use the
6689** extra szExtra bytes on each page to store metadata about the underlying
6690** database page on disk.  The value passed into szExtra depends
6691** on the SQLite version, the target platform, and how SQLite was compiled.
6692** ^The third argument to xCreate(), bPurgeable, is true if the cache being
6693** created will be used to cache database pages of a file stored on disk, or
6694** false if it is used for an in-memory database. The cache implementation
6695** does not have to do anything special based with the value of bPurgeable;
6696** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
6697** never invoke xUnpin() except to deliberately delete a page.
6698** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
6699** false will always have the "discard" flag set to true.
6700** ^Hence, a cache created with bPurgeable false will
6701** never contain any unpinned pages.
6702**
6703** [[the xCachesize() page cache method]]
6704** ^(The xCachesize() method may be called at any time by SQLite to set the
6705** suggested maximum cache-size (number of pages stored by) the cache
6706** instance passed as the first argument. This is the value configured using
6707** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
6708** parameter, the implementation is not required to do anything with this
6709** value; it is advisory only.
6710**
6711** [[the xPagecount() page cache methods]]
6712** The xPagecount() method must return the number of pages currently
6713** stored in the cache, both pinned and unpinned.
6714**
6715** [[the xFetch() page cache methods]]
6716** The xFetch() method locates a page in the cache and returns a pointer to
6717** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
6718** The pBuf element of the returned sqlite3_pcache_page object will be a
6719** pointer to a buffer of szPage bytes used to store the content of a
6720** single database page.  The pExtra element of sqlite3_pcache_page will be
6721** a pointer to the szExtra bytes of extra storage that SQLite has requested
6722** for each entry in the page cache.
6723**
6724** The page to be fetched is determined by the key. ^The minimum key value
6725** is 1.  After it has been retrieved using xFetch, the page is considered
6726** to be "pinned".
6727**
6728** If the requested page is already in the page cache, then the page cache
6729** implementation must return a pointer to the page buffer with its content
6730** intact.  If the requested page is not already in the cache, then the
6731** cache implementation should use the value of the createFlag
6732** parameter to help it determined what action to take:
6733**
6734** <table border=1 width=85% align=center>
6735** <tr><th> createFlag <th> Behavior when page is not already in cache
6736** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
6737** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
6738**                 Otherwise return NULL.
6739** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
6740**                 NULL if allocating a new page is effectively impossible.
6741** </table>
6742**
6743** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
6744** will only use a createFlag of 2 after a prior call with a createFlag of 1
6745** failed.)^  In between the to xFetch() calls, SQLite may
6746** attempt to unpin one or more cache pages by spilling the content of
6747** pinned pages to disk and synching the operating system disk cache.
6748**
6749** [[the xUnpin() page cache method]]
6750** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
6751** as its second argument.  If the third parameter, discard, is non-zero,
6752** then the page must be evicted from the cache.
6753** ^If the discard parameter is
6754** zero, then the page may be discarded or retained at the discretion of
6755** page cache implementation. ^The page cache implementation
6756** may choose to evict unpinned pages at any time.
6757**
6758** The cache must not perform any reference counting. A single
6759** call to xUnpin() unpins the page regardless of the number of prior calls
6760** to xFetch().
6761**
6762** [[the xRekey() page cache methods]]
6763** The xRekey() method is used to change the key value associated with the
6764** page passed as the second argument. If the cache
6765** previously contains an entry associated with newKey, it must be
6766** discarded. ^Any prior cache entry associated with newKey is guaranteed not
6767** to be pinned.
6768**
6769** When SQLite calls the xTruncate() method, the cache must discard all
6770** existing cache entries with page numbers (keys) greater than or equal
6771** to the value of the iLimit parameter passed to xTruncate(). If any
6772** of these pages are pinned, they are implicitly unpinned, meaning that
6773** they can be safely discarded.
6774**
6775** [[the xDestroy() page cache method]]
6776** ^The xDestroy() method is used to delete a cache allocated by xCreate().
6777** All resources associated with the specified cache should be freed. ^After
6778** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
6779** handle invalid, and will not use it with any other sqlite3_pcache_methods2
6780** functions.
6781**
6782** [[the xShrink() page cache method]]
6783** ^SQLite invokes the xShrink() method when it wants the page cache to
6784** free up as much of heap memory as possible.  The page cache implementation
6785** is not obligated to free any memory, but well-behaved implementations should
6786** do their best.
6787*/
6788typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
6789struct sqlite3_pcache_methods2 {
6790  int iVersion;
6791  void *pArg;
6792  int (*xInit)(void*);
6793  void (*xShutdown)(void*);
6794  sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
6795  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
6796  int (*xPagecount)(sqlite3_pcache*);
6797  sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
6798  void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
6799  void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
6800      unsigned oldKey, unsigned newKey);
6801  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
6802  void (*xDestroy)(sqlite3_pcache*);
6803  void (*xShrink)(sqlite3_pcache*);
6804};
6805
6806/*
6807** This is the obsolete pcache_methods object that has now been replaced
6808** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is
6809** retained in the header file for backwards compatibility only.
6810*/
6811typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
6812struct sqlite3_pcache_methods {
6813  void *pArg;
6814  int (*xInit)(void*);
6815  void (*xShutdown)(void*);
6816  sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
6817  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
6818  int (*xPagecount)(sqlite3_pcache*);
6819  void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
6820  void (*xUnpin)(sqlite3_pcache*, void*, int discard);
6821  void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
6822  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
6823  void (*xDestroy)(sqlite3_pcache*);
6824};
6825
6826
6827/*
6828** CAPI3REF: Online Backup Object
6829**
6830** The sqlite3_backup object records state information about an ongoing
6831** online backup operation.  ^The sqlite3_backup object is created by
6832** a call to [sqlite3_backup_init()] and is destroyed by a call to
6833** [sqlite3_backup_finish()].
6834**
6835** See Also: [Using the SQLite Online Backup API]
6836*/
6837typedef struct sqlite3_backup sqlite3_backup;
6838
6839/*
6840** CAPI3REF: Online Backup API.
6841**
6842** The backup API copies the content of one database into another.
6843** It is useful either for creating backups of databases or
6844** for copying in-memory databases to or from persistent files.
6845**
6846** See Also: [Using the SQLite Online Backup API]
6847**
6848** ^SQLite holds a write transaction open on the destination database file
6849** for the duration of the backup operation.
6850** ^The source database is read-locked only while it is being read;
6851** it is not locked continuously for the entire backup operation.
6852** ^Thus, the backup may be performed on a live source database without
6853** preventing other database connections from
6854** reading or writing to the source database while the backup is underway.
6855**
6856** ^(To perform a backup operation:
6857**   <ol>
6858**     <li><b>sqlite3_backup_init()</b> is called once to initialize the
6859**         backup,
6860**     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
6861**         the data between the two databases, and finally
6862**     <li><b>sqlite3_backup_finish()</b> is called to release all resources
6863**         associated with the backup operation.
6864**   </ol>)^
6865** There should be exactly one call to sqlite3_backup_finish() for each
6866** successful call to sqlite3_backup_init().
6867**
6868** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
6869**
6870** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
6871** [database connection] associated with the destination database
6872** and the database name, respectively.
6873** ^The database name is "main" for the main database, "temp" for the
6874** temporary database, or the name specified after the AS keyword in
6875** an [ATTACH] statement for an attached database.
6876** ^The S and M arguments passed to
6877** sqlite3_backup_init(D,N,S,M) identify the [database connection]
6878** and database name of the source database, respectively.
6879** ^The source and destination [database connections] (parameters S and D)
6880** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
6881** an error.
6882**
6883** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
6884** returned and an error code and error message are stored in the
6885** destination [database connection] D.
6886** ^The error code and message for the failed call to sqlite3_backup_init()
6887** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
6888** [sqlite3_errmsg16()] functions.
6889** ^A successful call to sqlite3_backup_init() returns a pointer to an
6890** [sqlite3_backup] object.
6891** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
6892** sqlite3_backup_finish() functions to perform the specified backup
6893** operation.
6894**
6895** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
6896**
6897** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
6898** the source and destination databases specified by [sqlite3_backup] object B.
6899** ^If N is negative, all remaining source pages are copied.
6900** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
6901** are still more pages to be copied, then the function returns [SQLITE_OK].
6902** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
6903** from source to destination, then it returns [SQLITE_DONE].
6904** ^If an error occurs while running sqlite3_backup_step(B,N),
6905** then an [error code] is returned. ^As well as [SQLITE_OK] and
6906** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
6907** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
6908** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
6909**
6910** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
6911** <ol>
6912** <li> the destination database was opened read-only, or
6913** <li> the destination database is using write-ahead-log journaling
6914** and the destination and source page sizes differ, or
6915** <li> the destination database is an in-memory database and the
6916** destination and source page sizes differ.
6917** </ol>)^
6918**
6919** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
6920** the [sqlite3_busy_handler | busy-handler function]
6921** is invoked (if one is specified). ^If the
6922** busy-handler returns non-zero before the lock is available, then
6923** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
6924** sqlite3_backup_step() can be retried later. ^If the source
6925** [database connection]
6926** is being used to write to the source database when sqlite3_backup_step()
6927** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
6928** case the call to sqlite3_backup_step() can be retried later on. ^(If
6929** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
6930** [SQLITE_READONLY] is returned, then
6931** there is no point in retrying the call to sqlite3_backup_step(). These
6932** errors are considered fatal.)^  The application must accept
6933** that the backup operation has failed and pass the backup operation handle
6934** to the sqlite3_backup_finish() to release associated resources.
6935**
6936** ^The first call to sqlite3_backup_step() obtains an exclusive lock
6937** on the destination file. ^The exclusive lock is not released until either
6938** sqlite3_backup_finish() is called or the backup operation is complete
6939** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
6940** sqlite3_backup_step() obtains a [shared lock] on the source database that
6941** lasts for the duration of the sqlite3_backup_step() call.
6942** ^Because the source database is not locked between calls to
6943** sqlite3_backup_step(), the source database may be modified mid-way
6944** through the backup process.  ^If the source database is modified by an
6945** external process or via a database connection other than the one being
6946** used by the backup operation, then the backup will be automatically
6947** restarted by the next call to sqlite3_backup_step(). ^If the source
6948** database is modified by the using the same database connection as is used
6949** by the backup operation, then the backup database is automatically
6950** updated at the same time.
6951**
6952** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
6953**
6954** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
6955** application wishes to abandon the backup operation, the application
6956** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
6957** ^The sqlite3_backup_finish() interfaces releases all
6958** resources associated with the [sqlite3_backup] object.
6959** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
6960** active write-transaction on the destination database is rolled back.
6961** The [sqlite3_backup] object is invalid
6962** and may not be used following a call to sqlite3_backup_finish().
6963**
6964** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
6965** sqlite3_backup_step() errors occurred, regardless or whether or not
6966** sqlite3_backup_step() completed.
6967** ^If an out-of-memory condition or IO error occurred during any prior
6968** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
6969** sqlite3_backup_finish() returns the corresponding [error code].
6970**
6971** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
6972** is not a permanent error and does not affect the return value of
6973** sqlite3_backup_finish().
6974**
6975** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]
6976** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
6977**
6978** ^Each call to sqlite3_backup_step() sets two values inside
6979** the [sqlite3_backup] object: the number of pages still to be backed
6980** up and the total number of pages in the source database file.
6981** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
6982** retrieve these two values, respectively.
6983**
6984** ^The values returned by these functions are only updated by
6985** sqlite3_backup_step(). ^If the source database is modified during a backup
6986** operation, then the values are not updated to account for any extra
6987** pages that need to be updated or the size of the source database file
6988** changing.
6989**
6990** <b>Concurrent Usage of Database Handles</b>
6991**
6992** ^The source [database connection] may be used by the application for other
6993** purposes while a backup operation is underway or being initialized.
6994** ^If SQLite is compiled and configured to support threadsafe database
6995** connections, then the source database connection may be used concurrently
6996** from within other threads.
6997**
6998** However, the application must guarantee that the destination
6999** [database connection] is not passed to any other API (by any thread) after
7000** sqlite3_backup_init() is called and before the corresponding call to
7001** sqlite3_backup_finish().  SQLite does not currently check to see
7002** if the application incorrectly accesses the destination [database connection]
7003** and so no error code is reported, but the operations may malfunction
7004** nevertheless.  Use of the destination database connection while a
7005** backup is in progress might also also cause a mutex deadlock.
7006**
7007** If running in [shared cache mode], the application must
7008** guarantee that the shared cache used by the destination database
7009** is not accessed while the backup is running. In practice this means
7010** that the application must guarantee that the disk file being
7011** backed up to is not accessed by any connection within the process,
7012** not just the specific connection that was passed to sqlite3_backup_init().
7013**
7014** The [sqlite3_backup] object itself is partially threadsafe. Multiple
7015** threads may safely make multiple concurrent calls to sqlite3_backup_step().
7016** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
7017** APIs are not strictly speaking threadsafe. If they are invoked at the
7018** same time as another thread is invoking sqlite3_backup_step() it is
7019** possible that they return invalid values.
7020*/
7021SQLITE_API sqlite3_backup *sqlite3_backup_init(
7022  sqlite3 *pDest,                        /* Destination database handle */
7023  const char *zDestName,                 /* Destination database name */
7024  sqlite3 *pSource,                      /* Source database handle */
7025  const char *zSourceName                /* Source database name */
7026);
7027SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
7028SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
7029SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
7030SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
7031
7032/*
7033** CAPI3REF: Unlock Notification
7034**
7035** ^When running in shared-cache mode, a database operation may fail with
7036** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
7037** individual tables within the shared-cache cannot be obtained. See
7038** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
7039** ^This API may be used to register a callback that SQLite will invoke
7040** when the connection currently holding the required lock relinquishes it.
7041** ^This API is only available if the library was compiled with the
7042** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
7043**
7044** See Also: [Using the SQLite Unlock Notification Feature].
7045**
7046** ^Shared-cache locks are released when a database connection concludes
7047** its current transaction, either by committing it or rolling it back.
7048**
7049** ^When a connection (known as the blocked connection) fails to obtain a
7050** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
7051** identity of the database connection (the blocking connection) that
7052** has locked the required resource is stored internally. ^After an
7053** application receives an SQLITE_LOCKED error, it may call the
7054** sqlite3_unlock_notify() method with the blocked connection handle as
7055** the first argument to register for a callback that will be invoked
7056** when the blocking connections current transaction is concluded. ^The
7057** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
7058** call that concludes the blocking connections transaction.
7059**
7060** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
7061** there is a chance that the blocking connection will have already
7062** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
7063** If this happens, then the specified callback is invoked immediately,
7064** from within the call to sqlite3_unlock_notify().)^
7065**
7066** ^If the blocked connection is attempting to obtain a write-lock on a
7067** shared-cache table, and more than one other connection currently holds
7068** a read-lock on the same table, then SQLite arbitrarily selects one of
7069** the other connections to use as the blocking connection.
7070**
7071** ^(There may be at most one unlock-notify callback registered by a
7072** blocked connection. If sqlite3_unlock_notify() is called when the
7073** blocked connection already has a registered unlock-notify callback,
7074** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
7075** called with a NULL pointer as its second argument, then any existing
7076** unlock-notify callback is canceled. ^The blocked connections
7077** unlock-notify callback may also be canceled by closing the blocked
7078** connection using [sqlite3_close()].
7079**
7080** The unlock-notify callback is not reentrant. If an application invokes
7081** any sqlite3_xxx API functions from within an unlock-notify callback, a
7082** crash or deadlock may be the result.
7083**
7084** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
7085** returns SQLITE_OK.
7086**
7087** <b>Callback Invocation Details</b>
7088**
7089** When an unlock-notify callback is registered, the application provides a
7090** single void* pointer that is passed to the callback when it is invoked.
7091** However, the signature of the callback function allows SQLite to pass
7092** it an array of void* context pointers. The first argument passed to
7093** an unlock-notify callback is a pointer to an array of void* pointers,
7094** and the second is the number of entries in the array.
7095**
7096** When a blocking connections transaction is concluded, there may be
7097** more than one blocked connection that has registered for an unlock-notify
7098** callback. ^If two or more such blocked connections have specified the
7099** same callback function, then instead of invoking the callback function
7100** multiple times, it is invoked once with the set of void* context pointers
7101** specified by the blocked connections bundled together into an array.
7102** This gives the application an opportunity to prioritize any actions
7103** related to the set of unblocked database connections.
7104**
7105** <b>Deadlock Detection</b>
7106**
7107** Assuming that after registering for an unlock-notify callback a
7108** database waits for the callback to be issued before taking any further
7109** action (a reasonable assumption), then using this API may cause the
7110** application to deadlock. For example, if connection X is waiting for
7111** connection Y's transaction to be concluded, and similarly connection
7112** Y is waiting on connection X's transaction, then neither connection
7113** will proceed and the system may remain deadlocked indefinitely.
7114**
7115** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
7116** detection. ^If a given call to sqlite3_unlock_notify() would put the
7117** system in a deadlocked state, then SQLITE_LOCKED is returned and no
7118** unlock-notify callback is registered. The system is said to be in
7119** a deadlocked state if connection A has registered for an unlock-notify
7120** callback on the conclusion of connection B's transaction, and connection
7121** B has itself registered for an unlock-notify callback when connection
7122** A's transaction is concluded. ^Indirect deadlock is also detected, so
7123** the system is also considered to be deadlocked if connection B has
7124** registered for an unlock-notify callback on the conclusion of connection
7125** C's transaction, where connection C is waiting on connection A. ^Any
7126** number of levels of indirection are allowed.
7127**
7128** <b>The "DROP TABLE" Exception</b>
7129**
7130** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
7131** always appropriate to call sqlite3_unlock_notify(). There is however,
7132** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
7133** SQLite checks if there are any currently executing SELECT statements
7134** that belong to the same connection. If there are, SQLITE_LOCKED is
7135** returned. In this case there is no "blocking connection", so invoking
7136** sqlite3_unlock_notify() results in the unlock-notify callback being
7137** invoked immediately. If the application then re-attempts the "DROP TABLE"
7138** or "DROP INDEX" query, an infinite loop might be the result.
7139**
7140** One way around this problem is to check the extended error code returned
7141** by an sqlite3_step() call. ^(If there is a blocking connection, then the
7142** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
7143** the special "DROP TABLE/INDEX" case, the extended error code is just
7144** SQLITE_LOCKED.)^
7145*/
7146SQLITE_API int sqlite3_unlock_notify(
7147  sqlite3 *pBlocked,                          /* Waiting connection */
7148  void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
7149  void *pNotifyArg                            /* Argument to pass to xNotify */
7150);
7151
7152
7153/*
7154** CAPI3REF: String Comparison
7155**
7156** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
7157** and extensions to compare the contents of two buffers containing UTF-8
7158** strings in a case-independent fashion, using the same definition of "case
7159** independence" that SQLite uses internally when comparing identifiers.
7160*/
7161SQLITE_API int sqlite3_stricmp(const char *, const char *);
7162SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
7163
7164/*
7165** CAPI3REF: String Globbing
7166*
7167** ^The [sqlite3_strglob(P,X)] interface returns zero if string X matches
7168** the glob pattern P, and it returns non-zero if string X does not match
7169** the glob pattern P.  ^The definition of glob pattern matching used in
7170** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
7171** SQL dialect used by SQLite.  ^The sqlite3_strglob(P,X) function is case
7172** sensitive.
7173**
7174** Note that this routine returns zero on a match and non-zero if the strings
7175** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
7176*/
7177SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
7178
7179/*
7180** CAPI3REF: Error Logging Interface
7181**
7182** ^The [sqlite3_log()] interface writes a message into the [error log]
7183** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
7184** ^If logging is enabled, the zFormat string and subsequent arguments are
7185** used with [sqlite3_snprintf()] to generate the final output string.
7186**
7187** The sqlite3_log() interface is intended for use by extensions such as
7188** virtual tables, collating functions, and SQL functions.  While there is
7189** nothing to prevent an application from calling sqlite3_log(), doing so
7190** is considered bad form.
7191**
7192** The zFormat string must not be NULL.
7193**
7194** To avoid deadlocks and other threading problems, the sqlite3_log() routine
7195** will not use dynamically allocated memory.  The log message is stored in
7196** a fixed-length buffer on the stack.  If the log message is longer than
7197** a few hundred characters, it will be truncated to the length of the
7198** buffer.
7199*/
7200SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
7201
7202/*
7203** CAPI3REF: Write-Ahead Log Commit Hook
7204**
7205** ^The [sqlite3_wal_hook()] function is used to register a callback that
7206** will be invoked each time a database connection commits data to a
7207** [write-ahead log] (i.e. whenever a transaction is committed in
7208** [journal_mode | journal_mode=WAL mode]).
7209**
7210** ^The callback is invoked by SQLite after the commit has taken place and
7211** the associated write-lock on the database released, so the implementation
7212** may read, write or [checkpoint] the database as required.
7213**
7214** ^The first parameter passed to the callback function when it is invoked
7215** is a copy of the third parameter passed to sqlite3_wal_hook() when
7216** registering the callback. ^The second is a copy of the database handle.
7217** ^The third parameter is the name of the database that was written to -
7218** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
7219** is the number of pages currently in the write-ahead log file,
7220** including those that were just committed.
7221**
7222** The callback function should normally return [SQLITE_OK].  ^If an error
7223** code is returned, that error will propagate back up through the
7224** SQLite code base to cause the statement that provoked the callback
7225** to report an error, though the commit will have still occurred. If the
7226** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
7227** that does not correspond to any valid SQLite error code, the results
7228** are undefined.
7229**
7230** A single database handle may have at most a single write-ahead log callback
7231** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
7232** previously registered write-ahead log callback. ^Note that the
7233** [sqlite3_wal_autocheckpoint()] interface and the
7234** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
7235** those overwrite any prior [sqlite3_wal_hook()] settings.
7236*/
7237SQLITE_API void *sqlite3_wal_hook(
7238  sqlite3*,
7239  int(*)(void *,sqlite3*,const char*,int),
7240  void*
7241);
7242
7243/*
7244** CAPI3REF: Configure an auto-checkpoint
7245**
7246** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
7247** [sqlite3_wal_hook()] that causes any database on [database connection] D
7248** to automatically [checkpoint]
7249** after committing a transaction if there are N or
7250** more frames in the [write-ahead log] file.  ^Passing zero or
7251** a negative value as the nFrame parameter disables automatic
7252** checkpoints entirely.
7253**
7254** ^The callback registered by this function replaces any existing callback
7255** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
7256** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
7257** configured by this function.
7258**
7259** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
7260** from SQL.
7261**
7262** ^Every new [database connection] defaults to having the auto-checkpoint
7263** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
7264** pages.  The use of this interface
7265** is only necessary if the default setting is found to be suboptimal
7266** for a particular application.
7267*/
7268SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
7269
7270/*
7271** CAPI3REF: Checkpoint a database
7272**
7273** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
7274** on [database connection] D to be [checkpointed].  ^If X is NULL or an
7275** empty string, then a checkpoint is run on all databases of
7276** connection D.  ^If the database connection D is not in
7277** [WAL | write-ahead log mode] then this interface is a harmless no-op.
7278**
7279** ^The [wal_checkpoint pragma] can be used to invoke this interface
7280** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the
7281** [wal_autocheckpoint pragma] can be used to cause this interface to be
7282** run whenever the WAL reaches a certain size threshold.
7283**
7284** See also: [sqlite3_wal_checkpoint_v2()]
7285*/
7286SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
7287
7288/*
7289** CAPI3REF: Checkpoint a database
7290**
7291** Run a checkpoint operation on WAL database zDb attached to database
7292** handle db. The specific operation is determined by the value of the
7293** eMode parameter:
7294**
7295** <dl>
7296** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
7297**   Checkpoint as many frames as possible without waiting for any database
7298**   readers or writers to finish. Sync the db file if all frames in the log
7299**   are checkpointed. This mode is the same as calling
7300**   sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.
7301**
7302** <dt>SQLITE_CHECKPOINT_FULL<dd>
7303**   This mode blocks (calls the busy-handler callback) until there is no
7304**   database writer and all readers are reading from the most recent database
7305**   snapshot. It then checkpoints all frames in the log file and syncs the
7306**   database file. This call blocks database writers while it is running,
7307**   but not database readers.
7308**
7309** <dt>SQLITE_CHECKPOINT_RESTART<dd>
7310**   This mode works the same way as SQLITE_CHECKPOINT_FULL, except after
7311**   checkpointing the log file it blocks (calls the busy-handler callback)
7312**   until all readers are reading from the database file only. This ensures
7313**   that the next client to write to the database file restarts the log file
7314**   from the beginning. This call blocks database writers while it is running,
7315**   but not database readers.
7316** </dl>
7317**
7318** If pnLog is not NULL, then *pnLog is set to the total number of frames in
7319** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
7320** the total number of checkpointed frames (including any that were already
7321** checkpointed when this function is called). *pnLog and *pnCkpt may be
7322** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
7323** If no values are available because of an error, they are both set to -1
7324** before returning to communicate this to the caller.
7325**
7326** All calls obtain an exclusive "checkpoint" lock on the database file. If
7327** any other process is running a checkpoint operation at the same time, the
7328** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a
7329** busy-handler configured, it will not be invoked in this case.
7330**
7331** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive
7332** "writer" lock on the database file. If the writer lock cannot be obtained
7333** immediately, and a busy-handler is configured, it is invoked and the writer
7334** lock retried until either the busy-handler returns 0 or the lock is
7335** successfully obtained. The busy-handler is also invoked while waiting for
7336** database readers as described above. If the busy-handler returns 0 before
7337** the writer lock is obtained or while waiting for database readers, the
7338** checkpoint operation proceeds from that point in the same way as
7339** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
7340** without blocking any further. SQLITE_BUSY is returned in this case.
7341**
7342** If parameter zDb is NULL or points to a zero length string, then the
7343** specified operation is attempted on all WAL databases. In this case the
7344** values written to output parameters *pnLog and *pnCkpt are undefined. If
7345** an SQLITE_BUSY error is encountered when processing one or more of the
7346** attached WAL databases, the operation is still attempted on any remaining
7347** attached databases and SQLITE_BUSY is returned to the caller. If any other
7348** error occurs while processing an attached database, processing is abandoned
7349** and the error code returned to the caller immediately. If no error
7350** (SQLITE_BUSY or otherwise) is encountered while processing the attached
7351** databases, SQLITE_OK is returned.
7352**
7353** If database zDb is the name of an attached database that is not in WAL
7354** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
7355** zDb is not NULL (or a zero length string) and is not the name of any
7356** attached database, SQLITE_ERROR is returned to the caller.
7357*/
7358SQLITE_API int sqlite3_wal_checkpoint_v2(
7359  sqlite3 *db,                    /* Database handle */
7360  const char *zDb,                /* Name of attached database (or NULL) */
7361  int eMode,                      /* SQLITE_CHECKPOINT_* value */
7362  int *pnLog,                     /* OUT: Size of WAL log in frames */
7363  int *pnCkpt                     /* OUT: Total number of frames checkpointed */
7364);
7365
7366/*
7367** CAPI3REF: Checkpoint operation parameters
7368**
7369** These constants can be used as the 3rd parameter to
7370** [sqlite3_wal_checkpoint_v2()].  See the [sqlite3_wal_checkpoint_v2()]
7371** documentation for additional information about the meaning and use of
7372** each of these values.
7373*/
7374#define SQLITE_CHECKPOINT_PASSIVE 0
7375#define SQLITE_CHECKPOINT_FULL    1
7376#define SQLITE_CHECKPOINT_RESTART 2
7377
7378/*
7379** CAPI3REF: Virtual Table Interface Configuration
7380**
7381** This function may be called by either the [xConnect] or [xCreate] method
7382** of a [virtual table] implementation to configure
7383** various facets of the virtual table interface.
7384**
7385** If this interface is invoked outside the context of an xConnect or
7386** xCreate virtual table method then the behavior is undefined.
7387**
7388** At present, there is only one option that may be configured using
7389** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].)  Further options
7390** may be added in the future.
7391*/
7392SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
7393
7394/*
7395** CAPI3REF: Virtual Table Configuration Options
7396**
7397** These macros define the various options to the
7398** [sqlite3_vtab_config()] interface that [virtual table] implementations
7399** can use to customize and optimize their behavior.
7400**
7401** <dl>
7402** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
7403** <dd>Calls of the form
7404** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
7405** where X is an integer.  If X is zero, then the [virtual table] whose
7406** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
7407** support constraints.  In this configuration (which is the default) if
7408** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
7409** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
7410** specified as part of the users SQL statement, regardless of the actual
7411** ON CONFLICT mode specified.
7412**
7413** If X is non-zero, then the virtual table implementation guarantees
7414** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
7415** any modifications to internal or persistent data structures have been made.
7416** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
7417** is able to roll back a statement or database transaction, and abandon
7418** or continue processing the current SQL statement as appropriate.
7419** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
7420** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
7421** had been ABORT.
7422**
7423** Virtual table implementations that are required to handle OR REPLACE
7424** must do so within the [xUpdate] method. If a call to the
7425** [sqlite3_vtab_on_conflict()] function indicates that the current ON
7426** CONFLICT policy is REPLACE, the virtual table implementation should
7427** silently replace the appropriate rows within the xUpdate callback and
7428** return SQLITE_OK. Or, if this is not possible, it may return
7429** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
7430** constraint handling.
7431** </dl>
7432*/
7433#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
7434
7435/*
7436** CAPI3REF: Determine The Virtual Table Conflict Policy
7437**
7438** This function may only be called from within a call to the [xUpdate] method
7439** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
7440** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
7441** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
7442** of the SQL statement that triggered the call to the [xUpdate] method of the
7443** [virtual table].
7444*/
7445SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
7446
7447/*
7448** CAPI3REF: Conflict resolution modes
7449**
7450** These constants are returned by [sqlite3_vtab_on_conflict()] to
7451** inform a [virtual table] implementation what the [ON CONFLICT] mode
7452** is for the SQL statement being evaluated.
7453**
7454** Note that the [SQLITE_IGNORE] constant is also used as a potential
7455** return value from the [sqlite3_set_authorizer()] callback and that
7456** [SQLITE_ABORT] is also a [result code].
7457*/
7458#define SQLITE_ROLLBACK 1
7459/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
7460#define SQLITE_FAIL     3
7461/* #define SQLITE_ABORT 4  // Also an error code */
7462#define SQLITE_REPLACE  5
7463
7464
7465
7466/*
7467** Undo the hack that converts floating point types to integer for
7468** builds on processors without floating point support.
7469*/
7470#ifdef SQLITE_OMIT_FLOATING_POINT
7471# undef double
7472#endif
7473
7474#if 0
7475}  /* End of the 'extern "C"' block */
7476#endif
7477#endif /* _SQLITE3_H_ */
7478
7479/*
7480** 2010 August 30
7481**
7482** The author disclaims copyright to this source code.  In place of
7483** a legal notice, here is a blessing:
7484**
7485**    May you do good and not evil.
7486**    May you find forgiveness for yourself and forgive others.
7487**    May you share freely, never taking more than you give.
7488**
7489*************************************************************************
7490*/
7491
7492#ifndef _SQLITE3RTREE_H_
7493#define _SQLITE3RTREE_H_
7494
7495
7496#if 0
7497extern "C" {
7498#endif
7499
7500typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
7501typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
7502
7503/* The double-precision datatype used by RTree depends on the
7504** SQLITE_RTREE_INT_ONLY compile-time option.
7505*/
7506#ifdef SQLITE_RTREE_INT_ONLY
7507  typedef sqlite3_int64 sqlite3_rtree_dbl;
7508#else
7509  typedef double sqlite3_rtree_dbl;
7510#endif
7511
7512/*
7513** Register a geometry callback named zGeom that can be used as part of an
7514** R-Tree geometry query as follows:
7515**
7516**   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
7517*/
7518SQLITE_API int sqlite3_rtree_geometry_callback(
7519  sqlite3 *db,
7520  const char *zGeom,
7521  int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
7522  void *pContext
7523);
7524
7525
7526/*
7527** A pointer to a structure of the following type is passed as the first
7528** argument to callbacks registered using rtree_geometry_callback().
7529*/
7530struct sqlite3_rtree_geometry {
7531  void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
7532  int nParam;                     /* Size of array aParam[] */
7533  sqlite3_rtree_dbl *aParam;      /* Parameters passed to SQL geom function */
7534  void *pUser;                    /* Callback implementation user data */
7535  void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
7536};
7537
7538/*
7539** Register a 2nd-generation geometry callback named zScore that can be
7540** used as part of an R-Tree geometry query as follows:
7541**
7542**   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
7543*/
7544SQLITE_API int sqlite3_rtree_query_callback(
7545  sqlite3 *db,
7546  const char *zQueryFunc,
7547  int (*xQueryFunc)(sqlite3_rtree_query_info*),
7548  void *pContext,
7549  void (*xDestructor)(void*)
7550);
7551
7552
7553/*
7554** A pointer to a structure of the following type is passed as the
7555** argument to scored geometry callback registered using
7556** sqlite3_rtree_query_callback().
7557**
7558** Note that the first 5 fields of this structure are identical to
7559** sqlite3_rtree_geometry.  This structure is a subclass of
7560** sqlite3_rtree_geometry.
7561*/
7562struct sqlite3_rtree_query_info {
7563  void *pContext;                   /* pContext from when function registered */
7564  int nParam;                       /* Number of function parameters */
7565  sqlite3_rtree_dbl *aParam;        /* value of function parameters */
7566  void *pUser;                      /* callback can use this, if desired */
7567  void (*xDelUser)(void*);          /* function to free pUser */
7568  sqlite3_rtree_dbl *aCoord;        /* Coordinates of node or entry to check */
7569  unsigned int *anQueue;            /* Number of pending entries in the queue */
7570  int nCoord;                       /* Number of coordinates */
7571  int iLevel;                       /* Level of current node or entry */
7572  int mxLevel;                      /* The largest iLevel value in the tree */
7573  sqlite3_int64 iRowid;             /* Rowid for current entry */
7574  sqlite3_rtree_dbl rParentScore;   /* Score of parent node */
7575  int eParentWithin;                /* Visibility of parent node */
7576  int eWithin;                      /* OUT: Visiblity */
7577  sqlite3_rtree_dbl rScore;         /* OUT: Write the score here */
7578};
7579
7580/*
7581** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
7582*/
7583#define NOT_WITHIN       0   /* Object completely outside of query region */
7584#define PARTLY_WITHIN    1   /* Object partially overlaps query region */
7585#define FULLY_WITHIN     2   /* Object fully contained within query region */
7586
7587
7588#if 0
7589}  /* end of the 'extern "C"' block */
7590#endif
7591
7592#endif  /* ifndef _SQLITE3RTREE_H_ */
7593
7594
7595/************** End of sqlite3.h *********************************************/
7596/************** Continuing where we left off in sqliteInt.h ******************/
7597
7598/*
7599** Include the configuration header output by 'configure' if we're using the
7600** autoconf-based build
7601*/
7602#ifdef _HAVE_SQLITE_CONFIG_H
7603#include "config.h"
7604#endif
7605
7606/************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
7607/************** Begin file sqliteLimit.h *************************************/
7608/*
7609** 2007 May 7
7610**
7611** The author disclaims copyright to this source code.  In place of
7612** a legal notice, here is a blessing:
7613**
7614**    May you do good and not evil.
7615**    May you find forgiveness for yourself and forgive others.
7616**    May you share freely, never taking more than you give.
7617**
7618*************************************************************************
7619**
7620** This file defines various limits of what SQLite can process.
7621*/
7622
7623/*
7624** The maximum length of a TEXT or BLOB in bytes.   This also
7625** limits the size of a row in a table or index.
7626**
7627** The hard limit is the ability of a 32-bit signed integer
7628** to count the size: 2^31-1 or 2147483647.
7629*/
7630#ifndef SQLITE_MAX_LENGTH
7631# define SQLITE_MAX_LENGTH 1000000000
7632#endif
7633
7634/*
7635** This is the maximum number of
7636**
7637**    * Columns in a table
7638**    * Columns in an index
7639**    * Columns in a view
7640**    * Terms in the SET clause of an UPDATE statement
7641**    * Terms in the result set of a SELECT statement
7642**    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
7643**    * Terms in the VALUES clause of an INSERT statement
7644**
7645** The hard upper limit here is 32676.  Most database people will
7646** tell you that in a well-normalized database, you usually should
7647** not have more than a dozen or so columns in any table.  And if
7648** that is the case, there is no point in having more than a few
7649** dozen values in any of the other situations described above.
7650*/
7651#ifndef SQLITE_MAX_COLUMN
7652# define SQLITE_MAX_COLUMN 2000
7653#endif
7654
7655/*
7656** The maximum length of a single SQL statement in bytes.
7657**
7658** It used to be the case that setting this value to zero would
7659** turn the limit off.  That is no longer true.  It is not possible
7660** to turn this limit off.
7661*/
7662#ifndef SQLITE_MAX_SQL_LENGTH
7663# define SQLITE_MAX_SQL_LENGTH 1000000000
7664#endif
7665
7666/*
7667** The maximum depth of an expression tree. This is limited to
7668** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
7669** want to place more severe limits on the complexity of an
7670** expression.
7671**
7672** A value of 0 used to mean that the limit was not enforced.
7673** But that is no longer true.  The limit is now strictly enforced
7674** at all times.
7675*/
7676#ifndef SQLITE_MAX_EXPR_DEPTH
7677# define SQLITE_MAX_EXPR_DEPTH 1000
7678#endif
7679
7680/*
7681** The maximum number of terms in a compound SELECT statement.
7682** The code generator for compound SELECT statements does one
7683** level of recursion for each term.  A stack overflow can result
7684** if the number of terms is too large.  In practice, most SQL
7685** never has more than 3 or 4 terms.  Use a value of 0 to disable
7686** any limit on the number of terms in a compount SELECT.
7687*/
7688#ifndef SQLITE_MAX_COMPOUND_SELECT
7689# define SQLITE_MAX_COMPOUND_SELECT 500
7690#endif
7691
7692/*
7693** The maximum number of opcodes in a VDBE program.
7694** Not currently enforced.
7695*/
7696#ifndef SQLITE_MAX_VDBE_OP
7697# define SQLITE_MAX_VDBE_OP 25000
7698#endif
7699
7700/*
7701** The maximum number of arguments to an SQL function.
7702*/
7703#ifndef SQLITE_MAX_FUNCTION_ARG
7704# define SQLITE_MAX_FUNCTION_ARG 127
7705#endif
7706
7707/*
7708** The maximum number of in-memory pages to use for the main database
7709** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
7710*/
7711#ifndef SQLITE_DEFAULT_CACHE_SIZE
7712# define SQLITE_DEFAULT_CACHE_SIZE  2000
7713#endif
7714#ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
7715# define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
7716#endif
7717
7718/*
7719** The default number of frames to accumulate in the log file before
7720** checkpointing the database in WAL mode.
7721*/
7722#ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
7723# define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
7724#endif
7725
7726/*
7727** The maximum number of attached databases.  This must be between 0
7728** and 62.  The upper bound on 62 is because a 64-bit integer bitmap
7729** is used internally to track attached databases.
7730*/
7731#ifndef SQLITE_MAX_ATTACHED
7732# define SQLITE_MAX_ATTACHED 10
7733#endif
7734
7735
7736/*
7737** The maximum value of a ?nnn wildcard that the parser will accept.
7738*/
7739#ifndef SQLITE_MAX_VARIABLE_NUMBER
7740# define SQLITE_MAX_VARIABLE_NUMBER 999
7741#endif
7742
7743/* Maximum page size.  The upper bound on this value is 65536.  This a limit
7744** imposed by the use of 16-bit offsets within each page.
7745**
7746** Earlier versions of SQLite allowed the user to change this value at
7747** compile time. This is no longer permitted, on the grounds that it creates
7748** a library that is technically incompatible with an SQLite library
7749** compiled with a different limit. If a process operating on a database
7750** with a page-size of 65536 bytes crashes, then an instance of SQLite
7751** compiled with the default page-size limit will not be able to rollback
7752** the aborted transaction. This could lead to database corruption.
7753*/
7754#ifdef SQLITE_MAX_PAGE_SIZE
7755# undef SQLITE_MAX_PAGE_SIZE
7756#endif
7757#define SQLITE_MAX_PAGE_SIZE 65536
7758
7759
7760/*
7761** The default size of a database page.
7762*/
7763#ifndef SQLITE_DEFAULT_PAGE_SIZE
7764# define SQLITE_DEFAULT_PAGE_SIZE 1024
7765#endif
7766#if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
7767# undef SQLITE_DEFAULT_PAGE_SIZE
7768# define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
7769#endif
7770
7771/*
7772** Ordinarily, if no value is explicitly provided, SQLite creates databases
7773** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
7774** device characteristics (sector-size and atomic write() support),
7775** SQLite may choose a larger value. This constant is the maximum value
7776** SQLite will choose on its own.
7777*/
7778#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
7779# define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
7780#endif
7781#if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
7782# undef SQLITE_MAX_DEFAULT_PAGE_SIZE
7783# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
7784#endif
7785
7786
7787/*
7788** Maximum number of pages in one database file.
7789**
7790** This is really just the default value for the max_page_count pragma.
7791** This value can be lowered (or raised) at run-time using that the
7792** max_page_count macro.
7793*/
7794#ifndef SQLITE_MAX_PAGE_COUNT
7795# define SQLITE_MAX_PAGE_COUNT 1073741823
7796#endif
7797
7798/*
7799** Maximum length (in bytes) of the pattern in a LIKE or GLOB
7800** operator.
7801*/
7802#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
7803# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
7804#endif
7805
7806/*
7807** Maximum depth of recursion for triggers.
7808**
7809** A value of 1 means that a trigger program will not be able to itself
7810** fire any triggers. A value of 0 means that no trigger programs at all
7811** may be executed.
7812*/
7813#ifndef SQLITE_MAX_TRIGGER_DEPTH
7814# define SQLITE_MAX_TRIGGER_DEPTH 1000
7815#endif
7816
7817/************** End of sqliteLimit.h *****************************************/
7818/************** Continuing where we left off in sqliteInt.h ******************/
7819
7820/* Disable nuisance warnings on Borland compilers */
7821#if defined(__BORLANDC__)
7822#pragma warn -rch /* unreachable code */
7823#pragma warn -ccc /* Condition is always true or false */
7824#pragma warn -aus /* Assigned value is never used */
7825#pragma warn -csu /* Comparing signed and unsigned */
7826#pragma warn -spa /* Suspicious pointer arithmetic */
7827#endif
7828
7829/* Needed for various definitions... */
7830#ifndef _GNU_SOURCE
7831# define _GNU_SOURCE
7832#endif
7833
7834#if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
7835# define _BSD_SOURCE
7836#endif
7837
7838/*
7839** Include standard header files as necessary
7840*/
7841#ifdef HAVE_STDINT_H
7842#include <stdint.h>
7843#endif
7844#ifdef HAVE_INTTYPES_H
7845#include <inttypes.h>
7846#endif
7847
7848/*
7849** The following macros are used to cast pointers to integers and
7850** integers to pointers.  The way you do this varies from one compiler
7851** to the next, so we have developed the following set of #if statements
7852** to generate appropriate macros for a wide range of compilers.
7853**
7854** The correct "ANSI" way to do this is to use the intptr_t type.
7855** Unfortunately, that typedef is not available on all compilers, or
7856** if it is available, it requires an #include of specific headers
7857** that vary from one machine to the next.
7858**
7859** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
7860** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
7861** So we have to define the macros in different ways depending on the
7862** compiler.
7863*/
7864#if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
7865# define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
7866# define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
7867#elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
7868# define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
7869# define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
7870#elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
7871# define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
7872# define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
7873#else                          /* Generates a warning - but it always works */
7874# define SQLITE_INT_TO_PTR(X)  ((void*)(X))
7875# define SQLITE_PTR_TO_INT(X)  ((int)(X))
7876#endif
7877
7878/*
7879** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
7880** 0 means mutexes are permanently disable and the library is never
7881** threadsafe.  1 means the library is serialized which is the highest
7882** level of threadsafety.  2 means the library is multithreaded - multiple
7883** threads can use SQLite as long as no two threads try to use the same
7884** database connection at the same time.
7885**
7886** Older versions of SQLite used an optional THREADSAFE macro.
7887** We support that for legacy.
7888*/
7889#if !defined(SQLITE_THREADSAFE)
7890# if defined(THREADSAFE)
7891#   define SQLITE_THREADSAFE THREADSAFE
7892# else
7893#   define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
7894# endif
7895#endif
7896
7897/*
7898** Powersafe overwrite is on by default.  But can be turned off using
7899** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
7900*/
7901#ifndef SQLITE_POWERSAFE_OVERWRITE
7902# define SQLITE_POWERSAFE_OVERWRITE 1
7903#endif
7904
7905/*
7906** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
7907** It determines whether or not the features related to
7908** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
7909** be overridden at runtime using the sqlite3_config() API.
7910*/
7911#if !defined(SQLITE_DEFAULT_MEMSTATUS)
7912# define SQLITE_DEFAULT_MEMSTATUS 1
7913#endif
7914
7915/*
7916** Exactly one of the following macros must be defined in order to
7917** specify which memory allocation subsystem to use.
7918**
7919**     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
7920**     SQLITE_WIN32_MALLOC           // Use Win32 native heap API
7921**     SQLITE_ZERO_MALLOC            // Use a stub allocator that always fails
7922**     SQLITE_MEMDEBUG               // Debugging version of system malloc()
7923**
7924** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
7925** assert() macro is enabled, each call into the Win32 native heap subsystem
7926** will cause HeapValidate to be called.  If heap validation should fail, an
7927** assertion will be triggered.
7928**
7929** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
7930** the default.
7931*/
7932#if defined(SQLITE_SYSTEM_MALLOC) \
7933  + defined(SQLITE_WIN32_MALLOC) \
7934  + defined(SQLITE_ZERO_MALLOC) \
7935  + defined(SQLITE_MEMDEBUG)>1
7936# error "Two or more of the following compile-time configuration options\
7937 are defined but at most one is allowed:\
7938 SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
7939 SQLITE_ZERO_MALLOC"
7940#endif
7941#if defined(SQLITE_SYSTEM_MALLOC) \
7942  + defined(SQLITE_WIN32_MALLOC) \
7943  + defined(SQLITE_ZERO_MALLOC) \
7944  + defined(SQLITE_MEMDEBUG)==0
7945# define SQLITE_SYSTEM_MALLOC 1
7946#endif
7947
7948/*
7949** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
7950** sizes of memory allocations below this value where possible.
7951*/
7952#if !defined(SQLITE_MALLOC_SOFT_LIMIT)
7953# define SQLITE_MALLOC_SOFT_LIMIT 1024
7954#endif
7955
7956/*
7957** We need to define _XOPEN_SOURCE as follows in order to enable
7958** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
7959** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
7960** it.
7961*/
7962#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
7963#  define _XOPEN_SOURCE 600
7964#endif
7965
7966/*
7967** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that
7968** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,
7969** make it true by defining or undefining NDEBUG.
7970**
7971** Setting NDEBUG makes the code smaller and faster by disabling the
7972** assert() statements in the code.  So we want the default action
7973** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
7974** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
7975** feature.
7976*/
7977#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
7978# define NDEBUG 1
7979#endif
7980#if defined(NDEBUG) && defined(SQLITE_DEBUG)
7981# undef NDEBUG
7982#endif
7983
7984/*
7985** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
7986*/
7987#if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
7988# define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
7989#endif
7990
7991/*
7992** The testcase() macro is used to aid in coverage testing.  When
7993** doing coverage testing, the condition inside the argument to
7994** testcase() must be evaluated both true and false in order to
7995** get full branch coverage.  The testcase() macro is inserted
7996** to help ensure adequate test coverage in places where simple
7997** condition/decision coverage is inadequate.  For example, testcase()
7998** can be used to make sure boundary values are tested.  For
7999** bitmask tests, testcase() can be used to make sure each bit
8000** is significant and used at least once.  On switch statements
8001** where multiple cases go to the same block of code, testcase()
8002** can insure that all cases are evaluated.
8003**
8004*/
8005#ifdef SQLITE_COVERAGE_TEST
8006SQLITE_PRIVATE   void sqlite3Coverage(int);
8007# define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
8008#else
8009# define testcase(X)
8010#endif
8011
8012/*
8013** The TESTONLY macro is used to enclose variable declarations or
8014** other bits of code that are needed to support the arguments
8015** within testcase() and assert() macros.
8016*/
8017#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
8018# define TESTONLY(X)  X
8019#else
8020# define TESTONLY(X)
8021#endif
8022
8023/*
8024** Sometimes we need a small amount of code such as a variable initialization
8025** to setup for a later assert() statement.  We do not want this code to
8026** appear when assert() is disabled.  The following macro is therefore
8027** used to contain that setup code.  The "VVA" acronym stands for
8028** "Verification, Validation, and Accreditation".  In other words, the
8029** code within VVA_ONLY() will only run during verification processes.
8030*/
8031#ifndef NDEBUG
8032# define VVA_ONLY(X)  X
8033#else
8034# define VVA_ONLY(X)
8035#endif
8036
8037/*
8038** The ALWAYS and NEVER macros surround boolean expressions which
8039** are intended to always be true or false, respectively.  Such
8040** expressions could be omitted from the code completely.  But they
8041** are included in a few cases in order to enhance the resilience
8042** of SQLite to unexpected behavior - to make the code "self-healing"
8043** or "ductile" rather than being "brittle" and crashing at the first
8044** hint of unplanned behavior.
8045**
8046** In other words, ALWAYS and NEVER are added for defensive code.
8047**
8048** When doing coverage testing ALWAYS and NEVER are hard-coded to
8049** be true and false so that the unreachable code they specify will
8050** not be counted as untested code.
8051*/
8052#if defined(SQLITE_COVERAGE_TEST)
8053# define ALWAYS(X)      (1)
8054# define NEVER(X)       (0)
8055#elif !defined(NDEBUG)
8056# define ALWAYS(X)      ((X)?1:(assert(0),0))
8057# define NEVER(X)       ((X)?(assert(0),1):0)
8058#else
8059# define ALWAYS(X)      (X)
8060# define NEVER(X)       (X)
8061#endif
8062
8063/*
8064** Return true (non-zero) if the input is a integer that is too large
8065** to fit in 32-bits.  This macro is used inside of various testcase()
8066** macros to verify that we have tested SQLite for large-file support.
8067*/
8068#define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
8069
8070/*
8071** The macro unlikely() is a hint that surrounds a boolean
8072** expression that is usually false.  Macro likely() surrounds
8073** a boolean expression that is usually true.  These hints could,
8074** in theory, be used by the compiler to generate better code, but
8075** currently they are just comments for human readers.
8076*/
8077#define likely(X)    (X)
8078#define unlikely(X)  (X)
8079
8080/************** Include hash.h in the middle of sqliteInt.h ******************/
8081/************** Begin file hash.h ********************************************/
8082/*
8083** 2001 September 22
8084**
8085** The author disclaims copyright to this source code.  In place of
8086** a legal notice, here is a blessing:
8087**
8088**    May you do good and not evil.
8089**    May you find forgiveness for yourself and forgive others.
8090**    May you share freely, never taking more than you give.
8091**
8092*************************************************************************
8093** This is the header file for the generic hash-table implementation
8094** used in SQLite.
8095*/
8096#ifndef _SQLITE_HASH_H_
8097#define _SQLITE_HASH_H_
8098
8099/* Forward declarations of structures. */
8100typedef struct Hash Hash;
8101typedef struct HashElem HashElem;
8102
8103/* A complete hash table is an instance of the following structure.
8104** The internals of this structure are intended to be opaque -- client
8105** code should not attempt to access or modify the fields of this structure
8106** directly.  Change this structure only by using the routines below.
8107** However, some of the "procedures" and "functions" for modifying and
8108** accessing this structure are really macros, so we can't really make
8109** this structure opaque.
8110**
8111** All elements of the hash table are on a single doubly-linked list.
8112** Hash.first points to the head of this list.
8113**
8114** There are Hash.htsize buckets.  Each bucket points to a spot in
8115** the global doubly-linked list.  The contents of the bucket are the
8116** element pointed to plus the next _ht.count-1 elements in the list.
8117**
8118** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
8119** by a linear search of the global list.  For small tables, the
8120** Hash.ht table is never allocated because if there are few elements
8121** in the table, it is faster to do a linear search than to manage
8122** the hash table.
8123*/
8124struct Hash {
8125  unsigned int htsize;      /* Number of buckets in the hash table */
8126  unsigned int count;       /* Number of entries in this table */
8127  HashElem *first;          /* The first element of the array */
8128  struct _ht {              /* the hash table */
8129    int count;                 /* Number of entries with this hash */
8130    HashElem *chain;           /* Pointer to first entry with this hash */
8131  } *ht;
8132};
8133
8134/* Each element in the hash table is an instance of the following
8135** structure.  All elements are stored on a single doubly-linked list.
8136**
8137** Again, this structure is intended to be opaque, but it can't really
8138** be opaque because it is used by macros.
8139*/
8140struct HashElem {
8141  HashElem *next, *prev;       /* Next and previous elements in the table */
8142  void *data;                  /* Data associated with this element */
8143  const char *pKey; int nKey;  /* Key associated with this element */
8144};
8145
8146/*
8147** Access routines.  To delete, insert a NULL pointer.
8148*/
8149SQLITE_PRIVATE void sqlite3HashInit(Hash*);
8150SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
8151SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
8152SQLITE_PRIVATE void sqlite3HashClear(Hash*);
8153
8154/*
8155** Macros for looping over all elements of a hash table.  The idiom is
8156** like this:
8157**
8158**   Hash h;
8159**   HashElem *p;
8160**   ...
8161**   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
8162**     SomeStructure *pData = sqliteHashData(p);
8163**     // do something with pData
8164**   }
8165*/
8166#define sqliteHashFirst(H)  ((H)->first)
8167#define sqliteHashNext(E)   ((E)->next)
8168#define sqliteHashData(E)   ((E)->data)
8169/* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
8170/* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
8171
8172/*
8173** Number of entries in a hash table
8174*/
8175/* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
8176
8177#endif /* _SQLITE_HASH_H_ */
8178
8179/************** End of hash.h ************************************************/
8180/************** Continuing where we left off in sqliteInt.h ******************/
8181/************** Include parse.h in the middle of sqliteInt.h *****************/
8182/************** Begin file parse.h *******************************************/
8183#define TK_SEMI                             1
8184#define TK_EXPLAIN                          2
8185#define TK_QUERY                            3
8186#define TK_PLAN                             4
8187#define TK_BEGIN                            5
8188#define TK_TRANSACTION                      6
8189#define TK_DEFERRED                         7
8190#define TK_IMMEDIATE                        8
8191#define TK_EXCLUSIVE                        9
8192#define TK_COMMIT                          10
8193#define TK_END                             11
8194#define TK_ROLLBACK                        12
8195#define TK_SAVEPOINT                       13
8196#define TK_RELEASE                         14
8197#define TK_TO                              15
8198#define TK_TABLE                           16
8199#define TK_CREATE                          17
8200#define TK_IF                              18
8201#define TK_NOT                             19
8202#define TK_EXISTS                          20
8203#define TK_TEMP                            21
8204#define TK_LP                              22
8205#define TK_RP                              23
8206#define TK_AS                              24
8207#define TK_WITHOUT                         25
8208#define TK_COMMA                           26
8209#define TK_ID                              27
8210#define TK_INDEXED                         28
8211#define TK_ABORT                           29
8212#define TK_ACTION                          30
8213#define TK_AFTER                           31
8214#define TK_ANALYZE                         32
8215#define TK_ASC                             33
8216#define TK_ATTACH                          34
8217#define TK_BEFORE                          35
8218#define TK_BY                              36
8219#define TK_CASCADE                         37
8220#define TK_CAST                            38
8221#define TK_COLUMNKW                        39
8222#define TK_CONFLICT                        40
8223#define TK_DATABASE                        41
8224#define TK_DESC                            42
8225#define TK_DETACH                          43
8226#define TK_EACH                            44
8227#define TK_FAIL                            45
8228#define TK_FOR                             46
8229#define TK_IGNORE                          47
8230#define TK_INITIALLY                       48
8231#define TK_INSTEAD                         49
8232#define TK_LIKE_KW                         50
8233#define TK_MATCH                           51
8234#define TK_NO                              52
8235#define TK_KEY                             53
8236#define TK_OF                              54
8237#define TK_OFFSET                          55
8238#define TK_PRAGMA                          56
8239#define TK_RAISE                           57
8240#define TK_RECURSIVE                       58
8241#define TK_REPLACE                         59
8242#define TK_RESTRICT                        60
8243#define TK_ROW                             61
8244#define TK_TRIGGER                         62
8245#define TK_VACUUM                          63
8246#define TK_VIEW                            64
8247#define TK_VIRTUAL                         65
8248#define TK_WITH                            66
8249#define TK_REINDEX                         67
8250#define TK_RENAME                          68
8251#define TK_CTIME_KW                        69
8252#define TK_ANY                             70
8253#define TK_OR                              71
8254#define TK_AND                             72
8255#define TK_IS                              73
8256#define TK_BETWEEN                         74
8257#define TK_IN                              75
8258#define TK_ISNULL                          76
8259#define TK_NOTNULL                         77
8260#define TK_NE                              78
8261#define TK_EQ                              79
8262#define TK_GT                              80
8263#define TK_LE                              81
8264#define TK_LT                              82
8265#define TK_GE                              83
8266#define TK_ESCAPE                          84
8267#define TK_BITAND                          85
8268#define TK_BITOR                           86
8269#define TK_LSHIFT                          87
8270#define TK_RSHIFT                          88
8271#define TK_PLUS                            89
8272#define TK_MINUS                           90
8273#define TK_STAR                            91
8274#define TK_SLASH                           92
8275#define TK_REM                             93
8276#define TK_CONCAT                          94
8277#define TK_COLLATE                         95
8278#define TK_BITNOT                          96
8279#define TK_STRING                          97
8280#define TK_JOIN_KW                         98
8281#define TK_CONSTRAINT                      99
8282#define TK_DEFAULT                        100
8283#define TK_NULL                           101
8284#define TK_PRIMARY                        102
8285#define TK_UNIQUE                         103
8286#define TK_CHECK                          104
8287#define TK_REFERENCES                     105
8288#define TK_AUTOINCR                       106
8289#define TK_ON                             107
8290#define TK_INSERT                         108
8291#define TK_DELETE                         109
8292#define TK_UPDATE                         110
8293#define TK_SET                            111
8294#define TK_DEFERRABLE                     112
8295#define TK_FOREIGN                        113
8296#define TK_DROP                           114
8297#define TK_UNION                          115
8298#define TK_ALL                            116
8299#define TK_EXCEPT                         117
8300#define TK_INTERSECT                      118
8301#define TK_SELECT                         119
8302#define TK_VALUES                         120
8303#define TK_DISTINCT                       121
8304#define TK_DOT                            122
8305#define TK_FROM                           123
8306#define TK_JOIN                           124
8307#define TK_USING                          125
8308#define TK_ORDER                          126
8309#define TK_GROUP                          127
8310#define TK_HAVING                         128
8311#define TK_LIMIT                          129
8312#define TK_WHERE                          130
8313#define TK_INTO                           131
8314#define TK_INTEGER                        132
8315#define TK_FLOAT                          133
8316#define TK_BLOB                           134
8317#define TK_VARIABLE                       135
8318#define TK_CASE                           136
8319#define TK_WHEN                           137
8320#define TK_THEN                           138
8321#define TK_ELSE                           139
8322#define TK_INDEX                          140
8323#define TK_ALTER                          141
8324#define TK_ADD                            142
8325#define TK_TO_TEXT                        143
8326#define TK_TO_BLOB                        144
8327#define TK_TO_NUMERIC                     145
8328#define TK_TO_INT                         146
8329#define TK_TO_REAL                        147
8330#define TK_ISNOT                          148
8331#define TK_END_OF_FILE                    149
8332#define TK_ILLEGAL                        150
8333#define TK_SPACE                          151
8334#define TK_UNCLOSED_STRING                152
8335#define TK_FUNCTION                       153
8336#define TK_COLUMN                         154
8337#define TK_AGG_FUNCTION                   155
8338#define TK_AGG_COLUMN                     156
8339#define TK_UMINUS                         157
8340#define TK_UPLUS                          158
8341#define TK_REGISTER                       159
8342
8343/************** End of parse.h ***********************************************/
8344/************** Continuing where we left off in sqliteInt.h ******************/
8345#include <stdio.h>
8346#include <stdlib.h>
8347#include <string.h>
8348#include <assert.h>
8349#include <stddef.h>
8350
8351/*
8352** If compiling for a processor that lacks floating point support,
8353** substitute integer for floating-point
8354*/
8355#ifdef SQLITE_OMIT_FLOATING_POINT
8356# define double sqlite_int64
8357# define float sqlite_int64
8358# define LONGDOUBLE_TYPE sqlite_int64
8359# ifndef SQLITE_BIG_DBL
8360#   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
8361# endif
8362# define SQLITE_OMIT_DATETIME_FUNCS 1
8363# define SQLITE_OMIT_TRACE 1
8364# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
8365# undef SQLITE_HAVE_ISNAN
8366#endif
8367#ifndef SQLITE_BIG_DBL
8368# define SQLITE_BIG_DBL (1e99)
8369#endif
8370
8371/*
8372** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
8373** afterward. Having this macro allows us to cause the C compiler
8374** to omit code used by TEMP tables without messy #ifndef statements.
8375*/
8376#ifdef SQLITE_OMIT_TEMPDB
8377#define OMIT_TEMPDB 1
8378#else
8379#define OMIT_TEMPDB 0
8380#endif
8381
8382/*
8383** The "file format" number is an integer that is incremented whenever
8384** the VDBE-level file format changes.  The following macros define the
8385** the default file format for new databases and the maximum file format
8386** that the library can read.
8387*/
8388#define SQLITE_MAX_FILE_FORMAT 4
8389#ifndef SQLITE_DEFAULT_FILE_FORMAT
8390# define SQLITE_DEFAULT_FILE_FORMAT 4
8391#endif
8392
8393/*
8394** Determine whether triggers are recursive by default.  This can be
8395** changed at run-time using a pragma.
8396*/
8397#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
8398# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
8399#endif
8400
8401/*
8402** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
8403** on the command-line
8404*/
8405#ifndef SQLITE_TEMP_STORE
8406# define SQLITE_TEMP_STORE 1
8407# define SQLITE_TEMP_STORE_xc 1  /* Exclude from ctime.c */
8408#endif
8409
8410/*
8411** GCC does not define the offsetof() macro so we'll have to do it
8412** ourselves.
8413*/
8414#ifndef offsetof
8415#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
8416#endif
8417
8418/*
8419** Macros to compute minimum and maximum of two numbers.
8420*/
8421#define MIN(A,B) ((A)<(B)?(A):(B))
8422#define MAX(A,B) ((A)>(B)?(A):(B))
8423
8424/*
8425** Check to see if this machine uses EBCDIC.  (Yes, believe it or
8426** not, there are still machines out there that use EBCDIC.)
8427*/
8428#if 'A' == '\301'
8429# define SQLITE_EBCDIC 1
8430#else
8431# define SQLITE_ASCII 1
8432#endif
8433
8434/*
8435** Integers of known sizes.  These typedefs might change for architectures
8436** where the sizes very.  Preprocessor macros are available so that the
8437** types can be conveniently redefined at compile-type.  Like this:
8438**
8439**         cc '-DUINTPTR_TYPE=long long int' ...
8440*/
8441#ifndef UINT32_TYPE
8442# ifdef HAVE_UINT32_T
8443#  define UINT32_TYPE uint32_t
8444# else
8445#  define UINT32_TYPE unsigned int
8446# endif
8447#endif
8448#ifndef UINT16_TYPE
8449# ifdef HAVE_UINT16_T
8450#  define UINT16_TYPE uint16_t
8451# else
8452#  define UINT16_TYPE unsigned short int
8453# endif
8454#endif
8455#ifndef INT16_TYPE
8456# ifdef HAVE_INT16_T
8457#  define INT16_TYPE int16_t
8458# else
8459#  define INT16_TYPE short int
8460# endif
8461#endif
8462#ifndef UINT8_TYPE
8463# ifdef HAVE_UINT8_T
8464#  define UINT8_TYPE uint8_t
8465# else
8466#  define UINT8_TYPE unsigned char
8467# endif
8468#endif
8469#ifndef INT8_TYPE
8470# ifdef HAVE_INT8_T
8471#  define INT8_TYPE int8_t
8472# else
8473#  define INT8_TYPE signed char
8474# endif
8475#endif
8476#ifndef LONGDOUBLE_TYPE
8477# define LONGDOUBLE_TYPE long double
8478#endif
8479typedef sqlite_int64 i64;          /* 8-byte signed integer */
8480typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
8481typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
8482typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
8483typedef INT16_TYPE i16;            /* 2-byte signed integer */
8484typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
8485typedef INT8_TYPE i8;              /* 1-byte signed integer */
8486
8487/*
8488** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
8489** that can be stored in a u32 without loss of data.  The value
8490** is 0x00000000ffffffff.  But because of quirks of some compilers, we
8491** have to specify the value in the less intuitive manner shown:
8492*/
8493#define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
8494
8495/*
8496** The datatype used to store estimates of the number of rows in a
8497** table or index.  This is an unsigned integer type.  For 99.9% of
8498** the world, a 32-bit integer is sufficient.  But a 64-bit integer
8499** can be used at compile-time if desired.
8500*/
8501#ifdef SQLITE_64BIT_STATS
8502 typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */
8503#else
8504 typedef u32 tRowcnt;    /* 32-bit is the default */
8505#endif
8506
8507/*
8508** Estimated quantities used for query planning are stored as 16-bit
8509** logarithms.  For quantity X, the value stored is 10*log2(X).  This
8510** gives a possible range of values of approximately 1.0e986 to 1e-986.
8511** But the allowed values are "grainy".  Not every value is representable.
8512** For example, quantities 16 and 17 are both represented by a LogEst
8513** of 40.  However, since LogEst quantaties are suppose to be estimates,
8514** not exact values, this imprecision is not a problem.
8515**
8516** "LogEst" is short for "Logarithmic Estimate".
8517**
8518** Examples:
8519**      1 -> 0              20 -> 43          10000 -> 132
8520**      2 -> 10             25 -> 46          25000 -> 146
8521**      3 -> 16            100 -> 66        1000000 -> 199
8522**      4 -> 20           1000 -> 99        1048576 -> 200
8523**     10 -> 33           1024 -> 100    4294967296 -> 320
8524**
8525** The LogEst can be negative to indicate fractional values.
8526** Examples:
8527**
8528**    0.5 -> -10           0.1 -> -33        0.0625 -> -40
8529*/
8530typedef INT16_TYPE LogEst;
8531
8532/*
8533** Macros to determine whether the machine is big or little endian,
8534** and whether or not that determination is run-time or compile-time.
8535**
8536** For best performance, an attempt is made to guess at the byte-order
8537** using C-preprocessor macros.  If that is unsuccessful, or if
8538** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
8539** at run-time.
8540*/
8541#ifdef SQLITE_AMALGAMATION
8542SQLITE_PRIVATE const int sqlite3one = 1;
8543#else
8544SQLITE_PRIVATE const int sqlite3one;
8545#endif
8546#if (defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
8547     defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
8548     defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
8549     defined(__arm__)) && !defined(SQLITE_RUNTIME_BYTEORDER)
8550# define SQLITE_BYTEORDER    1234
8551# define SQLITE_BIGENDIAN    0
8552# define SQLITE_LITTLEENDIAN 1
8553# define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
8554#endif
8555#if (defined(sparc)    || defined(__ppc__))  \
8556    && !defined(SQLITE_RUNTIME_BYTEORDER)
8557# define SQLITE_BYTEORDER    4321
8558# define SQLITE_BIGENDIAN    1
8559# define SQLITE_LITTLEENDIAN 0
8560# define SQLITE_UTF16NATIVE  SQLITE_UTF16BE
8561#endif
8562#if !defined(SQLITE_BYTEORDER)
8563# define SQLITE_BYTEORDER    0     /* 0 means "unknown at compile-time" */
8564# define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
8565# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
8566# define SQLITE_UTF16NATIVE  (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
8567#endif
8568
8569/*
8570** Constants for the largest and smallest possible 64-bit signed integers.
8571** These macros are designed to work correctly on both 32-bit and 64-bit
8572** compilers.
8573*/
8574#define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
8575#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
8576
8577/*
8578** Round up a number to the next larger multiple of 8.  This is used
8579** to force 8-byte alignment on 64-bit architectures.
8580*/
8581#define ROUND8(x)     (((x)+7)&~7)
8582
8583/*
8584** Round down to the nearest multiple of 8
8585*/
8586#define ROUNDDOWN8(x) ((x)&~7)
8587
8588/*
8589** Assert that the pointer X is aligned to an 8-byte boundary.  This
8590** macro is used only within assert() to verify that the code gets
8591** all alignment restrictions correct.
8592**
8593** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
8594** underlying malloc() implemention might return us 4-byte aligned
8595** pointers.  In that case, only verify 4-byte alignment.
8596*/
8597#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
8598# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
8599#else
8600# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
8601#endif
8602
8603/*
8604** Disable MMAP on platforms where it is known to not work
8605*/
8606#if defined(__OpenBSD__) || defined(__QNXNTO__)
8607# undef SQLITE_MAX_MMAP_SIZE
8608# define SQLITE_MAX_MMAP_SIZE 0
8609#endif
8610
8611/*
8612** Default maximum size of memory used by memory-mapped I/O in the VFS
8613*/
8614#ifdef __APPLE__
8615# include <TargetConditionals.h>
8616# if TARGET_OS_IPHONE
8617#   undef SQLITE_MAX_MMAP_SIZE
8618#   define SQLITE_MAX_MMAP_SIZE 0
8619# endif
8620#endif
8621#ifndef SQLITE_MAX_MMAP_SIZE
8622# if defined(__linux__) \
8623  || defined(_WIN32) \
8624  || (defined(__APPLE__) && defined(__MACH__)) \
8625  || defined(__sun)
8626#   define SQLITE_MAX_MMAP_SIZE 0x7fff0000  /* 2147418112 */
8627# else
8628#   define SQLITE_MAX_MMAP_SIZE 0
8629# endif
8630# define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
8631#endif
8632
8633/*
8634** The default MMAP_SIZE is zero on all platforms.  Or, even if a larger
8635** default MMAP_SIZE is specified at compile-time, make sure that it does
8636** not exceed the maximum mmap size.
8637*/
8638#ifndef SQLITE_DEFAULT_MMAP_SIZE
8639# define SQLITE_DEFAULT_MMAP_SIZE 0
8640# define SQLITE_DEFAULT_MMAP_SIZE_xc 1  /* Exclude from ctime.c */
8641#endif
8642#if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
8643# undef SQLITE_DEFAULT_MMAP_SIZE
8644# define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
8645#endif
8646
8647/*
8648** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
8649** Priority is given to SQLITE_ENABLE_STAT4.  If either are defined, also
8650** define SQLITE_ENABLE_STAT3_OR_STAT4
8651*/
8652#ifdef SQLITE_ENABLE_STAT4
8653# undef SQLITE_ENABLE_STAT3
8654# define SQLITE_ENABLE_STAT3_OR_STAT4 1
8655#elif SQLITE_ENABLE_STAT3
8656# define SQLITE_ENABLE_STAT3_OR_STAT4 1
8657#elif SQLITE_ENABLE_STAT3_OR_STAT4
8658# undef SQLITE_ENABLE_STAT3_OR_STAT4
8659#endif
8660
8661/*
8662** An instance of the following structure is used to store the busy-handler
8663** callback for a given sqlite handle.
8664**
8665** The sqlite.busyHandler member of the sqlite struct contains the busy
8666** callback for the database handle. Each pager opened via the sqlite
8667** handle is passed a pointer to sqlite.busyHandler. The busy-handler
8668** callback is currently invoked only from within pager.c.
8669*/
8670typedef struct BusyHandler BusyHandler;
8671struct BusyHandler {
8672  int (*xFunc)(void *,int);  /* The busy callback */
8673  void *pArg;                /* First arg to busy callback */
8674  int nBusy;                 /* Incremented with each busy call */
8675};
8676
8677/*
8678** Name of the master database table.  The master database table
8679** is a special table that holds the names and attributes of all
8680** user tables and indices.
8681*/
8682#define MASTER_NAME       "sqlite_master"
8683#define TEMP_MASTER_NAME  "sqlite_temp_master"
8684
8685/*
8686** The root-page of the master database table.
8687*/
8688#define MASTER_ROOT       1
8689
8690/*
8691** The name of the schema table.
8692*/
8693#define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
8694
8695/*
8696** A convenience macro that returns the number of elements in
8697** an array.
8698*/
8699#define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
8700
8701/*
8702** Determine if the argument is a power of two
8703*/
8704#define IsPowerOfTwo(X) (((X)&((X)-1))==0)
8705
8706/*
8707** The following value as a destructor means to use sqlite3DbFree().
8708** The sqlite3DbFree() routine requires two parameters instead of the
8709** one parameter that destructors normally want.  So we have to introduce
8710** this magic value that the code knows to handle differently.  Any
8711** pointer will work here as long as it is distinct from SQLITE_STATIC
8712** and SQLITE_TRANSIENT.
8713*/
8714#define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3MallocSize)
8715
8716/*
8717** When SQLITE_OMIT_WSD is defined, it means that the target platform does
8718** not support Writable Static Data (WSD) such as global and static variables.
8719** All variables must either be on the stack or dynamically allocated from
8720** the heap.  When WSD is unsupported, the variable declarations scattered
8721** throughout the SQLite code must become constants instead.  The SQLITE_WSD
8722** macro is used for this purpose.  And instead of referencing the variable
8723** directly, we use its constant as a key to lookup the run-time allocated
8724** buffer that holds real variable.  The constant is also the initializer
8725** for the run-time allocated buffer.
8726**
8727** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
8728** macros become no-ops and have zero performance impact.
8729*/
8730#ifdef SQLITE_OMIT_WSD
8731  #define SQLITE_WSD const
8732  #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
8733  #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
8734SQLITE_API   int sqlite3_wsd_init(int N, int J);
8735SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
8736#else
8737  #define SQLITE_WSD
8738  #define GLOBAL(t,v) v
8739  #define sqlite3GlobalConfig sqlite3Config
8740#endif
8741
8742/*
8743** The following macros are used to suppress compiler warnings and to
8744** make it clear to human readers when a function parameter is deliberately
8745** left unused within the body of a function. This usually happens when
8746** a function is called via a function pointer. For example the
8747** implementation of an SQL aggregate step callback may not use the
8748** parameter indicating the number of arguments passed to the aggregate,
8749** if it knows that this is enforced elsewhere.
8750**
8751** When a function parameter is not used at all within the body of a function,
8752** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
8753** However, these macros may also be used to suppress warnings related to
8754** parameters that may or may not be used depending on compilation options.
8755** For example those parameters only used in assert() statements. In these
8756** cases the parameters are named as per the usual conventions.
8757*/
8758#define UNUSED_PARAMETER(x) (void)(x)
8759#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
8760
8761/*
8762** Forward references to structures
8763*/
8764typedef struct AggInfo AggInfo;
8765typedef struct AuthContext AuthContext;
8766typedef struct AutoincInfo AutoincInfo;
8767typedef struct Bitvec Bitvec;
8768typedef struct CollSeq CollSeq;
8769typedef struct Column Column;
8770typedef struct Db Db;
8771typedef struct Schema Schema;
8772typedef struct Expr Expr;
8773typedef struct ExprList ExprList;
8774typedef struct ExprSpan ExprSpan;
8775typedef struct FKey FKey;
8776typedef struct FuncDestructor FuncDestructor;
8777typedef struct FuncDef FuncDef;
8778typedef struct FuncDefHash FuncDefHash;
8779typedef struct IdList IdList;
8780typedef struct Index Index;
8781typedef struct IndexSample IndexSample;
8782typedef struct KeyClass KeyClass;
8783typedef struct KeyInfo KeyInfo;
8784typedef struct Lookaside Lookaside;
8785typedef struct LookasideSlot LookasideSlot;
8786typedef struct Module Module;
8787typedef struct NameContext NameContext;
8788typedef struct Parse Parse;
8789typedef struct PrintfArguments PrintfArguments;
8790typedef struct RowSet RowSet;
8791typedef struct Savepoint Savepoint;
8792typedef struct Select Select;
8793typedef struct SelectDest SelectDest;
8794typedef struct SrcList SrcList;
8795typedef struct StrAccum StrAccum;
8796typedef struct Table Table;
8797typedef struct TableLock TableLock;
8798typedef struct Token Token;
8799typedef struct Trigger Trigger;
8800typedef struct TriggerPrg TriggerPrg;
8801typedef struct TriggerStep TriggerStep;
8802typedef struct UnpackedRecord UnpackedRecord;
8803typedef struct VTable VTable;
8804typedef struct VtabCtx VtabCtx;
8805typedef struct Walker Walker;
8806typedef struct WhereInfo WhereInfo;
8807typedef struct With With;
8808
8809/*
8810** Defer sourcing vdbe.h and btree.h until after the "u8" and
8811** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
8812** pointer types (i.e. FuncDef) defined above.
8813*/
8814/************** Include btree.h in the middle of sqliteInt.h *****************/
8815/************** Begin file btree.h *******************************************/
8816/*
8817** 2001 September 15
8818**
8819** The author disclaims copyright to this source code.  In place of
8820** a legal notice, here is a blessing:
8821**
8822**    May you do good and not evil.
8823**    May you find forgiveness for yourself and forgive others.
8824**    May you share freely, never taking more than you give.
8825**
8826*************************************************************************
8827** This header file defines the interface that the sqlite B-Tree file
8828** subsystem.  See comments in the source code for a detailed description
8829** of what each interface routine does.
8830*/
8831#ifndef _BTREE_H_
8832#define _BTREE_H_
8833
8834/* TODO: This definition is just included so other modules compile. It
8835** needs to be revisited.
8836*/
8837#define SQLITE_N_BTREE_META 10
8838
8839/*
8840** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
8841** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
8842*/
8843#ifndef SQLITE_DEFAULT_AUTOVACUUM
8844  #define SQLITE_DEFAULT_AUTOVACUUM 0
8845#endif
8846
8847#define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
8848#define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
8849#define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
8850
8851/*
8852** Forward declarations of structure
8853*/
8854typedef struct Btree Btree;
8855typedef struct BtCursor BtCursor;
8856typedef struct BtShared BtShared;
8857
8858
8859SQLITE_PRIVATE int sqlite3BtreeOpen(
8860  sqlite3_vfs *pVfs,       /* VFS to use with this b-tree */
8861  const char *zFilename,   /* Name of database file to open */
8862  sqlite3 *db,             /* Associated database connection */
8863  Btree **ppBtree,         /* Return open Btree* here */
8864  int flags,               /* Flags */
8865  int vfsFlags             /* Flags passed through to VFS open */
8866);
8867
8868/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
8869** following values.
8870**
8871** NOTE:  These values must match the corresponding PAGER_ values in
8872** pager.h.
8873*/
8874#define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
8875#define BTREE_MEMORY        2  /* This is an in-memory DB */
8876#define BTREE_SINGLE        4  /* The file contains at most 1 b-tree */
8877#define BTREE_UNORDERED     8  /* Use of a hash implementation is OK */
8878
8879SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
8880SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
8881#if SQLITE_MAX_MMAP_SIZE>0
8882SQLITE_PRIVATE   int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
8883#endif
8884SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
8885SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
8886SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
8887SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
8888SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
8889SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
8890SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
8891SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
8892#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
8893SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
8894#endif
8895SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
8896SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
8897SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
8898SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
8899SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
8900SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
8901SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int);
8902SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
8903SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
8904SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
8905SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
8906SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
8907SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
8908SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
8909SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
8910SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
8911
8912SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
8913SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
8914SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
8915
8916SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
8917
8918/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
8919** of the flags shown below.
8920**
8921** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
8922** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
8923** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
8924** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
8925** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
8926** indices.)
8927*/
8928#define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
8929#define BTREE_BLOBKEY    2    /* Table has keys only - no data */
8930
8931SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
8932SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
8933SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
8934SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
8935
8936SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
8937SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
8938
8939SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
8940
8941/*
8942** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
8943** should be one of the following values. The integer values are assigned
8944** to constants so that the offset of the corresponding field in an
8945** SQLite database header may be found using the following formula:
8946**
8947**   offset = 36 + (idx * 4)
8948**
8949** For example, the free-page-count field is located at byte offset 36 of
8950** the database file header. The incr-vacuum-flag field is located at
8951** byte offset 64 (== 36+4*7).
8952*/
8953#define BTREE_FREE_PAGE_COUNT     0
8954#define BTREE_SCHEMA_VERSION      1
8955#define BTREE_FILE_FORMAT         2
8956#define BTREE_DEFAULT_CACHE_SIZE  3
8957#define BTREE_LARGEST_ROOT_PAGE   4
8958#define BTREE_TEXT_ENCODING       5
8959#define BTREE_USER_VERSION        6
8960#define BTREE_INCR_VACUUM         7
8961#define BTREE_APPLICATION_ID      8
8962
8963/*
8964** Values that may be OR'd together to form the second argument of an
8965** sqlite3BtreeCursorHints() call.
8966*/
8967#define BTREE_BULKLOAD 0x00000001
8968
8969SQLITE_PRIVATE int sqlite3BtreeCursor(
8970  Btree*,                              /* BTree containing table to open */
8971  int iTable,                          /* Index of root page */
8972  int wrFlag,                          /* 1 for writing.  0 for read-only */
8973  struct KeyInfo*,                     /* First argument to compare function */
8974  BtCursor *pCursor                    /* Space to write cursor structure */
8975);
8976SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
8977SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
8978
8979SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
8980SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
8981  BtCursor*,
8982  UnpackedRecord *pUnKey,
8983  i64 intKey,
8984  int bias,
8985  int *pRes
8986);
8987SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
8988SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
8989SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
8990                                  const void *pData, int nData,
8991                                  int nZero, int bias, int seekResult);
8992SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
8993SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
8994SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
8995SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
8996SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
8997SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
8998SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
8999SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, u32 *pAmt);
9000SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, u32 *pAmt);
9001SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
9002SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
9003
9004SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
9005SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
9006
9007SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
9008SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
9009SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
9010SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
9011SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask);
9012SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
9013
9014#ifndef NDEBUG
9015SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
9016#endif
9017
9018#ifndef SQLITE_OMIT_BTREECOUNT
9019SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
9020#endif
9021
9022#ifdef SQLITE_TEST
9023SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
9024SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
9025#endif
9026
9027#ifndef SQLITE_OMIT_WAL
9028SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
9029#endif
9030
9031/*
9032** If we are not using shared cache, then there is no need to
9033** use mutexes to access the BtShared structures.  So make the
9034** Enter and Leave procedures no-ops.
9035*/
9036#ifndef SQLITE_OMIT_SHARED_CACHE
9037SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
9038SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
9039#else
9040# define sqlite3BtreeEnter(X)
9041# define sqlite3BtreeEnterAll(X)
9042#endif
9043
9044#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
9045SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
9046SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
9047SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
9048SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
9049SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
9050#ifndef NDEBUG
9051  /* These routines are used inside assert() statements only. */
9052SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
9053SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
9054SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
9055#endif
9056#else
9057
9058# define sqlite3BtreeSharable(X) 0
9059# define sqlite3BtreeLeave(X)
9060# define sqlite3BtreeEnterCursor(X)
9061# define sqlite3BtreeLeaveCursor(X)
9062# define sqlite3BtreeLeaveAll(X)
9063
9064# define sqlite3BtreeHoldsMutex(X) 1
9065# define sqlite3BtreeHoldsAllMutexes(X) 1
9066# define sqlite3SchemaMutexHeld(X,Y,Z) 1
9067#endif
9068
9069
9070#endif /* _BTREE_H_ */
9071
9072/************** End of btree.h ***********************************************/
9073/************** Continuing where we left off in sqliteInt.h ******************/
9074/************** Include vdbe.h in the middle of sqliteInt.h ******************/
9075/************** Begin file vdbe.h ********************************************/
9076/*
9077** 2001 September 15
9078**
9079** The author disclaims copyright to this source code.  In place of
9080** a legal notice, here is a blessing:
9081**
9082**    May you do good and not evil.
9083**    May you find forgiveness for yourself and forgive others.
9084**    May you share freely, never taking more than you give.
9085**
9086*************************************************************************
9087** Header file for the Virtual DataBase Engine (VDBE)
9088**
9089** This header defines the interface to the virtual database engine
9090** or VDBE.  The VDBE implements an abstract machine that runs a
9091** simple program to access and modify the underlying database.
9092*/
9093#ifndef _SQLITE_VDBE_H_
9094#define _SQLITE_VDBE_H_
9095/* #include <stdio.h> */
9096
9097/*
9098** A single VDBE is an opaque structure named "Vdbe".  Only routines
9099** in the source file sqliteVdbe.c are allowed to see the insides
9100** of this structure.
9101*/
9102typedef struct Vdbe Vdbe;
9103
9104/*
9105** The names of the following types declared in vdbeInt.h are required
9106** for the VdbeOp definition.
9107*/
9108typedef struct Mem Mem;
9109typedef struct SubProgram SubProgram;
9110
9111/*
9112** A single instruction of the virtual machine has an opcode
9113** and as many as three operands.  The instruction is recorded
9114** as an instance of the following structure:
9115*/
9116struct VdbeOp {
9117  u8 opcode;          /* What operation to perform */
9118  signed char p4type; /* One of the P4_xxx constants for p4 */
9119  u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
9120  u8 p5;              /* Fifth parameter is an unsigned character */
9121  int p1;             /* First operand */
9122  int p2;             /* Second parameter (often the jump destination) */
9123  int p3;             /* The third parameter */
9124  union {             /* fourth parameter */
9125    int i;                 /* Integer value if p4type==P4_INT32 */
9126    void *p;               /* Generic pointer */
9127    char *z;               /* Pointer to data for string (char array) types */
9128    i64 *pI64;             /* Used when p4type is P4_INT64 */
9129    double *pReal;         /* Used when p4type is P4_REAL */
9130    FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
9131    CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
9132    Mem *pMem;             /* Used when p4type is P4_MEM */
9133    VTable *pVtab;         /* Used when p4type is P4_VTAB */
9134    KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
9135    int *ai;               /* Used when p4type is P4_INTARRAY */
9136    SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
9137    int (*xAdvance)(BtCursor *, int *);
9138  } p4;
9139#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
9140  char *zComment;          /* Comment to improve readability */
9141#endif
9142#ifdef VDBE_PROFILE
9143  u32 cnt;                 /* Number of times this instruction was executed */
9144  u64 cycles;              /* Total time spent executing this instruction */
9145#endif
9146#ifdef SQLITE_VDBE_COVERAGE
9147  int iSrcLine;            /* Source-code line that generated this opcode */
9148#endif
9149};
9150typedef struct VdbeOp VdbeOp;
9151
9152
9153/*
9154** A sub-routine used to implement a trigger program.
9155*/
9156struct SubProgram {
9157  VdbeOp *aOp;                  /* Array of opcodes for sub-program */
9158  int nOp;                      /* Elements in aOp[] */
9159  int nMem;                     /* Number of memory cells required */
9160  int nCsr;                     /* Number of cursors required */
9161  int nOnce;                    /* Number of OP_Once instructions */
9162  void *token;                  /* id that may be used to recursive triggers */
9163  SubProgram *pNext;            /* Next sub-program already visited */
9164};
9165
9166/*
9167** A smaller version of VdbeOp used for the VdbeAddOpList() function because
9168** it takes up less space.
9169*/
9170struct VdbeOpList {
9171  u8 opcode;          /* What operation to perform */
9172  signed char p1;     /* First operand */
9173  signed char p2;     /* Second parameter (often the jump destination) */
9174  signed char p3;     /* Third parameter */
9175};
9176typedef struct VdbeOpList VdbeOpList;
9177
9178/*
9179** Allowed values of VdbeOp.p4type
9180*/
9181#define P4_NOTUSED    0   /* The P4 parameter is not used */
9182#define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
9183#define P4_STATIC   (-2)  /* Pointer to a static string */
9184#define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
9185#define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
9186#define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
9187#define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
9188#define P4_TRANSIENT  0   /* P4 is a pointer to a transient string */
9189#define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
9190#define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
9191#define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
9192#define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
9193#define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
9194#define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
9195#define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
9196#define P4_ADVANCE  (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
9197
9198/* Error message codes for OP_Halt */
9199#define P5_ConstraintNotNull 1
9200#define P5_ConstraintUnique  2
9201#define P5_ConstraintCheck   3
9202#define P5_ConstraintFK      4
9203
9204/*
9205** The Vdbe.aColName array contains 5n Mem structures, where n is the
9206** number of columns of data returned by the statement.
9207*/
9208#define COLNAME_NAME     0
9209#define COLNAME_DECLTYPE 1
9210#define COLNAME_DATABASE 2
9211#define COLNAME_TABLE    3
9212#define COLNAME_COLUMN   4
9213#ifdef SQLITE_ENABLE_COLUMN_METADATA
9214# define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
9215#else
9216# ifdef SQLITE_OMIT_DECLTYPE
9217#   define COLNAME_N      1      /* Store only the name */
9218# else
9219#   define COLNAME_N      2      /* Store the name and decltype */
9220# endif
9221#endif
9222
9223/*
9224** The following macro converts a relative address in the p2 field
9225** of a VdbeOp structure into a negative number so that
9226** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
9227** the macro again restores the address.
9228*/
9229#define ADDR(X)  (-1-(X))
9230
9231/*
9232** The makefile scans the vdbe.c source file and creates the "opcodes.h"
9233** header file that defines a number for each opcode used by the VDBE.
9234*/
9235/************** Include opcodes.h in the middle of vdbe.h ********************/
9236/************** Begin file opcodes.h *****************************************/
9237/* Automatically generated.  Do not edit */
9238/* See the mkopcodeh.awk script for details */
9239#define OP_Function        1 /* synopsis: r[P3]=func(r[P2@P5])             */
9240#define OP_Savepoint       2
9241#define OP_AutoCommit      3
9242#define OP_Transaction     4
9243#define OP_SorterNext      5
9244#define OP_PrevIfOpen      6
9245#define OP_NextIfOpen      7
9246#define OP_Prev            8
9247#define OP_Next            9
9248#define OP_AggStep        10 /* synopsis: accum=r[P3] step(r[P2@P5])       */
9249#define OP_Checkpoint     11
9250#define OP_JournalMode    12
9251#define OP_Vacuum         13
9252#define OP_VFilter        14 /* synopsis: iplan=r[P3] zplan='P4'           */
9253#define OP_VUpdate        15 /* synopsis: data=r[P3@P2]                    */
9254#define OP_Goto           16
9255#define OP_Gosub          17
9256#define OP_Return         18
9257#define OP_Not            19 /* same as TK_NOT, synopsis: r[P2]= !r[P1]    */
9258#define OP_InitCoroutine  20
9259#define OP_EndCoroutine   21
9260#define OP_Yield          22
9261#define OP_HaltIfNull     23 /* synopsis: if r[P3]=null halt               */
9262#define OP_Halt           24
9263#define OP_Integer        25 /* synopsis: r[P2]=P1                         */
9264#define OP_Int64          26 /* synopsis: r[P2]=P4                         */
9265#define OP_String         27 /* synopsis: r[P2]='P4' (len=P1)              */
9266#define OP_Null           28 /* synopsis: r[P2..P3]=NULL                   */
9267#define OP_SoftNull       29 /* synopsis: r[P1]=NULL                       */
9268#define OP_Blob           30 /* synopsis: r[P2]=P4 (len=P1)                */
9269#define OP_Variable       31 /* synopsis: r[P2]=parameter(P1,P4)           */
9270#define OP_Move           32 /* synopsis: r[P2@P3]=r[P1@P3]                */
9271#define OP_Copy           33 /* synopsis: r[P2@P3+1]=r[P1@P3+1]            */
9272#define OP_SCopy          34 /* synopsis: r[P2]=r[P1]                      */
9273#define OP_ResultRow      35 /* synopsis: output=r[P1@P2]                  */
9274#define OP_CollSeq        36
9275#define OP_AddImm         37 /* synopsis: r[P1]=r[P1]+P2                   */
9276#define OP_MustBeInt      38
9277#define OP_RealAffinity   39
9278#define OP_Permutation    40
9279#define OP_Compare        41 /* synopsis: r[P1@P3] <-> r[P2@P3]            */
9280#define OP_Jump           42
9281#define OP_Once           43
9282#define OP_If             44
9283#define OP_IfNot          45
9284#define OP_Column         46 /* synopsis: r[P3]=PX                         */
9285#define OP_Affinity       47 /* synopsis: affinity(r[P1@P2])               */
9286#define OP_MakeRecord     48 /* synopsis: r[P3]=mkrec(r[P1@P2])            */
9287#define OP_Count          49 /* synopsis: r[P2]=count()                    */
9288#define OP_ReadCookie     50
9289#define OP_SetCookie      51
9290#define OP_OpenRead       52 /* synopsis: root=P2 iDb=P3                   */
9291#define OP_OpenWrite      53 /* synopsis: root=P2 iDb=P3                   */
9292#define OP_OpenAutoindex  54 /* synopsis: nColumn=P2                       */
9293#define OP_OpenEphemeral  55 /* synopsis: nColumn=P2                       */
9294#define OP_SorterOpen     56
9295#define OP_OpenPseudo     57 /* synopsis: P3 columns in r[P2]              */
9296#define OP_Close          58
9297#define OP_SeekLT         59
9298#define OP_SeekLE         60
9299#define OP_SeekGE         61
9300#define OP_SeekGT         62
9301#define OP_Seek           63 /* synopsis: intkey=r[P2]                     */
9302#define OP_NoConflict     64 /* synopsis: key=r[P3@P4]                     */
9303#define OP_NotFound       65 /* synopsis: key=r[P3@P4]                     */
9304#define OP_Found          66 /* synopsis: key=r[P3@P4]                     */
9305#define OP_NotExists      67 /* synopsis: intkey=r[P3]                     */
9306#define OP_Sequence       68 /* synopsis: r[P2]=cursor[P1].ctr++           */
9307#define OP_NewRowid       69 /* synopsis: r[P2]=rowid                      */
9308#define OP_Insert         70 /* synopsis: intkey=r[P3] data=r[P2]          */
9309#define OP_Or             71 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
9310#define OP_And            72 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
9311#define OP_InsertInt      73 /* synopsis: intkey=P3 data=r[P2]             */
9312#define OP_Delete         74
9313#define OP_ResetCount     75
9314#define OP_IsNull         76 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
9315#define OP_NotNull        77 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
9316#define OP_Ne             78 /* same as TK_NE, synopsis: if r[P1]!=r[P3] goto P2 */
9317#define OP_Eq             79 /* same as TK_EQ, synopsis: if r[P1]==r[P3] goto P2 */
9318#define OP_Gt             80 /* same as TK_GT, synopsis: if r[P1]>r[P3] goto P2 */
9319#define OP_Le             81 /* same as TK_LE, synopsis: if r[P1]<=r[P3] goto P2 */
9320#define OP_Lt             82 /* same as TK_LT, synopsis: if r[P1]<r[P3] goto P2 */
9321#define OP_Ge             83 /* same as TK_GE, synopsis: if r[P1]>=r[P3] goto P2 */
9322#define OP_SorterCompare  84 /* synopsis: if key(P1)!=rtrim(r[P3],P4) goto P2 */
9323#define OP_BitAnd         85 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
9324#define OP_BitOr          86 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
9325#define OP_ShiftLeft      87 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
9326#define OP_ShiftRight     88 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
9327#define OP_Add            89 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
9328#define OP_Subtract       90 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
9329#define OP_Multiply       91 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
9330#define OP_Divide         92 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
9331#define OP_Remainder      93 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
9332#define OP_Concat         94 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
9333#define OP_SorterData     95 /* synopsis: r[P2]=data                       */
9334#define OP_BitNot         96 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
9335#define OP_String8        97 /* same as TK_STRING, synopsis: r[P2]='P4'    */
9336#define OP_RowKey         98 /* synopsis: r[P2]=key                        */
9337#define OP_RowData        99 /* synopsis: r[P2]=data                       */
9338#define OP_Rowid         100 /* synopsis: r[P2]=rowid                      */
9339#define OP_NullRow       101
9340#define OP_Last          102
9341#define OP_SorterSort    103
9342#define OP_Sort          104
9343#define OP_Rewind        105
9344#define OP_SorterInsert  106
9345#define OP_IdxInsert     107 /* synopsis: key=r[P2]                        */
9346#define OP_IdxDelete     108 /* synopsis: key=r[P2@P3]                     */
9347#define OP_IdxRowid      109 /* synopsis: r[P2]=rowid                      */
9348#define OP_IdxLE         110 /* synopsis: key=r[P3@P4]                     */
9349#define OP_IdxGT         111 /* synopsis: key=r[P3@P4]                     */
9350#define OP_IdxLT         112 /* synopsis: key=r[P3@P4]                     */
9351#define OP_IdxGE         113 /* synopsis: key=r[P3@P4]                     */
9352#define OP_Destroy       114
9353#define OP_Clear         115
9354#define OP_ResetSorter   116
9355#define OP_CreateIndex   117 /* synopsis: r[P2]=root iDb=P1                */
9356#define OP_CreateTable   118 /* synopsis: r[P2]=root iDb=P1                */
9357#define OP_ParseSchema   119
9358#define OP_LoadAnalysis  120
9359#define OP_DropTable     121
9360#define OP_DropIndex     122
9361#define OP_DropTrigger   123
9362#define OP_IntegrityCk   124
9363#define OP_RowSetAdd     125 /* synopsis: rowset(P1)=r[P2]                 */
9364#define OP_RowSetRead    126 /* synopsis: r[P3]=rowset(P1)                 */
9365#define OP_RowSetTest    127 /* synopsis: if r[P3] in rowset(P1) goto P2   */
9366#define OP_Program       128
9367#define OP_Param         129
9368#define OP_FkCounter     130 /* synopsis: fkctr[P1]+=P2                    */
9369#define OP_FkIfZero      131 /* synopsis: if fkctr[P1]==0 goto P2          */
9370#define OP_MemMax        132 /* synopsis: r[P1]=max(r[P1],r[P2])           */
9371#define OP_Real          133 /* same as TK_FLOAT, synopsis: r[P2]=P4       */
9372#define OP_IfPos         134 /* synopsis: if r[P1]>0 goto P2               */
9373#define OP_IfNeg         135 /* synopsis: if r[P1]<0 goto P2               */
9374#define OP_IfZero        136 /* synopsis: r[P1]+=P3, if r[P1]==0 goto P2   */
9375#define OP_AggFinal      137 /* synopsis: accum=r[P1] N=P2                 */
9376#define OP_IncrVacuum    138
9377#define OP_Expire        139
9378#define OP_TableLock     140 /* synopsis: iDb=P1 root=P2 write=P3          */
9379#define OP_VBegin        141
9380#define OP_VCreate       142
9381#define OP_ToText        143 /* same as TK_TO_TEXT                         */
9382#define OP_ToBlob        144 /* same as TK_TO_BLOB                         */
9383#define OP_ToNumeric     145 /* same as TK_TO_NUMERIC                      */
9384#define OP_ToInt         146 /* same as TK_TO_INT                          */
9385#define OP_ToReal        147 /* same as TK_TO_REAL                         */
9386#define OP_VDestroy      148
9387#define OP_VOpen         149
9388#define OP_VColumn       150 /* synopsis: r[P3]=vcolumn(P2)                */
9389#define OP_VNext         151
9390#define OP_VRename       152
9391#define OP_Pagecount     153
9392#define OP_MaxPgcnt      154
9393#define OP_Init          155 /* synopsis: Start at P2                      */
9394#define OP_Noop          156
9395#define OP_Explain       157
9396
9397
9398/* Properties such as "out2" or "jump" that are specified in
9399** comments following the "case" for each opcode in the vdbe.c
9400** are encoded into bitvectors as follows:
9401*/
9402#define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
9403#define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
9404#define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
9405#define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
9406#define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
9407#define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
9408#define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
9409#define OPFLG_INITIALIZER {\
9410/*   0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01,\
9411/*   8 */ 0x01, 0x01, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00,\
9412/*  16 */ 0x01, 0x01, 0x04, 0x24, 0x01, 0x04, 0x05, 0x10,\
9413/*  24 */ 0x00, 0x02, 0x02, 0x02, 0x02, 0x00, 0x02, 0x02,\
9414/*  32 */ 0x00, 0x00, 0x20, 0x00, 0x00, 0x04, 0x05, 0x04,\
9415/*  40 */ 0x00, 0x00, 0x01, 0x01, 0x05, 0x05, 0x00, 0x00,\
9416/*  48 */ 0x00, 0x02, 0x02, 0x10, 0x00, 0x00, 0x00, 0x00,\
9417/*  56 */ 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11, 0x08,\
9418/*  64 */ 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00, 0x4c,\
9419/*  72 */ 0x4c, 0x00, 0x00, 0x00, 0x05, 0x05, 0x15, 0x15,\
9420/*  80 */ 0x15, 0x15, 0x15, 0x15, 0x00, 0x4c, 0x4c, 0x4c,\
9421/*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x00,\
9422/*  96 */ 0x24, 0x02, 0x00, 0x00, 0x02, 0x00, 0x01, 0x01,\
9423/* 104 */ 0x01, 0x01, 0x08, 0x08, 0x00, 0x02, 0x01, 0x01,\
9424/* 112 */ 0x01, 0x01, 0x02, 0x00, 0x00, 0x02, 0x02, 0x00,\
9425/* 120 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x45, 0x15,\
9426/* 128 */ 0x01, 0x02, 0x00, 0x01, 0x08, 0x02, 0x05, 0x05,\
9427/* 136 */ 0x05, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x04,\
9428/* 144 */ 0x04, 0x04, 0x04, 0x04, 0x00, 0x00, 0x00, 0x01,\
9429/* 152 */ 0x00, 0x02, 0x02, 0x01, 0x00, 0x00,}
9430
9431/************** End of opcodes.h *********************************************/
9432/************** Continuing where we left off in vdbe.h ***********************/
9433
9434/*
9435** Prototypes for the VDBE interface.  See comments on the implementation
9436** for a description of what each of these routines does.
9437*/
9438SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
9439SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
9440SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
9441SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
9442SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
9443SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
9444SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
9445SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
9446SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
9447SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
9448SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
9449SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
9450SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
9451SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
9452SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
9453SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
9454SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
9455SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
9456SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
9457SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
9458SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
9459SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
9460SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
9461SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
9462SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
9463SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
9464SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
9465SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
9466#ifdef SQLITE_DEBUG
9467SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
9468#endif
9469SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
9470SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
9471SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
9472SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
9473SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
9474SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
9475SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
9476SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
9477SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
9478SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
9479SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
9480SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
9481#ifndef SQLITE_OMIT_TRACE
9482SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
9483#endif
9484
9485SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
9486SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*,int);
9487SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
9488
9489typedef int (*RecordCompare)(int,const void*,UnpackedRecord*,int);
9490SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
9491
9492#ifndef SQLITE_OMIT_TRIGGER
9493SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
9494#endif
9495
9496/* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
9497** each VDBE opcode.
9498**
9499** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
9500** comments in VDBE programs that show key decision points in the code
9501** generator.
9502*/
9503#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
9504SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
9505# define VdbeComment(X)  sqlite3VdbeComment X
9506SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
9507# define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
9508# ifdef SQLITE_ENABLE_MODULE_COMMENTS
9509#   define VdbeModuleComment(X)  sqlite3VdbeNoopComment X
9510# else
9511#   define VdbeModuleComment(X)
9512# endif
9513#else
9514# define VdbeComment(X)
9515# define VdbeNoopComment(X)
9516# define VdbeModuleComment(X)
9517#endif
9518
9519/*
9520** The VdbeCoverage macros are used to set a coverage testing point
9521** for VDBE branch instructions.  The coverage testing points are line
9522** numbers in the sqlite3.c source file.  VDBE branch coverage testing
9523** only works with an amalagmation build.  That's ok since a VDBE branch
9524** coverage build designed for testing the test suite only.  No application
9525** should ever ship with VDBE branch coverage measuring turned on.
9526**
9527**    VdbeCoverage(v)                  // Mark the previously coded instruction
9528**                                     // as a branch
9529**
9530**    VdbeCoverageIf(v, conditional)   // Mark previous if conditional true
9531**
9532**    VdbeCoverageAlwaysTaken(v)       // Previous branch is always taken
9533**
9534**    VdbeCoverageNeverTaken(v)        // Previous branch is never taken
9535**
9536** Every VDBE branch operation must be tagged with one of the macros above.
9537** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
9538** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
9539** routine in vdbe.c, alerting the developer to the missed tag.
9540*/
9541#ifdef SQLITE_VDBE_COVERAGE
9542SQLITE_PRIVATE   void sqlite3VdbeSetLineNumber(Vdbe*,int);
9543# define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
9544# define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
9545# define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
9546# define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
9547# define VDBE_OFFSET_LINENO(x) (__LINE__+x)
9548#else
9549# define VdbeCoverage(v)
9550# define VdbeCoverageIf(v,x)
9551# define VdbeCoverageAlwaysTaken(v)
9552# define VdbeCoverageNeverTaken(v)
9553# define VDBE_OFFSET_LINENO(x) 0
9554#endif
9555
9556#endif
9557
9558/************** End of vdbe.h ************************************************/
9559/************** Continuing where we left off in sqliteInt.h ******************/
9560/************** Include pager.h in the middle of sqliteInt.h *****************/
9561/************** Begin file pager.h *******************************************/
9562/*
9563** 2001 September 15
9564**
9565** The author disclaims copyright to this source code.  In place of
9566** a legal notice, here is a blessing:
9567**
9568**    May you do good and not evil.
9569**    May you find forgiveness for yourself and forgive others.
9570**    May you share freely, never taking more than you give.
9571**
9572*************************************************************************
9573** This header file defines the interface that the sqlite page cache
9574** subsystem.  The page cache subsystem reads and writes a file a page
9575** at a time and provides a journal for rollback.
9576*/
9577
9578#ifndef _PAGER_H_
9579#define _PAGER_H_
9580
9581/*
9582** Default maximum size for persistent journal files. A negative
9583** value means no limit. This value may be overridden using the
9584** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
9585*/
9586#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
9587  #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
9588#endif
9589
9590/*
9591** The type used to represent a page number.  The first page in a file
9592** is called page 1.  0 is used to represent "not a page".
9593*/
9594typedef u32 Pgno;
9595
9596/*
9597** Each open file is managed by a separate instance of the "Pager" structure.
9598*/
9599typedef struct Pager Pager;
9600
9601/*
9602** Handle type for pages.
9603*/
9604typedef struct PgHdr DbPage;
9605
9606/*
9607** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
9608** reserved for working around a windows/posix incompatibility). It is
9609** used in the journal to signify that the remainder of the journal file
9610** is devoted to storing a master journal name - there are no more pages to
9611** roll back. See comments for function writeMasterJournal() in pager.c
9612** for details.
9613*/
9614#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
9615
9616/*
9617** Allowed values for the flags parameter to sqlite3PagerOpen().
9618**
9619** NOTE: These values must match the corresponding BTREE_ values in btree.h.
9620*/
9621#define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
9622#define PAGER_MEMORY        0x0002    /* In-memory database */
9623
9624/*
9625** Valid values for the second argument to sqlite3PagerLockingMode().
9626*/
9627#define PAGER_LOCKINGMODE_QUERY      -1
9628#define PAGER_LOCKINGMODE_NORMAL      0
9629#define PAGER_LOCKINGMODE_EXCLUSIVE   1
9630
9631/*
9632** Numeric constants that encode the journalmode.
9633*/
9634#define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
9635#define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
9636#define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
9637#define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
9638#define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
9639#define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
9640#define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
9641
9642/*
9643** Flags that make up the mask passed to sqlite3PagerAcquire().
9644*/
9645#define PAGER_GET_NOCONTENT     0x01  /* Do not load data from disk */
9646#define PAGER_GET_READONLY      0x02  /* Read-only page is acceptable */
9647
9648/*
9649** Flags for sqlite3PagerSetFlags()
9650*/
9651#define PAGER_SYNCHRONOUS_OFF       0x01  /* PRAGMA synchronous=OFF */
9652#define PAGER_SYNCHRONOUS_NORMAL    0x02  /* PRAGMA synchronous=NORMAL */
9653#define PAGER_SYNCHRONOUS_FULL      0x03  /* PRAGMA synchronous=FULL */
9654#define PAGER_SYNCHRONOUS_MASK      0x03  /* Mask for three values above */
9655#define PAGER_FULLFSYNC             0x04  /* PRAGMA fullfsync=ON */
9656#define PAGER_CKPT_FULLFSYNC        0x08  /* PRAGMA checkpoint_fullfsync=ON */
9657#define PAGER_CACHESPILL            0x10  /* PRAGMA cache_spill=ON */
9658#define PAGER_FLAGS_MASK            0x1c  /* All above except SYNCHRONOUS */
9659
9660/*
9661** The remainder of this file contains the declarations of the functions
9662** that make up the Pager sub-system API. See source code comments for
9663** a detailed description of each routine.
9664*/
9665
9666/* Open and close a Pager connection. */
9667SQLITE_PRIVATE int sqlite3PagerOpen(
9668  sqlite3_vfs*,
9669  Pager **ppPager,
9670  const char*,
9671  int,
9672  int,
9673  int,
9674  void(*)(DbPage*)
9675);
9676SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
9677SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
9678
9679/* Functions used to configure a Pager object. */
9680SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
9681SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
9682SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
9683SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
9684SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
9685SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
9686SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
9687SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
9688SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
9689SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
9690SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
9691SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
9692SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
9693
9694/* Functions used to obtain and release page references. */
9695SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
9696#define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
9697SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
9698SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
9699SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
9700SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
9701
9702/* Operations on page references. */
9703SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
9704SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
9705SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
9706SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
9707SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
9708SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
9709
9710/* Functions used to manage pager transactions and savepoints. */
9711SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
9712SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
9713SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
9714SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
9715SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
9716SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
9717SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
9718SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
9719SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
9720SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
9721
9722#ifndef SQLITE_OMIT_WAL
9723SQLITE_PRIVATE   int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
9724SQLITE_PRIVATE   int sqlite3PagerWalSupported(Pager *pPager);
9725SQLITE_PRIVATE   int sqlite3PagerWalCallback(Pager *pPager);
9726SQLITE_PRIVATE   int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
9727SQLITE_PRIVATE   int sqlite3PagerCloseWal(Pager *pPager);
9728#endif
9729
9730#ifdef SQLITE_ENABLE_ZIPVFS
9731SQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);
9732#endif
9733
9734/* Functions used to query pager state and configuration. */
9735SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
9736SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
9737SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
9738SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
9739SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
9740SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
9741SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
9742SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
9743SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
9744SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
9745SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
9746SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
9747SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
9748
9749/* Functions used to truncate the database file. */
9750SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
9751
9752#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
9753SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
9754#endif
9755
9756/* Functions to support testing and debugging. */
9757#if !defined(NDEBUG) || defined(SQLITE_TEST)
9758SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
9759SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
9760#endif
9761#ifdef SQLITE_TEST
9762SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
9763SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
9764  void disable_simulated_io_errors(void);
9765  void enable_simulated_io_errors(void);
9766#else
9767# define disable_simulated_io_errors()
9768# define enable_simulated_io_errors()
9769#endif
9770
9771#endif /* _PAGER_H_ */
9772
9773/************** End of pager.h ***********************************************/
9774/************** Continuing where we left off in sqliteInt.h ******************/
9775/************** Include pcache.h in the middle of sqliteInt.h ****************/
9776/************** Begin file pcache.h ******************************************/
9777/*
9778** 2008 August 05
9779**
9780** The author disclaims copyright to this source code.  In place of
9781** a legal notice, here is a blessing:
9782**
9783**    May you do good and not evil.
9784**    May you find forgiveness for yourself and forgive others.
9785**    May you share freely, never taking more than you give.
9786**
9787*************************************************************************
9788** This header file defines the interface that the sqlite page cache
9789** subsystem.
9790*/
9791
9792#ifndef _PCACHE_H_
9793
9794typedef struct PgHdr PgHdr;
9795typedef struct PCache PCache;
9796
9797/*
9798** Every page in the cache is controlled by an instance of the following
9799** structure.
9800*/
9801struct PgHdr {
9802  sqlite3_pcache_page *pPage;    /* Pcache object page handle */
9803  void *pData;                   /* Page data */
9804  void *pExtra;                  /* Extra content */
9805  PgHdr *pDirty;                 /* Transient list of dirty pages */
9806  Pager *pPager;                 /* The pager this page is part of */
9807  Pgno pgno;                     /* Page number for this page */
9808#ifdef SQLITE_CHECK_PAGES
9809  u32 pageHash;                  /* Hash of page content */
9810#endif
9811  u16 flags;                     /* PGHDR flags defined below */
9812
9813  /**********************************************************************
9814  ** Elements above are public.  All that follows is private to pcache.c
9815  ** and should not be accessed by other modules.
9816  */
9817  i16 nRef;                      /* Number of users of this page */
9818  PCache *pCache;                /* Cache that owns this page */
9819
9820  PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
9821  PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
9822};
9823
9824/* Bit values for PgHdr.flags */
9825#define PGHDR_DIRTY             0x002  /* Page has changed */
9826#define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
9827                                       ** writing this page to the database */
9828#define PGHDR_NEED_READ         0x008  /* Content is unread */
9829#define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
9830#define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
9831
9832#define PGHDR_MMAP              0x040  /* This is an mmap page object */
9833
9834/* Initialize and shutdown the page cache subsystem */
9835SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
9836SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
9837
9838/* Page cache buffer management:
9839** These routines implement SQLITE_CONFIG_PAGECACHE.
9840*/
9841SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
9842
9843/* Create a new pager cache.
9844** Under memory stress, invoke xStress to try to make pages clean.
9845** Only clean and unpinned pages can be reclaimed.
9846*/
9847SQLITE_PRIVATE void sqlite3PcacheOpen(
9848  int szPage,                    /* Size of every page */
9849  int szExtra,                   /* Extra space associated with each page */
9850  int bPurgeable,                /* True if pages are on backing store */
9851  int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
9852  void *pStress,                 /* Argument to xStress */
9853  PCache *pToInit                /* Preallocated space for the PCache */
9854);
9855
9856/* Modify the page-size after the cache has been created. */
9857SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
9858
9859/* Return the size in bytes of a PCache object.  Used to preallocate
9860** storage space.
9861*/
9862SQLITE_PRIVATE int sqlite3PcacheSize(void);
9863
9864/* One release per successful fetch.  Page is pinned until released.
9865** Reference counted.
9866*/
9867SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
9868SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
9869
9870SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
9871SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
9872SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
9873SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
9874
9875/* Change a page number.  Used by incr-vacuum. */
9876SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
9877
9878/* Remove all pages with pgno>x.  Reset the cache if x==0 */
9879SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
9880
9881/* Get a list of all dirty pages in the cache, sorted by page number */
9882SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
9883
9884/* Reset and close the cache object */
9885SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
9886
9887/* Clear flags from pages of the page cache */
9888SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
9889
9890/* Discard the contents of the cache */
9891SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
9892
9893/* Return the total number of outstanding page references */
9894SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
9895
9896/* Increment the reference count of an existing page */
9897SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
9898
9899SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
9900
9901/* Return the total number of pages stored in the cache */
9902SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
9903
9904#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
9905/* Iterate through all dirty pages currently stored in the cache. This
9906** interface is only available if SQLITE_CHECK_PAGES is defined when the
9907** library is built.
9908*/
9909SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
9910#endif
9911
9912/* Set and get the suggested cache-size for the specified pager-cache.
9913**
9914** If no global maximum is configured, then the system attempts to limit
9915** the total number of pages cached by purgeable pager-caches to the sum
9916** of the suggested cache-sizes.
9917*/
9918SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
9919#ifdef SQLITE_TEST
9920SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
9921#endif
9922
9923/* Free up as much memory as possible from the page cache */
9924SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
9925
9926#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
9927/* Try to return memory used by the pcache module to the main memory heap */
9928SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
9929#endif
9930
9931#ifdef SQLITE_TEST
9932SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
9933#endif
9934
9935SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
9936
9937#endif /* _PCACHE_H_ */
9938
9939/************** End of pcache.h **********************************************/
9940/************** Continuing where we left off in sqliteInt.h ******************/
9941
9942/************** Include os.h in the middle of sqliteInt.h ********************/
9943/************** Begin file os.h **********************************************/
9944/*
9945** 2001 September 16
9946**
9947** The author disclaims copyright to this source code.  In place of
9948** a legal notice, here is a blessing:
9949**
9950**    May you do good and not evil.
9951**    May you find forgiveness for yourself and forgive others.
9952**    May you share freely, never taking more than you give.
9953**
9954******************************************************************************
9955**
9956** This header file (together with is companion C source-code file
9957** "os.c") attempt to abstract the underlying operating system so that
9958** the SQLite library will work on both POSIX and windows systems.
9959**
9960** This header file is #include-ed by sqliteInt.h and thus ends up
9961** being included by every source file.
9962*/
9963#ifndef _SQLITE_OS_H_
9964#define _SQLITE_OS_H_
9965
9966/*
9967** Attempt to automatically detect the operating system and setup the
9968** necessary pre-processor macros for it.
9969*/
9970/************** Include os_setup.h in the middle of os.h *********************/
9971/************** Begin file os_setup.h ****************************************/
9972/*
9973** 2013 November 25
9974**
9975** The author disclaims copyright to this source code.  In place of
9976** a legal notice, here is a blessing:
9977**
9978**    May you do good and not evil.
9979**    May you find forgiveness for yourself and forgive others.
9980**    May you share freely, never taking more than you give.
9981**
9982******************************************************************************
9983**
9984** This file contains pre-processor directives related to operating system
9985** detection and/or setup.
9986*/
9987#ifndef _OS_SETUP_H_
9988#define _OS_SETUP_H_
9989
9990/*
9991** Figure out if we are dealing with Unix, Windows, or some other operating
9992** system.
9993**
9994** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
9995** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0.  One of
9996** the three will be 1.  The other two will be 0.
9997*/
9998#if defined(SQLITE_OS_OTHER)
9999#  if SQLITE_OS_OTHER==1
10000#    undef SQLITE_OS_UNIX
10001#    define SQLITE_OS_UNIX 0
10002#    undef SQLITE_OS_WIN
10003#    define SQLITE_OS_WIN 0
10004#  else
10005#    undef SQLITE_OS_OTHER
10006#  endif
10007#endif
10008#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
10009#  define SQLITE_OS_OTHER 0
10010#  ifndef SQLITE_OS_WIN
10011#    if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
10012        defined(__MINGW32__) || defined(__BORLANDC__)
10013#      define SQLITE_OS_WIN 1
10014#      define SQLITE_OS_UNIX 0
10015#    else
10016#      define SQLITE_OS_WIN 0
10017#      define SQLITE_OS_UNIX 1
10018#    endif
10019#  else
10020#    define SQLITE_OS_UNIX 0
10021#  endif
10022#else
10023#  ifndef SQLITE_OS_WIN
10024#    define SQLITE_OS_WIN 0
10025#  endif
10026#endif
10027
10028#endif /* _OS_SETUP_H_ */
10029
10030/************** End of os_setup.h ********************************************/
10031/************** Continuing where we left off in os.h *************************/
10032
10033/* If the SET_FULLSYNC macro is not defined above, then make it
10034** a no-op
10035*/
10036#ifndef SET_FULLSYNC
10037# define SET_FULLSYNC(x,y)
10038#endif
10039
10040/*
10041** The default size of a disk sector
10042*/
10043#ifndef SQLITE_DEFAULT_SECTOR_SIZE
10044# define SQLITE_DEFAULT_SECTOR_SIZE 4096
10045#endif
10046
10047/*
10048** Temporary files are named starting with this prefix followed by 16 random
10049** alphanumeric characters, and no file extension. They are stored in the
10050** OS's standard temporary file directory, and are deleted prior to exit.
10051** If sqlite is being embedded in another program, you may wish to change the
10052** prefix to reflect your program's name, so that if your program exits
10053** prematurely, old temporary files can be easily identified. This can be done
10054** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
10055**
10056** 2006-10-31:  The default prefix used to be "sqlite_".  But then
10057** Mcafee started using SQLite in their anti-virus product and it
10058** started putting files with the "sqlite" name in the c:/temp folder.
10059** This annoyed many windows users.  Those users would then do a
10060** Google search for "sqlite", find the telephone numbers of the
10061** developers and call to wake them up at night and complain.
10062** For this reason, the default name prefix is changed to be "sqlite"
10063** spelled backwards.  So the temp files are still identified, but
10064** anybody smart enough to figure out the code is also likely smart
10065** enough to know that calling the developer will not help get rid
10066** of the file.
10067*/
10068#ifndef SQLITE_TEMP_FILE_PREFIX
10069# define SQLITE_TEMP_FILE_PREFIX "etilqs_"
10070#endif
10071
10072/*
10073** The following values may be passed as the second argument to
10074** sqlite3OsLock(). The various locks exhibit the following semantics:
10075**
10076** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
10077** RESERVED:  A single process may hold a RESERVED lock on a file at
10078**            any time. Other processes may hold and obtain new SHARED locks.
10079** PENDING:   A single process may hold a PENDING lock on a file at
10080**            any one time. Existing SHARED locks may persist, but no new
10081**            SHARED locks may be obtained by other processes.
10082** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
10083**
10084** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
10085** process that requests an EXCLUSIVE lock may actually obtain a PENDING
10086** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
10087** sqlite3OsLock().
10088*/
10089#define NO_LOCK         0
10090#define SHARED_LOCK     1
10091#define RESERVED_LOCK   2
10092#define PENDING_LOCK    3
10093#define EXCLUSIVE_LOCK  4
10094
10095/*
10096** File Locking Notes:  (Mostly about windows but also some info for Unix)
10097**
10098** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
10099** those functions are not available.  So we use only LockFile() and
10100** UnlockFile().
10101**
10102** LockFile() prevents not just writing but also reading by other processes.
10103** A SHARED_LOCK is obtained by locking a single randomly-chosen
10104** byte out of a specific range of bytes. The lock byte is obtained at
10105** random so two separate readers can probably access the file at the
10106** same time, unless they are unlucky and choose the same lock byte.
10107** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
10108** There can only be one writer.  A RESERVED_LOCK is obtained by locking
10109** a single byte of the file that is designated as the reserved lock byte.
10110** A PENDING_LOCK is obtained by locking a designated byte different from
10111** the RESERVED_LOCK byte.
10112**
10113** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
10114** which means we can use reader/writer locks.  When reader/writer locks
10115** are used, the lock is placed on the same range of bytes that is used
10116** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
10117** will support two or more Win95 readers or two or more WinNT readers.
10118** But a single Win95 reader will lock out all WinNT readers and a single
10119** WinNT reader will lock out all other Win95 readers.
10120**
10121** The following #defines specify the range of bytes used for locking.
10122** SHARED_SIZE is the number of bytes available in the pool from which
10123** a random byte is selected for a shared lock.  The pool of bytes for
10124** shared locks begins at SHARED_FIRST.
10125**
10126** The same locking strategy and
10127** byte ranges are used for Unix.  This leaves open the possiblity of having
10128** clients on win95, winNT, and unix all talking to the same shared file
10129** and all locking correctly.  To do so would require that samba (or whatever
10130** tool is being used for file sharing) implements locks correctly between
10131** windows and unix.  I'm guessing that isn't likely to happen, but by
10132** using the same locking range we are at least open to the possibility.
10133**
10134** Locking in windows is manditory.  For this reason, we cannot store
10135** actual data in the bytes used for locking.  The pager never allocates
10136** the pages involved in locking therefore.  SHARED_SIZE is selected so
10137** that all locks will fit on a single page even at the minimum page size.
10138** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
10139** is set high so that we don't have to allocate an unused page except
10140** for very large databases.  But one should test the page skipping logic
10141** by setting PENDING_BYTE low and running the entire regression suite.
10142**
10143** Changing the value of PENDING_BYTE results in a subtly incompatible
10144** file format.  Depending on how it is changed, you might not notice
10145** the incompatibility right away, even running a full regression test.
10146** The default location of PENDING_BYTE is the first byte past the
10147** 1GB boundary.
10148**
10149*/
10150#ifdef SQLITE_OMIT_WSD
10151# define PENDING_BYTE     (0x40000000)
10152#else
10153# define PENDING_BYTE      sqlite3PendingByte
10154#endif
10155#define RESERVED_BYTE     (PENDING_BYTE+1)
10156#define SHARED_FIRST      (PENDING_BYTE+2)
10157#define SHARED_SIZE       510
10158
10159/*
10160** Wrapper around OS specific sqlite3_os_init() function.
10161*/
10162SQLITE_PRIVATE int sqlite3OsInit(void);
10163
10164/*
10165** Functions for accessing sqlite3_file methods
10166*/
10167SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
10168SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
10169SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
10170SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
10171SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
10172SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
10173SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
10174SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
10175SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
10176SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
10177SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
10178#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
10179SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
10180SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
10181SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
10182SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
10183SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
10184SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
10185SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
10186SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
10187
10188
10189/*
10190** Functions for accessing sqlite3_vfs methods
10191*/
10192SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
10193SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
10194SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
10195SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
10196#ifndef SQLITE_OMIT_LOAD_EXTENSION
10197SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
10198SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
10199SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
10200SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
10201#endif /* SQLITE_OMIT_LOAD_EXTENSION */
10202SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
10203SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
10204SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
10205
10206/*
10207** Convenience functions for opening and closing files using
10208** sqlite3_malloc() to obtain space for the file-handle structure.
10209*/
10210SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
10211SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
10212
10213#endif /* _SQLITE_OS_H_ */
10214
10215/************** End of os.h **************************************************/
10216/************** Continuing where we left off in sqliteInt.h ******************/
10217/************** Include mutex.h in the middle of sqliteInt.h *****************/
10218/************** Begin file mutex.h *******************************************/
10219/*
10220** 2007 August 28
10221**
10222** The author disclaims copyright to this source code.  In place of
10223** a legal notice, here is a blessing:
10224**
10225**    May you do good and not evil.
10226**    May you find forgiveness for yourself and forgive others.
10227**    May you share freely, never taking more than you give.
10228**
10229*************************************************************************
10230**
10231** This file contains the common header for all mutex implementations.
10232** The sqliteInt.h header #includes this file so that it is available
10233** to all source files.  We break it out in an effort to keep the code
10234** better organized.
10235**
10236** NOTE:  source files should *not* #include this header file directly.
10237** Source files should #include the sqliteInt.h file and let that file
10238** include this one indirectly.
10239*/
10240
10241
10242/*
10243** Figure out what version of the code to use.  The choices are
10244**
10245**   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
10246**                             mutexes implemention cannot be overridden
10247**                             at start-time.
10248**
10249**   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
10250**                             mutual exclusion is provided.  But this
10251**                             implementation can be overridden at
10252**                             start-time.
10253**
10254**   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
10255**
10256**   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
10257*/
10258#if !SQLITE_THREADSAFE
10259# define SQLITE_MUTEX_OMIT
10260#endif
10261#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
10262#  if SQLITE_OS_UNIX
10263#    define SQLITE_MUTEX_PTHREADS
10264#  elif SQLITE_OS_WIN
10265#    define SQLITE_MUTEX_W32
10266#  else
10267#    define SQLITE_MUTEX_NOOP
10268#  endif
10269#endif
10270
10271#ifdef SQLITE_MUTEX_OMIT
10272/*
10273** If this is a no-op implementation, implement everything as macros.
10274*/
10275#define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
10276#define sqlite3_mutex_free(X)
10277#define sqlite3_mutex_enter(X)
10278#define sqlite3_mutex_try(X)      SQLITE_OK
10279#define sqlite3_mutex_leave(X)
10280#define sqlite3_mutex_held(X)     ((void)(X),1)
10281#define sqlite3_mutex_notheld(X)  ((void)(X),1)
10282#define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
10283#define sqlite3MutexInit()        SQLITE_OK
10284#define sqlite3MutexEnd()
10285#define MUTEX_LOGIC(X)
10286#else
10287#define MUTEX_LOGIC(X)            X
10288#endif /* defined(SQLITE_MUTEX_OMIT) */
10289
10290/************** End of mutex.h ***********************************************/
10291/************** Continuing where we left off in sqliteInt.h ******************/
10292
10293
10294/*
10295** Each database file to be accessed by the system is an instance
10296** of the following structure.  There are normally two of these structures
10297** in the sqlite.aDb[] array.  aDb[0] is the main database file and
10298** aDb[1] is the database file used to hold temporary tables.  Additional
10299** databases may be attached.
10300*/
10301struct Db {
10302  char *zName;         /* Name of this database */
10303  Btree *pBt;          /* The B*Tree structure for this database file */
10304  u8 safety_level;     /* How aggressive at syncing data to disk */
10305  Schema *pSchema;     /* Pointer to database schema (possibly shared) */
10306};
10307
10308/*
10309** An instance of the following structure stores a database schema.
10310**
10311** Most Schema objects are associated with a Btree.  The exception is
10312** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
10313** In shared cache mode, a single Schema object can be shared by multiple
10314** Btrees that refer to the same underlying BtShared object.
10315**
10316** Schema objects are automatically deallocated when the last Btree that
10317** references them is destroyed.   The TEMP Schema is manually freed by
10318** sqlite3_close().
10319*
10320** A thread must be holding a mutex on the corresponding Btree in order
10321** to access Schema content.  This implies that the thread must also be
10322** holding a mutex on the sqlite3 connection pointer that owns the Btree.
10323** For a TEMP Schema, only the connection mutex is required.
10324*/
10325struct Schema {
10326  int schema_cookie;   /* Database schema version number for this file */
10327  int iGeneration;     /* Generation counter.  Incremented with each change */
10328  Hash tblHash;        /* All tables indexed by name */
10329  Hash idxHash;        /* All (named) indices indexed by name */
10330  Hash trigHash;       /* All triggers indexed by name */
10331  Hash fkeyHash;       /* All foreign keys by referenced table name */
10332  Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
10333  u8 file_format;      /* Schema format version for this file */
10334  u8 enc;              /* Text encoding used by this database */
10335  u16 flags;           /* Flags associated with this schema */
10336  int cache_size;      /* Number of pages to use in the cache */
10337};
10338
10339/*
10340** These macros can be used to test, set, or clear bits in the
10341** Db.pSchema->flags field.
10342*/
10343#define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
10344#define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
10345#define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
10346#define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
10347
10348/*
10349** Allowed values for the DB.pSchema->flags field.
10350**
10351** The DB_SchemaLoaded flag is set after the database schema has been
10352** read into internal hash tables.
10353**
10354** DB_UnresetViews means that one or more views have column names that
10355** have been filled out.  If the schema changes, these column names might
10356** changes and so the view will need to be reset.
10357*/
10358#define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
10359#define DB_UnresetViews    0x0002  /* Some views have defined column names */
10360#define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
10361
10362/*
10363** The number of different kinds of things that can be limited
10364** using the sqlite3_limit() interface.
10365*/
10366#define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
10367
10368/*
10369** Lookaside malloc is a set of fixed-size buffers that can be used
10370** to satisfy small transient memory allocation requests for objects
10371** associated with a particular database connection.  The use of
10372** lookaside malloc provides a significant performance enhancement
10373** (approx 10%) by avoiding numerous malloc/free requests while parsing
10374** SQL statements.
10375**
10376** The Lookaside structure holds configuration information about the
10377** lookaside malloc subsystem.  Each available memory allocation in
10378** the lookaside subsystem is stored on a linked list of LookasideSlot
10379** objects.
10380**
10381** Lookaside allocations are only allowed for objects that are associated
10382** with a particular database connection.  Hence, schema information cannot
10383** be stored in lookaside because in shared cache mode the schema information
10384** is shared by multiple database connections.  Therefore, while parsing
10385** schema information, the Lookaside.bEnabled flag is cleared so that
10386** lookaside allocations are not used to construct the schema objects.
10387*/
10388struct Lookaside {
10389  u16 sz;                 /* Size of each buffer in bytes */
10390  u8 bEnabled;            /* False to disable new lookaside allocations */
10391  u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
10392  int nOut;               /* Number of buffers currently checked out */
10393  int mxOut;              /* Highwater mark for nOut */
10394  int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
10395  LookasideSlot *pFree;   /* List of available buffers */
10396  void *pStart;           /* First byte of available memory space */
10397  void *pEnd;             /* First byte past end of available space */
10398};
10399struct LookasideSlot {
10400  LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
10401};
10402
10403/*
10404** A hash table for function definitions.
10405**
10406** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
10407** Collisions are on the FuncDef.pHash chain.
10408*/
10409struct FuncDefHash {
10410  FuncDef *a[23];       /* Hash table for functions */
10411};
10412
10413/*
10414** Each database connection is an instance of the following structure.
10415*/
10416struct sqlite3 {
10417  sqlite3_vfs *pVfs;            /* OS Interface */
10418  struct Vdbe *pVdbe;           /* List of active virtual machines */
10419  CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
10420  sqlite3_mutex *mutex;         /* Connection mutex */
10421  Db *aDb;                      /* All backends */
10422  int nDb;                      /* Number of backends currently in use */
10423  int flags;                    /* Miscellaneous flags. See below */
10424  i64 lastRowid;                /* ROWID of most recent insert (see above) */
10425  i64 szMmap;                   /* Default mmap_size setting */
10426  unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
10427  int errCode;                  /* Most recent error code (SQLITE_*) */
10428  int errMask;                  /* & result codes with this before returning */
10429  u16 dbOptFlags;               /* Flags to enable/disable optimizations */
10430  u8 autoCommit;                /* The auto-commit flag. */
10431  u8 temp_store;                /* 1: file 2: memory 0: default */
10432  u8 mallocFailed;              /* True if we have seen a malloc failure */
10433  u8 dfltLockMode;              /* Default locking-mode for attached dbs */
10434  signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
10435  u8 suppressErr;               /* Do not issue error messages if true */
10436  u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
10437  u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
10438  int nextPagesize;             /* Pagesize after VACUUM if >0 */
10439  u32 magic;                    /* Magic number for detect library misuse */
10440  int nChange;                  /* Value returned by sqlite3_changes() */
10441  int nTotalChange;             /* Value returned by sqlite3_total_changes() */
10442  int aLimit[SQLITE_N_LIMIT];   /* Limits */
10443  struct sqlite3InitInfo {      /* Information used during initialization */
10444    int newTnum;                /* Rootpage of table being initialized */
10445    u8 iDb;                     /* Which db file is being initialized */
10446    u8 busy;                    /* TRUE if currently initializing */
10447    u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
10448  } init;
10449  int nVdbeActive;              /* Number of VDBEs currently running */
10450  int nVdbeRead;                /* Number of active VDBEs that read or write */
10451  int nVdbeWrite;               /* Number of active VDBEs that read and write */
10452  int nVdbeExec;                /* Number of nested calls to VdbeExec() */
10453  int nExtension;               /* Number of loaded extensions */
10454  void **aExtension;            /* Array of shared library handles */
10455  void (*xTrace)(void*,const char*);        /* Trace function */
10456  void *pTraceArg;                          /* Argument to the trace function */
10457  void (*xProfile)(void*,const char*,u64);  /* Profiling function */
10458  void *pProfileArg;                        /* Argument to profile function */
10459  void *pCommitArg;                 /* Argument to xCommitCallback() */
10460  int (*xCommitCallback)(void*);    /* Invoked at every commit. */
10461  void *pRollbackArg;               /* Argument to xRollbackCallback() */
10462  void (*xRollbackCallback)(void*); /* Invoked at every commit. */
10463  void *pUpdateArg;
10464  void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
10465#ifndef SQLITE_OMIT_WAL
10466  int (*xWalCallback)(void *, sqlite3 *, const char *, int);
10467  void *pWalArg;
10468#endif
10469  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
10470  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
10471  void *pCollNeededArg;
10472  sqlite3_value *pErr;          /* Most recent error message */
10473  union {
10474    volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
10475    double notUsed1;            /* Spacer */
10476  } u1;
10477  Lookaside lookaside;          /* Lookaside malloc configuration */
10478#ifndef SQLITE_OMIT_AUTHORIZATION
10479  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
10480                                /* Access authorization function */
10481  void *pAuthArg;               /* 1st argument to the access auth function */
10482#endif
10483#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
10484  int (*xProgress)(void *);     /* The progress callback */
10485  void *pProgressArg;           /* Argument to the progress callback */
10486  unsigned nProgressOps;        /* Number of opcodes for progress callback */
10487#endif
10488#ifndef SQLITE_OMIT_VIRTUALTABLE
10489  int nVTrans;                  /* Allocated size of aVTrans */
10490  Hash aModule;                 /* populated by sqlite3_create_module() */
10491  VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
10492  VTable **aVTrans;             /* Virtual tables with open transactions */
10493  VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
10494#endif
10495  FuncDefHash aFunc;            /* Hash table of connection functions */
10496  Hash aCollSeq;                /* All collating sequences */
10497  BusyHandler busyHandler;      /* Busy callback */
10498  Db aDbStatic[2];              /* Static space for the 2 default backends */
10499  Savepoint *pSavepoint;        /* List of active savepoints */
10500  int busyTimeout;              /* Busy handler timeout, in msec */
10501  int nSavepoint;               /* Number of non-transaction savepoints */
10502  int nStatement;               /* Number of nested statement-transactions  */
10503  i64 nDeferredCons;            /* Net deferred constraints this transaction. */
10504  i64 nDeferredImmCons;         /* Net deferred immediate constraints */
10505  int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
10506
10507#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
10508  /* The following variables are all protected by the STATIC_MASTER
10509  ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
10510  **
10511  ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
10512  ** unlock so that it can proceed.
10513  **
10514  ** When X.pBlockingConnection==Y, that means that something that X tried
10515  ** tried to do recently failed with an SQLITE_LOCKED error due to locks
10516  ** held by Y.
10517  */
10518  sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
10519  sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
10520  void *pUnlockArg;                     /* Argument to xUnlockNotify */
10521  void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
10522  sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
10523#endif
10524};
10525
10526/*
10527** A macro to discover the encoding of a database.
10528*/
10529#define ENC(db) ((db)->aDb[0].pSchema->enc)
10530
10531/*
10532** Possible values for the sqlite3.flags.
10533*/
10534#define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
10535#define SQLITE_InternChanges  0x00000002  /* Uncommitted Hash table changes */
10536#define SQLITE_FullFSync      0x00000004  /* Use full fsync on the backend */
10537#define SQLITE_CkptFullFSync  0x00000008  /* Use full fsync for checkpoint */
10538#define SQLITE_CacheSpill     0x00000010  /* OK to spill pager cache */
10539#define SQLITE_FullColNames   0x00000020  /* Show full column names on SELECT */
10540#define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
10541#define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
10542                                          /*   DELETE, or UPDATE and return */
10543                                          /*   the count using a callback. */
10544#define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
10545                                          /*   result set is empty */
10546#define SQLITE_SqlTrace       0x00000200  /* Debug print SQL as it executes */
10547#define SQLITE_VdbeListing    0x00000400  /* Debug listings of VDBE programs */
10548#define SQLITE_WriteSchema    0x00000800  /* OK to update SQLITE_MASTER */
10549#define SQLITE_VdbeAddopTrace 0x00001000  /* Trace sqlite3VdbeAddOp() calls */
10550#define SQLITE_IgnoreChecks   0x00002000  /* Do not enforce check constraints */
10551#define SQLITE_ReadUncommitted 0x0004000  /* For shared-cache mode */
10552#define SQLITE_LegacyFileFmt  0x00008000  /* Create new databases in format 1 */
10553#define SQLITE_RecoveryMode   0x00010000  /* Ignore schema errors */
10554#define SQLITE_ReverseOrder   0x00020000  /* Reverse unordered SELECTs */
10555#define SQLITE_RecTriggers    0x00040000  /* Enable recursive triggers */
10556#define SQLITE_ForeignKeys    0x00080000  /* Enforce foreign key constraints  */
10557#define SQLITE_AutoIndex      0x00100000  /* Enable automatic indexes */
10558#define SQLITE_PreferBuiltin  0x00200000  /* Preference to built-in funcs */
10559#define SQLITE_LoadExtension  0x00400000  /* Enable load_extension */
10560#define SQLITE_EnableTrigger  0x00800000  /* True to enable triggers */
10561#define SQLITE_DeferFKs       0x01000000  /* Defer all FK constraints */
10562#define SQLITE_QueryOnly      0x02000000  /* Disable database changes */
10563#define SQLITE_VdbeEQP        0x04000000  /* Debug EXPLAIN QUERY PLAN */
10564
10565
10566/*
10567** Bits of the sqlite3.dbOptFlags field that are used by the
10568** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
10569** selectively disable various optimizations.
10570*/
10571#define SQLITE_QueryFlattener 0x0001   /* Query flattening */
10572#define SQLITE_ColumnCache    0x0002   /* Column cache */
10573#define SQLITE_GroupByOrder   0x0004   /* GROUPBY cover of ORDERBY */
10574#define SQLITE_FactorOutConst 0x0008   /* Constant factoring */
10575/*                not used    0x0010   // Was: SQLITE_IdxRealAsInt */
10576#define SQLITE_DistinctOpt    0x0020   /* DISTINCT using indexes */
10577#define SQLITE_CoverIdxScan   0x0040   /* Covering index scans */
10578#define SQLITE_OrderByIdxJoin 0x0080   /* ORDER BY of joins via index */
10579#define SQLITE_SubqCoroutine  0x0100   /* Evaluate subqueries as coroutines */
10580#define SQLITE_Transitive     0x0200   /* Transitive constraints */
10581#define SQLITE_OmitNoopJoin   0x0400   /* Omit unused tables in joins */
10582#define SQLITE_Stat3          0x0800   /* Use the SQLITE_STAT3 table */
10583#define SQLITE_AdjustOutEst   0x1000   /* Adjust output estimates using WHERE */
10584#define SQLITE_AllOpts        0xffff   /* All optimizations */
10585
10586/*
10587** Macros for testing whether or not optimizations are enabled or disabled.
10588*/
10589#ifndef SQLITE_OMIT_BUILTIN_TEST
10590#define OptimizationDisabled(db, mask)  (((db)->dbOptFlags&(mask))!=0)
10591#define OptimizationEnabled(db, mask)   (((db)->dbOptFlags&(mask))==0)
10592#else
10593#define OptimizationDisabled(db, mask)  0
10594#define OptimizationEnabled(db, mask)   1
10595#endif
10596
10597/*
10598** Return true if it OK to factor constant expressions into the initialization
10599** code. The argument is a Parse object for the code generator.
10600*/
10601#define ConstFactorOk(P) ((P)->okConstFactor)
10602
10603/*
10604** Possible values for the sqlite.magic field.
10605** The numbers are obtained at random and have no special meaning, other
10606** than being distinct from one another.
10607*/
10608#define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
10609#define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
10610#define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
10611#define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
10612#define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
10613#define SQLITE_MAGIC_ZOMBIE   0x64cffc7f  /* Close with last statement close */
10614
10615/*
10616** Each SQL function is defined by an instance of the following
10617** structure.  A pointer to this structure is stored in the sqlite.aFunc
10618** hash table.  When multiple functions have the same name, the hash table
10619** points to a linked list of these structures.
10620*/
10621struct FuncDef {
10622  i16 nArg;            /* Number of arguments.  -1 means unlimited */
10623  u16 funcFlags;       /* Some combination of SQLITE_FUNC_* */
10624  void *pUserData;     /* User data parameter */
10625  FuncDef *pNext;      /* Next function with same name */
10626  void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
10627  void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
10628  void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
10629  char *zName;         /* SQL name of the function. */
10630  FuncDef *pHash;      /* Next with a different name but the same hash */
10631  FuncDestructor *pDestructor;   /* Reference counted destructor function */
10632};
10633
10634/*
10635** This structure encapsulates a user-function destructor callback (as
10636** configured using create_function_v2()) and a reference counter. When
10637** create_function_v2() is called to create a function with a destructor,
10638** a single object of this type is allocated. FuncDestructor.nRef is set to
10639** the number of FuncDef objects created (either 1 or 3, depending on whether
10640** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
10641** member of each of the new FuncDef objects is set to point to the allocated
10642** FuncDestructor.
10643**
10644** Thereafter, when one of the FuncDef objects is deleted, the reference
10645** count on this object is decremented. When it reaches 0, the destructor
10646** is invoked and the FuncDestructor structure freed.
10647*/
10648struct FuncDestructor {
10649  int nRef;
10650  void (*xDestroy)(void *);
10651  void *pUserData;
10652};
10653
10654/*
10655** Possible values for FuncDef.flags.  Note that the _LENGTH and _TYPEOF
10656** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG.  There
10657** are assert() statements in the code to verify this.
10658*/
10659#define SQLITE_FUNC_ENCMASK  0x003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
10660#define SQLITE_FUNC_LIKE     0x004 /* Candidate for the LIKE optimization */
10661#define SQLITE_FUNC_CASE     0x008 /* Case-sensitive LIKE-type function */
10662#define SQLITE_FUNC_EPHEM    0x010 /* Ephemeral.  Delete with VDBE */
10663#define SQLITE_FUNC_NEEDCOLL 0x020 /* sqlite3GetFuncCollSeq() might be called */
10664#define SQLITE_FUNC_LENGTH   0x040 /* Built-in length() function */
10665#define SQLITE_FUNC_TYPEOF   0x080 /* Built-in typeof() function */
10666#define SQLITE_FUNC_COUNT    0x100 /* Built-in count(*) aggregate */
10667#define SQLITE_FUNC_COALESCE 0x200 /* Built-in coalesce() or ifnull() */
10668#define SQLITE_FUNC_UNLIKELY 0x400 /* Built-in unlikely() function */
10669#define SQLITE_FUNC_CONSTANT 0x800 /* Constant inputs give a constant output */
10670
10671/*
10672** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
10673** used to create the initializers for the FuncDef structures.
10674**
10675**   FUNCTION(zName, nArg, iArg, bNC, xFunc)
10676**     Used to create a scalar function definition of a function zName
10677**     implemented by C function xFunc that accepts nArg arguments. The
10678**     value passed as iArg is cast to a (void*) and made available
10679**     as the user-data (sqlite3_user_data()) for the function. If
10680**     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
10681**
10682**   VFUNCTION(zName, nArg, iArg, bNC, xFunc)
10683**     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
10684**
10685**   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
10686**     Used to create an aggregate function definition implemented by
10687**     the C functions xStep and xFinal. The first four parameters
10688**     are interpreted in the same way as the first 4 parameters to
10689**     FUNCTION().
10690**
10691**   LIKEFUNC(zName, nArg, pArg, flags)
10692**     Used to create a scalar function definition of a function zName
10693**     that accepts nArg arguments and is implemented by a call to C
10694**     function likeFunc. Argument pArg is cast to a (void *) and made
10695**     available as the function user-data (sqlite3_user_data()). The
10696**     FuncDef.flags variable is set to the value passed as the flags
10697**     parameter.
10698*/
10699#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
10700  {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
10701   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10702#define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
10703  {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
10704   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10705#define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
10706  {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
10707   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10708#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
10709  {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
10710   pArg, 0, xFunc, 0, 0, #zName, 0, 0}
10711#define LIKEFUNC(zName, nArg, arg, flags) \
10712  {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
10713   (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
10714#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
10715  {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
10716   SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
10717
10718/*
10719** All current savepoints are stored in a linked list starting at
10720** sqlite3.pSavepoint. The first element in the list is the most recently
10721** opened savepoint. Savepoints are added to the list by the vdbe
10722** OP_Savepoint instruction.
10723*/
10724struct Savepoint {
10725  char *zName;                        /* Savepoint name (nul-terminated) */
10726  i64 nDeferredCons;                  /* Number of deferred fk violations */
10727  i64 nDeferredImmCons;               /* Number of deferred imm fk. */
10728  Savepoint *pNext;                   /* Parent savepoint (if any) */
10729};
10730
10731/*
10732** The following are used as the second parameter to sqlite3Savepoint(),
10733** and as the P1 argument to the OP_Savepoint instruction.
10734*/
10735#define SAVEPOINT_BEGIN      0
10736#define SAVEPOINT_RELEASE    1
10737#define SAVEPOINT_ROLLBACK   2
10738
10739
10740/*
10741** Each SQLite module (virtual table definition) is defined by an
10742** instance of the following structure, stored in the sqlite3.aModule
10743** hash table.
10744*/
10745struct Module {
10746  const sqlite3_module *pModule;       /* Callback pointers */
10747  const char *zName;                   /* Name passed to create_module() */
10748  void *pAux;                          /* pAux passed to create_module() */
10749  void (*xDestroy)(void *);            /* Module destructor function */
10750};
10751
10752/*
10753** information about each column of an SQL table is held in an instance
10754** of this structure.
10755*/
10756struct Column {
10757  char *zName;     /* Name of this column */
10758  Expr *pDflt;     /* Default value of this column */
10759  char *zDflt;     /* Original text of the default value */
10760  char *zType;     /* Data type for this column */
10761  char *zColl;     /* Collating sequence.  If NULL, use the default */
10762  u8 notNull;      /* An OE_ code for handling a NOT NULL constraint */
10763  char affinity;   /* One of the SQLITE_AFF_... values */
10764  u8 szEst;        /* Estimated size of this column.  INT==1 */
10765  u8 colFlags;     /* Boolean properties.  See COLFLAG_ defines below */
10766};
10767
10768/* Allowed values for Column.colFlags:
10769*/
10770#define COLFLAG_PRIMKEY  0x0001    /* Column is part of the primary key */
10771#define COLFLAG_HIDDEN   0x0002    /* A hidden column in a virtual table */
10772
10773/*
10774** A "Collating Sequence" is defined by an instance of the following
10775** structure. Conceptually, a collating sequence consists of a name and
10776** a comparison routine that defines the order of that sequence.
10777**
10778** If CollSeq.xCmp is NULL, it means that the
10779** collating sequence is undefined.  Indices built on an undefined
10780** collating sequence may not be read or written.
10781*/
10782struct CollSeq {
10783  char *zName;          /* Name of the collating sequence, UTF-8 encoded */
10784  u8 enc;               /* Text encoding handled by xCmp() */
10785  void *pUser;          /* First argument to xCmp() */
10786  int (*xCmp)(void*,int, const void*, int, const void*);
10787  void (*xDel)(void*);  /* Destructor for pUser */
10788};
10789
10790/*
10791** A sort order can be either ASC or DESC.
10792*/
10793#define SQLITE_SO_ASC       0  /* Sort in ascending order */
10794#define SQLITE_SO_DESC      1  /* Sort in ascending order */
10795
10796/*
10797** Column affinity types.
10798**
10799** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
10800** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
10801** the speed a little by numbering the values consecutively.
10802**
10803** But rather than start with 0 or 1, we begin with 'a'.  That way,
10804** when multiple affinity types are concatenated into a string and
10805** used as the P4 operand, they will be more readable.
10806**
10807** Note also that the numeric types are grouped together so that testing
10808** for a numeric type is a single comparison.
10809*/
10810#define SQLITE_AFF_TEXT     'a'
10811#define SQLITE_AFF_NONE     'b'
10812#define SQLITE_AFF_NUMERIC  'c'
10813#define SQLITE_AFF_INTEGER  'd'
10814#define SQLITE_AFF_REAL     'e'
10815
10816#define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
10817
10818/*
10819** The SQLITE_AFF_MASK values masks off the significant bits of an
10820** affinity value.
10821*/
10822#define SQLITE_AFF_MASK     0x67
10823
10824/*
10825** Additional bit values that can be ORed with an affinity without
10826** changing the affinity.
10827**
10828** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
10829** It causes an assert() to fire if either operand to a comparison
10830** operator is NULL.  It is added to certain comparison operators to
10831** prove that the operands are always NOT NULL.
10832*/
10833#define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
10834#define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
10835#define SQLITE_NULLEQ       0x80  /* NULL=NULL */
10836#define SQLITE_NOTNULL      0x88  /* Assert that operands are never NULL */
10837
10838/*
10839** An object of this type is created for each virtual table present in
10840** the database schema.
10841**
10842** If the database schema is shared, then there is one instance of this
10843** structure for each database connection (sqlite3*) that uses the shared
10844** schema. This is because each database connection requires its own unique
10845** instance of the sqlite3_vtab* handle used to access the virtual table
10846** implementation. sqlite3_vtab* handles can not be shared between
10847** database connections, even when the rest of the in-memory database
10848** schema is shared, as the implementation often stores the database
10849** connection handle passed to it via the xConnect() or xCreate() method
10850** during initialization internally. This database connection handle may
10851** then be used by the virtual table implementation to access real tables
10852** within the database. So that they appear as part of the callers
10853** transaction, these accesses need to be made via the same database
10854** connection as that used to execute SQL operations on the virtual table.
10855**
10856** All VTable objects that correspond to a single table in a shared
10857** database schema are initially stored in a linked-list pointed to by
10858** the Table.pVTable member variable of the corresponding Table object.
10859** When an sqlite3_prepare() operation is required to access the virtual
10860** table, it searches the list for the VTable that corresponds to the
10861** database connection doing the preparing so as to use the correct
10862** sqlite3_vtab* handle in the compiled query.
10863**
10864** When an in-memory Table object is deleted (for example when the
10865** schema is being reloaded for some reason), the VTable objects are not
10866** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
10867** immediately. Instead, they are moved from the Table.pVTable list to
10868** another linked list headed by the sqlite3.pDisconnect member of the
10869** corresponding sqlite3 structure. They are then deleted/xDisconnected
10870** next time a statement is prepared using said sqlite3*. This is done
10871** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
10872** Refer to comments above function sqlite3VtabUnlockList() for an
10873** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
10874** list without holding the corresponding sqlite3.mutex mutex.
10875**
10876** The memory for objects of this type is always allocated by
10877** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
10878** the first argument.
10879*/
10880struct VTable {
10881  sqlite3 *db;              /* Database connection associated with this table */
10882  Module *pMod;             /* Pointer to module implementation */
10883  sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
10884  int nRef;                 /* Number of pointers to this structure */
10885  u8 bConstraint;           /* True if constraints are supported */
10886  int iSavepoint;           /* Depth of the SAVEPOINT stack */
10887  VTable *pNext;            /* Next in linked list (see above) */
10888};
10889
10890/*
10891** Each SQL table is represented in memory by an instance of the
10892** following structure.
10893**
10894** Table.zName is the name of the table.  The case of the original
10895** CREATE TABLE statement is stored, but case is not significant for
10896** comparisons.
10897**
10898** Table.nCol is the number of columns in this table.  Table.aCol is a
10899** pointer to an array of Column structures, one for each column.
10900**
10901** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
10902** the column that is that key.   Otherwise Table.iPKey is negative.  Note
10903** that the datatype of the PRIMARY KEY must be INTEGER for this field to
10904** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
10905** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
10906** is generated for each row of the table.  TF_HasPrimaryKey is set if
10907** the table has any PRIMARY KEY, INTEGER or otherwise.
10908**
10909** Table.tnum is the page number for the root BTree page of the table in the
10910** database file.  If Table.iDb is the index of the database table backend
10911** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
10912** holds temporary tables and indices.  If TF_Ephemeral is set
10913** then the table is stored in a file that is automatically deleted
10914** when the VDBE cursor to the table is closed.  In this case Table.tnum
10915** refers VDBE cursor number that holds the table open, not to the root
10916** page number.  Transient tables are used to hold the results of a
10917** sub-query that appears instead of a real table name in the FROM clause
10918** of a SELECT statement.
10919*/
10920struct Table {
10921  char *zName;         /* Name of the table or view */
10922  Column *aCol;        /* Information about each column */
10923  Index *pIndex;       /* List of SQL indexes on this table. */
10924  Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
10925  FKey *pFKey;         /* Linked list of all foreign keys in this table */
10926  char *zColAff;       /* String defining the affinity of each column */
10927#ifndef SQLITE_OMIT_CHECK
10928  ExprList *pCheck;    /* All CHECK constraints */
10929#endif
10930  LogEst nRowLogEst;   /* Estimated rows in table - from sqlite_stat1 table */
10931  int tnum;            /* Root BTree node for this table (see note above) */
10932  i16 iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
10933  i16 nCol;            /* Number of columns in this table */
10934  u16 nRef;            /* Number of pointers to this Table */
10935  LogEst szTabRow;     /* Estimated size of each table row in bytes */
10936  u8 tabFlags;         /* Mask of TF_* values */
10937  u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
10938#ifndef SQLITE_OMIT_ALTERTABLE
10939  int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
10940#endif
10941#ifndef SQLITE_OMIT_VIRTUALTABLE
10942  int nModuleArg;      /* Number of arguments to the module */
10943  char **azModuleArg;  /* Text of all module args. [0] is module name */
10944  VTable *pVTable;     /* List of VTable objects. */
10945#endif
10946  Trigger *pTrigger;   /* List of triggers stored in pSchema */
10947  Schema *pSchema;     /* Schema that contains this table */
10948  Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
10949};
10950
10951/*
10952** Allowed values for Table.tabFlags.
10953*/
10954#define TF_Readonly        0x01    /* Read-only system table */
10955#define TF_Ephemeral       0x02    /* An ephemeral table */
10956#define TF_HasPrimaryKey   0x04    /* Table has a primary key */
10957#define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
10958#define TF_Virtual         0x10    /* Is a virtual table */
10959#define TF_WithoutRowid    0x20    /* No rowid used. PRIMARY KEY is the key */
10960
10961
10962/*
10963** Test to see whether or not a table is a virtual table.  This is
10964** done as a macro so that it will be optimized out when virtual
10965** table support is omitted from the build.
10966*/
10967#ifndef SQLITE_OMIT_VIRTUALTABLE
10968#  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
10969#  define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
10970#else
10971#  define IsVirtual(X)      0
10972#  define IsHiddenColumn(X) 0
10973#endif
10974
10975/* Does the table have a rowid */
10976#define HasRowid(X)     (((X)->tabFlags & TF_WithoutRowid)==0)
10977
10978/*
10979** Each foreign key constraint is an instance of the following structure.
10980**
10981** A foreign key is associated with two tables.  The "from" table is
10982** the table that contains the REFERENCES clause that creates the foreign
10983** key.  The "to" table is the table that is named in the REFERENCES clause.
10984** Consider this example:
10985**
10986**     CREATE TABLE ex1(
10987**       a INTEGER PRIMARY KEY,
10988**       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
10989**     );
10990**
10991** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
10992** Equivalent names:
10993**
10994**     from-table == child-table
10995**       to-table == parent-table
10996**
10997** Each REFERENCES clause generates an instance of the following structure
10998** which is attached to the from-table.  The to-table need not exist when
10999** the from-table is created.  The existence of the to-table is not checked.
11000**
11001** The list of all parents for child Table X is held at X.pFKey.
11002**
11003** A list of all children for a table named Z (which might not even exist)
11004** is held in Schema.fkeyHash with a hash key of Z.
11005*/
11006struct FKey {
11007  Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
11008  FKey *pNextFrom;  /* Next FKey with the same in pFrom. Next parent of pFrom */
11009  char *zTo;        /* Name of table that the key points to (aka: Parent) */
11010  FKey *pNextTo;    /* Next with the same zTo. Next child of zTo. */
11011  FKey *pPrevTo;    /* Previous with the same zTo */
11012  int nCol;         /* Number of columns in this key */
11013  /* EV: R-30323-21917 */
11014  u8 isDeferred;       /* True if constraint checking is deferred till COMMIT */
11015  u8 aAction[2];        /* ON DELETE and ON UPDATE actions, respectively */
11016  Trigger *apTrigger[2];/* Triggers for aAction[] actions */
11017  struct sColMap {      /* Mapping of columns in pFrom to columns in zTo */
11018    int iFrom;            /* Index of column in pFrom */
11019    char *zCol;           /* Name of column in zTo.  If NULL use PRIMARY KEY */
11020  } aCol[1];            /* One entry for each of nCol columns */
11021};
11022
11023/*
11024** SQLite supports many different ways to resolve a constraint
11025** error.  ROLLBACK processing means that a constraint violation
11026** causes the operation in process to fail and for the current transaction
11027** to be rolled back.  ABORT processing means the operation in process
11028** fails and any prior changes from that one operation are backed out,
11029** but the transaction is not rolled back.  FAIL processing means that
11030** the operation in progress stops and returns an error code.  But prior
11031** changes due to the same operation are not backed out and no rollback
11032** occurs.  IGNORE means that the particular row that caused the constraint
11033** error is not inserted or updated.  Processing continues and no error
11034** is returned.  REPLACE means that preexisting database rows that caused
11035** a UNIQUE constraint violation are removed so that the new insert or
11036** update can proceed.  Processing continues and no error is reported.
11037**
11038** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
11039** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
11040** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
11041** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
11042** referenced table row is propagated into the row that holds the
11043** foreign key.
11044**
11045** The following symbolic values are used to record which type
11046** of action to take.
11047*/
11048#define OE_None     0   /* There is no constraint to check */
11049#define OE_Rollback 1   /* Fail the operation and rollback the transaction */
11050#define OE_Abort    2   /* Back out changes but do no rollback transaction */
11051#define OE_Fail     3   /* Stop the operation but leave all prior changes */
11052#define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
11053#define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
11054
11055#define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
11056#define OE_SetNull  7   /* Set the foreign key value to NULL */
11057#define OE_SetDflt  8   /* Set the foreign key value to its default */
11058#define OE_Cascade  9   /* Cascade the changes */
11059
11060#define OE_Default  10  /* Do whatever the default action is */
11061
11062
11063/*
11064** An instance of the following structure is passed as the first
11065** argument to sqlite3VdbeKeyCompare and is used to control the
11066** comparison of the two index keys.
11067**
11068** Note that aSortOrder[] and aColl[] have nField+1 slots.  There
11069** are nField slots for the columns of an index then one extra slot
11070** for the rowid at the end.
11071*/
11072struct KeyInfo {
11073  u32 nRef;           /* Number of references to this KeyInfo object */
11074  u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
11075  u16 nField;         /* Number of key columns in the index */
11076  u16 nXField;        /* Number of columns beyond the key columns */
11077  sqlite3 *db;        /* The database connection */
11078  u8 *aSortOrder;     /* Sort order for each column. */
11079  CollSeq *aColl[1];  /* Collating sequence for each term of the key */
11080};
11081
11082/*
11083** An instance of the following structure holds information about a
11084** single index record that has already been parsed out into individual
11085** values.
11086**
11087** A record is an object that contains one or more fields of data.
11088** Records are used to store the content of a table row and to store
11089** the key of an index.  A blob encoding of a record is created by
11090** the OP_MakeRecord opcode of the VDBE and is disassembled by the
11091** OP_Column opcode.
11092**
11093** This structure holds a record that has already been disassembled
11094** into its constituent fields.
11095**
11096** The r1 and r2 member variables are only used by the optimized comparison
11097** functions vdbeRecordCompareInt() and vdbeRecordCompareString().
11098*/
11099struct UnpackedRecord {
11100  KeyInfo *pKeyInfo;  /* Collation and sort-order information */
11101  u16 nField;         /* Number of entries in apMem[] */
11102  i8 default_rc;      /* Comparison result if keys are equal */
11103  u8 isCorrupt;       /* Corruption detected by xRecordCompare() */
11104  Mem *aMem;          /* Values */
11105  int r1;             /* Value to return if (lhs > rhs) */
11106  int r2;             /* Value to return if (rhs < lhs) */
11107};
11108
11109
11110/*
11111** Each SQL index is represented in memory by an
11112** instance of the following structure.
11113**
11114** The columns of the table that are to be indexed are described
11115** by the aiColumn[] field of this structure.  For example, suppose
11116** we have the following table and index:
11117**
11118**     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
11119**     CREATE INDEX Ex2 ON Ex1(c3,c1);
11120**
11121** In the Table structure describing Ex1, nCol==3 because there are
11122** three columns in the table.  In the Index structure describing
11123** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
11124** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
11125** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
11126** The second column to be indexed (c1) has an index of 0 in
11127** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
11128**
11129** The Index.onError field determines whether or not the indexed columns
11130** must be unique and what to do if they are not.  When Index.onError=OE_None,
11131** it means this is not a unique index.  Otherwise it is a unique index
11132** and the value of Index.onError indicate the which conflict resolution
11133** algorithm to employ whenever an attempt is made to insert a non-unique
11134** element.
11135*/
11136struct Index {
11137  char *zName;             /* Name of this index */
11138  i16 *aiColumn;           /* Which columns are used by this index.  1st is 0 */
11139  LogEst *aiRowLogEst;     /* From ANALYZE: Est. rows selected by each column */
11140  Table *pTable;           /* The SQL table being indexed */
11141  char *zColAff;           /* String defining the affinity of each column */
11142  Index *pNext;            /* The next index associated with the same table */
11143  Schema *pSchema;         /* Schema containing this index */
11144  u8 *aSortOrder;          /* for each column: True==DESC, False==ASC */
11145  char **azColl;           /* Array of collation sequence names for index */
11146  Expr *pPartIdxWhere;     /* WHERE clause for partial indices */
11147  KeyInfo *pKeyInfo;       /* A KeyInfo object suitable for this index */
11148  int tnum;                /* DB Page containing root of this index */
11149  LogEst szIdxRow;         /* Estimated average row size in bytes */
11150  u16 nKeyCol;             /* Number of columns forming the key */
11151  u16 nColumn;             /* Number of columns stored in the index */
11152  u8 onError;              /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
11153  unsigned idxType:2;      /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
11154  unsigned bUnordered:1;   /* Use this index for == or IN queries only */
11155  unsigned uniqNotNull:1;  /* True if UNIQUE and NOT NULL for all columns */
11156  unsigned isResized:1;    /* True if resizeIndexObject() has been called */
11157  unsigned isCovering:1;   /* True if this is a covering index */
11158#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
11159  int nSample;             /* Number of elements in aSample[] */
11160  int nSampleCol;          /* Size of IndexSample.anEq[] and so on */
11161  tRowcnt *aAvgEq;         /* Average nEq values for keys not in aSample */
11162  IndexSample *aSample;    /* Samples of the left-most key */
11163#endif
11164};
11165
11166/*
11167** Allowed values for Index.idxType
11168*/
11169#define SQLITE_IDXTYPE_APPDEF      0   /* Created using CREATE INDEX */
11170#define SQLITE_IDXTYPE_UNIQUE      1   /* Implements a UNIQUE constraint */
11171#define SQLITE_IDXTYPE_PRIMARYKEY  2   /* Is the PRIMARY KEY for the table */
11172
11173/* Return true if index X is a PRIMARY KEY index */
11174#define IsPrimaryKeyIndex(X)  ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
11175
11176/*
11177** Each sample stored in the sqlite_stat3 table is represented in memory
11178** using a structure of this type.  See documentation at the top of the
11179** analyze.c source file for additional information.
11180*/
11181struct IndexSample {
11182  void *p;          /* Pointer to sampled record */
11183  int n;            /* Size of record in bytes */
11184  tRowcnt *anEq;    /* Est. number of rows where the key equals this sample */
11185  tRowcnt *anLt;    /* Est. number of rows where key is less than this sample */
11186  tRowcnt *anDLt;   /* Est. number of distinct keys less than this sample */
11187};
11188
11189/*
11190** Each token coming out of the lexer is an instance of
11191** this structure.  Tokens are also used as part of an expression.
11192**
11193** Note if Token.z==0 then Token.dyn and Token.n are undefined and
11194** may contain random values.  Do not make any assumptions about Token.dyn
11195** and Token.n when Token.z==0.
11196*/
11197struct Token {
11198  const char *z;     /* Text of the token.  Not NULL-terminated! */
11199  unsigned int n;    /* Number of characters in this token */
11200};
11201
11202/*
11203** An instance of this structure contains information needed to generate
11204** code for a SELECT that contains aggregate functions.
11205**
11206** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
11207** pointer to this structure.  The Expr.iColumn field is the index in
11208** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
11209** code for that node.
11210**
11211** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
11212** original Select structure that describes the SELECT statement.  These
11213** fields do not need to be freed when deallocating the AggInfo structure.
11214*/
11215struct AggInfo {
11216  u8 directMode;          /* Direct rendering mode means take data directly
11217                          ** from source tables rather than from accumulators */
11218  u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
11219                          ** than the source table */
11220  int sortingIdx;         /* Cursor number of the sorting index */
11221  int sortingIdxPTab;     /* Cursor number of pseudo-table */
11222  int nSortingColumn;     /* Number of columns in the sorting index */
11223  int mnReg, mxReg;       /* Range of registers allocated for aCol and aFunc */
11224  ExprList *pGroupBy;     /* The group by clause */
11225  struct AggInfo_col {    /* For each column used in source tables */
11226    Table *pTab;             /* Source table */
11227    int iTable;              /* Cursor number of the source table */
11228    int iColumn;             /* Column number within the source table */
11229    int iSorterColumn;       /* Column number in the sorting index */
11230    int iMem;                /* Memory location that acts as accumulator */
11231    Expr *pExpr;             /* The original expression */
11232  } *aCol;
11233  int nColumn;            /* Number of used entries in aCol[] */
11234  int nAccumulator;       /* Number of columns that show through to the output.
11235                          ** Additional columns are used only as parameters to
11236                          ** aggregate functions */
11237  struct AggInfo_func {   /* For each aggregate function */
11238    Expr *pExpr;             /* Expression encoding the function */
11239    FuncDef *pFunc;          /* The aggregate function implementation */
11240    int iMem;                /* Memory location that acts as accumulator */
11241    int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
11242  } *aFunc;
11243  int nFunc;              /* Number of entries in aFunc[] */
11244};
11245
11246/*
11247** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
11248** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
11249** than 32767 we have to make it 32-bit.  16-bit is preferred because
11250** it uses less memory in the Expr object, which is a big memory user
11251** in systems with lots of prepared statements.  And few applications
11252** need more than about 10 or 20 variables.  But some extreme users want
11253** to have prepared statements with over 32767 variables, and for them
11254** the option is available (at compile-time).
11255*/
11256#if SQLITE_MAX_VARIABLE_NUMBER<=32767
11257typedef i16 ynVar;
11258#else
11259typedef int ynVar;
11260#endif
11261
11262/*
11263** Each node of an expression in the parse tree is an instance
11264** of this structure.
11265**
11266** Expr.op is the opcode. The integer parser token codes are reused
11267** as opcodes here. For example, the parser defines TK_GE to be an integer
11268** code representing the ">=" operator. This same integer code is reused
11269** to represent the greater-than-or-equal-to operator in the expression
11270** tree.
11271**
11272** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
11273** or TK_STRING), then Expr.token contains the text of the SQL literal. If
11274** the expression is a variable (TK_VARIABLE), then Expr.token contains the
11275** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
11276** then Expr.token contains the name of the function.
11277**
11278** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
11279** binary operator. Either or both may be NULL.
11280**
11281** Expr.x.pList is a list of arguments if the expression is an SQL function,
11282** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
11283** Expr.x.pSelect is used if the expression is a sub-select or an expression of
11284** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
11285** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
11286** valid.
11287**
11288** An expression of the form ID or ID.ID refers to a column in a table.
11289** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
11290** the integer cursor number of a VDBE cursor pointing to that table and
11291** Expr.iColumn is the column number for the specific column.  If the
11292** expression is used as a result in an aggregate SELECT, then the
11293** value is also stored in the Expr.iAgg column in the aggregate so that
11294** it can be accessed after all aggregates are computed.
11295**
11296** If the expression is an unbound variable marker (a question mark
11297** character '?' in the original SQL) then the Expr.iTable holds the index
11298** number for that variable.
11299**
11300** If the expression is a subquery then Expr.iColumn holds an integer
11301** register number containing the result of the subquery.  If the
11302** subquery gives a constant result, then iTable is -1.  If the subquery
11303** gives a different answer at different times during statement processing
11304** then iTable is the address of a subroutine that computes the subquery.
11305**
11306** If the Expr is of type OP_Column, and the table it is selecting from
11307** is a disk table or the "old.*" pseudo-table, then pTab points to the
11308** corresponding table definition.
11309**
11310** ALLOCATION NOTES:
11311**
11312** Expr objects can use a lot of memory space in database schema.  To
11313** help reduce memory requirements, sometimes an Expr object will be
11314** truncated.  And to reduce the number of memory allocations, sometimes
11315** two or more Expr objects will be stored in a single memory allocation,
11316** together with Expr.zToken strings.
11317**
11318** If the EP_Reduced and EP_TokenOnly flags are set when
11319** an Expr object is truncated.  When EP_Reduced is set, then all
11320** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
11321** are contained within the same memory allocation.  Note, however, that
11322** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
11323** allocated, regardless of whether or not EP_Reduced is set.
11324*/
11325struct Expr {
11326  u8 op;                 /* Operation performed by this node */
11327  char affinity;         /* The affinity of the column or 0 if not a column */
11328  u32 flags;             /* Various flags.  EP_* See below */
11329  union {
11330    char *zToken;          /* Token value. Zero terminated and dequoted */
11331    int iValue;            /* Non-negative integer value if EP_IntValue */
11332  } u;
11333
11334  /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
11335  ** space is allocated for the fields below this point. An attempt to
11336  ** access them will result in a segfault or malfunction.
11337  *********************************************************************/
11338
11339  Expr *pLeft;           /* Left subnode */
11340  Expr *pRight;          /* Right subnode */
11341  union {
11342    ExprList *pList;     /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
11343    Select *pSelect;     /* EP_xIsSelect and op = IN, EXISTS, SELECT */
11344  } x;
11345
11346  /* If the EP_Reduced flag is set in the Expr.flags mask, then no
11347  ** space is allocated for the fields below this point. An attempt to
11348  ** access them will result in a segfault or malfunction.
11349  *********************************************************************/
11350
11351#if SQLITE_MAX_EXPR_DEPTH>0
11352  int nHeight;           /* Height of the tree headed by this node */
11353#endif
11354  int iTable;            /* TK_COLUMN: cursor number of table holding column
11355                         ** TK_REGISTER: register number
11356                         ** TK_TRIGGER: 1 -> new, 0 -> old
11357                         ** EP_Unlikely:  1000 times likelihood */
11358  ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
11359                         ** TK_VARIABLE: variable number (always >= 1). */
11360  i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
11361  i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
11362  u8 op2;                /* TK_REGISTER: original value of Expr.op
11363                         ** TK_COLUMN: the value of p5 for OP_Column
11364                         ** TK_AGG_FUNCTION: nesting depth */
11365  AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
11366  Table *pTab;           /* Table for TK_COLUMN expressions. */
11367};
11368
11369/*
11370** The following are the meanings of bits in the Expr.flags field.
11371*/
11372#define EP_FromJoin  0x000001 /* Originated in ON or USING clause of a join */
11373#define EP_Agg       0x000002 /* Contains one or more aggregate functions */
11374#define EP_Resolved  0x000004 /* IDs have been resolved to COLUMNs */
11375#define EP_Error     0x000008 /* Expression contains one or more errors */
11376#define EP_Distinct  0x000010 /* Aggregate function with DISTINCT keyword */
11377#define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
11378#define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
11379#define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
11380#define EP_Collate   0x000100 /* Tree contains a TK_COLLATE operator */
11381#define EP_Generic   0x000200 /* Ignore COLLATE or affinity on this tree */
11382#define EP_IntValue  0x000400 /* Integer value contained in u.iValue */
11383#define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
11384#define EP_Skip      0x001000 /* COLLATE, AS, or UNLIKELY */
11385#define EP_Reduced   0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
11386#define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
11387#define EP_Static    0x008000 /* Held in memory not obtained from malloc() */
11388#define EP_MemToken  0x010000 /* Need to sqlite3DbFree() Expr.zToken */
11389#define EP_NoReduce  0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
11390#define EP_Unlikely  0x040000 /* unlikely() or likelihood() function */
11391#define EP_Constant  0x080000 /* Node is a constant */
11392
11393/*
11394** These macros can be used to test, set, or clear bits in the
11395** Expr.flags field.
11396*/
11397#define ExprHasProperty(E,P)     (((E)->flags&(P))!=0)
11398#define ExprHasAllProperty(E,P)  (((E)->flags&(P))==(P))
11399#define ExprSetProperty(E,P)     (E)->flags|=(P)
11400#define ExprClearProperty(E,P)   (E)->flags&=~(P)
11401
11402/* The ExprSetVVAProperty() macro is used for Verification, Validation,
11403** and Accreditation only.  It works like ExprSetProperty() during VVA
11404** processes but is a no-op for delivery.
11405*/
11406#ifdef SQLITE_DEBUG
11407# define ExprSetVVAProperty(E,P)  (E)->flags|=(P)
11408#else
11409# define ExprSetVVAProperty(E,P)
11410#endif
11411
11412/*
11413** Macros to determine the number of bytes required by a normal Expr
11414** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
11415** and an Expr struct with the EP_TokenOnly flag set.
11416*/
11417#define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
11418#define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
11419#define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
11420
11421/*
11422** Flags passed to the sqlite3ExprDup() function. See the header comment
11423** above sqlite3ExprDup() for details.
11424*/
11425#define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
11426
11427/*
11428** A list of expressions.  Each expression may optionally have a
11429** name.  An expr/name combination can be used in several ways, such
11430** as the list of "expr AS ID" fields following a "SELECT" or in the
11431** list of "ID = expr" items in an UPDATE.  A list of expressions can
11432** also be used as the argument to a function, in which case the a.zName
11433** field is not used.
11434**
11435** By default the Expr.zSpan field holds a human-readable description of
11436** the expression that is used in the generation of error messages and
11437** column labels.  In this case, Expr.zSpan is typically the text of a
11438** column expression as it exists in a SELECT statement.  However, if
11439** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
11440** of the result column in the form: DATABASE.TABLE.COLUMN.  This later
11441** form is used for name resolution with nested FROM clauses.
11442*/
11443struct ExprList {
11444  int nExpr;             /* Number of expressions on the list */
11445  struct ExprList_item { /* For each expression in the list */
11446    Expr *pExpr;            /* The list of expressions */
11447    char *zName;            /* Token associated with this expression */
11448    char *zSpan;            /* Original text of the expression */
11449    u8 sortOrder;           /* 1 for DESC or 0 for ASC */
11450    unsigned done :1;       /* A flag to indicate when processing is finished */
11451    unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
11452    unsigned reusable :1;   /* Constant expression is reusable */
11453    union {
11454      struct {
11455        u16 iOrderByCol;      /* For ORDER BY, column number in result set */
11456        u16 iAlias;           /* Index into Parse.aAlias[] for zName */
11457      } x;
11458      int iConstExprReg;      /* Register in which Expr value is cached */
11459    } u;
11460  } *a;                  /* Alloc a power of two greater or equal to nExpr */
11461};
11462
11463/*
11464** An instance of this structure is used by the parser to record both
11465** the parse tree for an expression and the span of input text for an
11466** expression.
11467*/
11468struct ExprSpan {
11469  Expr *pExpr;          /* The expression parse tree */
11470  const char *zStart;   /* First character of input text */
11471  const char *zEnd;     /* One character past the end of input text */
11472};
11473
11474/*
11475** An instance of this structure can hold a simple list of identifiers,
11476** such as the list "a,b,c" in the following statements:
11477**
11478**      INSERT INTO t(a,b,c) VALUES ...;
11479**      CREATE INDEX idx ON t(a,b,c);
11480**      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
11481**
11482** The IdList.a.idx field is used when the IdList represents the list of
11483** column names after a table name in an INSERT statement.  In the statement
11484**
11485**     INSERT INTO t(a,b,c) ...
11486**
11487** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
11488*/
11489struct IdList {
11490  struct IdList_item {
11491    char *zName;      /* Name of the identifier */
11492    int idx;          /* Index in some Table.aCol[] of a column named zName */
11493  } *a;
11494  int nId;         /* Number of identifiers on the list */
11495};
11496
11497/*
11498** The bitmask datatype defined below is used for various optimizations.
11499**
11500** Changing this from a 64-bit to a 32-bit type limits the number of
11501** tables in a join to 32 instead of 64.  But it also reduces the size
11502** of the library by 738 bytes on ix86.
11503*/
11504typedef u64 Bitmask;
11505
11506/*
11507** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
11508*/
11509#define BMS  ((int)(sizeof(Bitmask)*8))
11510
11511/*
11512** A bit in a Bitmask
11513*/
11514#define MASKBIT(n)   (((Bitmask)1)<<(n))
11515#define MASKBIT32(n) (((unsigned int)1)<<(n))
11516
11517/*
11518** The following structure describes the FROM clause of a SELECT statement.
11519** Each table or subquery in the FROM clause is a separate element of
11520** the SrcList.a[] array.
11521**
11522** With the addition of multiple database support, the following structure
11523** can also be used to describe a particular table such as the table that
11524** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
11525** such a table must be a simple name: ID.  But in SQLite, the table can
11526** now be identified by a database name, a dot, then the table name: ID.ID.
11527**
11528** The jointype starts out showing the join type between the current table
11529** and the next table on the list.  The parser builds the list this way.
11530** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
11531** jointype expresses the join between the table and the previous table.
11532**
11533** In the colUsed field, the high-order bit (bit 63) is set if the table
11534** contains more than 63 columns and the 64-th or later column is used.
11535*/
11536struct SrcList {
11537  int nSrc;        /* Number of tables or subqueries in the FROM clause */
11538  u32 nAlloc;      /* Number of entries allocated in a[] below */
11539  struct SrcList_item {
11540    Schema *pSchema;  /* Schema to which this item is fixed */
11541    char *zDatabase;  /* Name of database holding this table */
11542    char *zName;      /* Name of the table */
11543    char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
11544    Table *pTab;      /* An SQL table corresponding to zName */
11545    Select *pSelect;  /* A SELECT statement used in place of a table name */
11546    int addrFillSub;  /* Address of subroutine to manifest a subquery */
11547    int regReturn;    /* Register holding return address of addrFillSub */
11548    int regResult;    /* Registers holding results of a co-routine */
11549    u8 jointype;      /* Type of join between this able and the previous */
11550    unsigned notIndexed :1;    /* True if there is a NOT INDEXED clause */
11551    unsigned isCorrelated :1;  /* True if sub-query is correlated */
11552    unsigned viaCoroutine :1;  /* Implemented as a co-routine */
11553    unsigned isRecursive :1;   /* True for recursive reference in WITH */
11554#ifndef SQLITE_OMIT_EXPLAIN
11555    u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
11556#endif
11557    int iCursor;      /* The VDBE cursor number used to access this table */
11558    Expr *pOn;        /* The ON clause of a join */
11559    IdList *pUsing;   /* The USING clause of a join */
11560    Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
11561    char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
11562    Index *pIndex;    /* Index structure corresponding to zIndex, if any */
11563  } a[1];             /* One entry for each identifier on the list */
11564};
11565
11566/*
11567** Permitted values of the SrcList.a.jointype field
11568*/
11569#define JT_INNER     0x0001    /* Any kind of inner or cross join */
11570#define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
11571#define JT_NATURAL   0x0004    /* True for a "natural" join */
11572#define JT_LEFT      0x0008    /* Left outer join */
11573#define JT_RIGHT     0x0010    /* Right outer join */
11574#define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
11575#define JT_ERROR     0x0040    /* unknown or unsupported join type */
11576
11577
11578/*
11579** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
11580** and the WhereInfo.wctrlFlags member.
11581*/
11582#define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
11583#define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
11584#define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
11585#define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
11586#define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
11587#define WHERE_OMIT_OPEN_CLOSE  0x0010 /* Table cursors are already open */
11588#define WHERE_FORCE_TABLE      0x0020 /* Do not use an index-only search */
11589#define WHERE_ONETABLE_ONLY    0x0040 /* Only code the 1st table in pTabList */
11590#define WHERE_AND_ONLY         0x0080 /* Don't use indices for OR terms */
11591#define WHERE_GROUPBY          0x0100 /* pOrderBy is really a GROUP BY */
11592#define WHERE_DISTINCTBY       0x0200 /* pOrderby is really a DISTINCT clause */
11593#define WHERE_WANT_DISTINCT    0x0400 /* All output needs to be distinct */
11594#define WHERE_SORTBYGROUP      0x0800 /* Support sqlite3WhereIsSorted() */
11595
11596/* Allowed return values from sqlite3WhereIsDistinct()
11597*/
11598#define WHERE_DISTINCT_NOOP      0  /* DISTINCT keyword not used */
11599#define WHERE_DISTINCT_UNIQUE    1  /* No duplicates */
11600#define WHERE_DISTINCT_ORDERED   2  /* All duplicates are adjacent */
11601#define WHERE_DISTINCT_UNORDERED 3  /* Duplicates are scattered */
11602
11603/*
11604** A NameContext defines a context in which to resolve table and column
11605** names.  The context consists of a list of tables (the pSrcList) field and
11606** a list of named expression (pEList).  The named expression list may
11607** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
11608** to the table being operated on by INSERT, UPDATE, or DELETE.  The
11609** pEList corresponds to the result set of a SELECT and is NULL for
11610** other statements.
11611**
11612** NameContexts can be nested.  When resolving names, the inner-most
11613** context is searched first.  If no match is found, the next outer
11614** context is checked.  If there is still no match, the next context
11615** is checked.  This process continues until either a match is found
11616** or all contexts are check.  When a match is found, the nRef member of
11617** the context containing the match is incremented.
11618**
11619** Each subquery gets a new NameContext.  The pNext field points to the
11620** NameContext in the parent query.  Thus the process of scanning the
11621** NameContext list corresponds to searching through successively outer
11622** subqueries looking for a match.
11623*/
11624struct NameContext {
11625  Parse *pParse;       /* The parser */
11626  SrcList *pSrcList;   /* One or more tables used to resolve names */
11627  ExprList *pEList;    /* Optional list of result-set columns */
11628  AggInfo *pAggInfo;   /* Information about aggregates at this level */
11629  NameContext *pNext;  /* Next outer name context.  NULL for outermost */
11630  int nRef;            /* Number of names resolved by this context */
11631  int nErr;            /* Number of errors encountered while resolving names */
11632  u8 ncFlags;          /* Zero or more NC_* flags defined below */
11633};
11634
11635/*
11636** Allowed values for the NameContext, ncFlags field.
11637*/
11638#define NC_AllowAgg  0x01    /* Aggregate functions are allowed here */
11639#define NC_HasAgg    0x02    /* One or more aggregate functions seen */
11640#define NC_IsCheck   0x04    /* True if resolving names in a CHECK constraint */
11641#define NC_InAggFunc 0x08    /* True if analyzing arguments to an agg func */
11642#define NC_PartIdx   0x10    /* True if resolving a partial index WHERE */
11643
11644/*
11645** An instance of the following structure contains all information
11646** needed to generate code for a single SELECT statement.
11647**
11648** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
11649** If there is a LIMIT clause, the parser sets nLimit to the value of the
11650** limit and nOffset to the value of the offset (or 0 if there is not
11651** offset).  But later on, nLimit and nOffset become the memory locations
11652** in the VDBE that record the limit and offset counters.
11653**
11654** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
11655** These addresses must be stored so that we can go back and fill in
11656** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
11657** the number of columns in P2 can be computed at the same time
11658** as the OP_OpenEphm instruction is coded because not
11659** enough information about the compound query is known at that point.
11660** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
11661** for the result set.  The KeyInfo for addrOpenEphm[2] contains collating
11662** sequences for the ORDER BY clause.
11663*/
11664struct Select {
11665  ExprList *pEList;      /* The fields of the result */
11666  u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
11667  u16 selFlags;          /* Various SF_* values */
11668  int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
11669  int addrOpenEphm[2];   /* OP_OpenEphem opcodes related to this select */
11670  u64 nSelectRow;        /* Estimated number of result rows */
11671  SrcList *pSrc;         /* The FROM clause */
11672  Expr *pWhere;          /* The WHERE clause */
11673  ExprList *pGroupBy;    /* The GROUP BY clause */
11674  Expr *pHaving;         /* The HAVING clause */
11675  ExprList *pOrderBy;    /* The ORDER BY clause */
11676  Select *pPrior;        /* Prior select in a compound select statement */
11677  Select *pNext;         /* Next select to the left in a compound */
11678  Expr *pLimit;          /* LIMIT expression. NULL means not used. */
11679  Expr *pOffset;         /* OFFSET expression. NULL means not used. */
11680  With *pWith;           /* WITH clause attached to this select. Or NULL. */
11681};
11682
11683/*
11684** Allowed values for Select.selFlags.  The "SF" prefix stands for
11685** "Select Flag".
11686*/
11687#define SF_Distinct        0x0001  /* Output should be DISTINCT */
11688#define SF_Resolved        0x0002  /* Identifiers have been resolved */
11689#define SF_Aggregate       0x0004  /* Contains aggregate functions */
11690#define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
11691#define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
11692#define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
11693                    /*     0x0040  NOT USED */
11694#define SF_Values          0x0080  /* Synthesized from VALUES clause */
11695                    /*     0x0100  NOT USED */
11696#define SF_NestedFrom      0x0200  /* Part of a parenthesized FROM clause */
11697#define SF_MaybeConvert    0x0400  /* Need convertCompoundSelectToSubquery() */
11698#define SF_Recursive       0x0800  /* The recursive part of a recursive CTE */
11699#define SF_Compound        0x1000  /* Part of a compound query */
11700
11701
11702/*
11703** The results of a SELECT can be distributed in several ways, as defined
11704** by one of the following macros.  The "SRT" prefix means "SELECT Result
11705** Type".
11706**
11707**     SRT_Union       Store results as a key in a temporary index
11708**                     identified by pDest->iSDParm.
11709**
11710**     SRT_Except      Remove results from the temporary index pDest->iSDParm.
11711**
11712**     SRT_Exists      Store a 1 in memory cell pDest->iSDParm if the result
11713**                     set is not empty.
11714**
11715**     SRT_Discard     Throw the results away.  This is used by SELECT
11716**                     statements within triggers whose only purpose is
11717**                     the side-effects of functions.
11718**
11719** All of the above are free to ignore their ORDER BY clause. Those that
11720** follow must honor the ORDER BY clause.
11721**
11722**     SRT_Output      Generate a row of output (using the OP_ResultRow
11723**                     opcode) for each row in the result set.
11724**
11725**     SRT_Mem         Only valid if the result is a single column.
11726**                     Store the first column of the first result row
11727**                     in register pDest->iSDParm then abandon the rest
11728**                     of the query.  This destination implies "LIMIT 1".
11729**
11730**     SRT_Set         The result must be a single column.  Store each
11731**                     row of result as the key in table pDest->iSDParm.
11732**                     Apply the affinity pDest->affSdst before storing
11733**                     results.  Used to implement "IN (SELECT ...)".
11734**
11735**     SRT_EphemTab    Create an temporary table pDest->iSDParm and store
11736**                     the result there. The cursor is left open after
11737**                     returning.  This is like SRT_Table except that
11738**                     this destination uses OP_OpenEphemeral to create
11739**                     the table first.
11740**
11741**     SRT_Coroutine   Generate a co-routine that returns a new row of
11742**                     results each time it is invoked.  The entry point
11743**                     of the co-routine is stored in register pDest->iSDParm
11744**                     and the result row is stored in pDest->nDest registers
11745**                     starting with pDest->iSdst.
11746**
11747**     SRT_Table       Store results in temporary table pDest->iSDParm.
11748**     SRT_Fifo        This is like SRT_EphemTab except that the table
11749**                     is assumed to already be open.  SRT_Fifo has
11750**                     the additional property of being able to ignore
11751**                     the ORDER BY clause.
11752**
11753**     SRT_DistFifo    Store results in a temporary table pDest->iSDParm.
11754**                     But also use temporary table pDest->iSDParm+1 as
11755**                     a record of all prior results and ignore any duplicate
11756**                     rows.  Name means:  "Distinct Fifo".
11757**
11758**     SRT_Queue       Store results in priority queue pDest->iSDParm (really
11759**                     an index).  Append a sequence number so that all entries
11760**                     are distinct.
11761**
11762**     SRT_DistQueue   Store results in priority queue pDest->iSDParm only if
11763**                     the same record has never been stored before.  The
11764**                     index at pDest->iSDParm+1 hold all prior stores.
11765*/
11766#define SRT_Union        1  /* Store result as keys in an index */
11767#define SRT_Except       2  /* Remove result from a UNION index */
11768#define SRT_Exists       3  /* Store 1 if the result is not empty */
11769#define SRT_Discard      4  /* Do not save the results anywhere */
11770#define SRT_Fifo         5  /* Store result as data with an automatic rowid */
11771#define SRT_DistFifo     6  /* Like SRT_Fifo, but unique results only */
11772#define SRT_Queue        7  /* Store result in an queue */
11773#define SRT_DistQueue    8  /* Like SRT_Queue, but unique results only */
11774
11775/* The ORDER BY clause is ignored for all of the above */
11776#define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
11777
11778#define SRT_Output       9  /* Output each row of result */
11779#define SRT_Mem         10  /* Store result in a memory cell */
11780#define SRT_Set         11  /* Store results as keys in an index */
11781#define SRT_EphemTab    12  /* Create transient tab and store like SRT_Table */
11782#define SRT_Coroutine   13  /* Generate a single row of result */
11783#define SRT_Table       14  /* Store result as data with an automatic rowid */
11784
11785/*
11786** An instance of this object describes where to put of the results of
11787** a SELECT statement.
11788*/
11789struct SelectDest {
11790  u8 eDest;            /* How to dispose of the results.  On of SRT_* above. */
11791  char affSdst;        /* Affinity used when eDest==SRT_Set */
11792  int iSDParm;         /* A parameter used by the eDest disposal method */
11793  int iSdst;           /* Base register where results are written */
11794  int nSdst;           /* Number of registers allocated */
11795  ExprList *pOrderBy;  /* Key columns for SRT_Queue and SRT_DistQueue */
11796};
11797
11798/*
11799** During code generation of statements that do inserts into AUTOINCREMENT
11800** tables, the following information is attached to the Table.u.autoInc.p
11801** pointer of each autoincrement table to record some side information that
11802** the code generator needs.  We have to keep per-table autoincrement
11803** information in case inserts are down within triggers.  Triggers do not
11804** normally coordinate their activities, but we do need to coordinate the
11805** loading and saving of autoincrement information.
11806*/
11807struct AutoincInfo {
11808  AutoincInfo *pNext;   /* Next info block in a list of them all */
11809  Table *pTab;          /* Table this info block refers to */
11810  int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
11811  int regCtr;           /* Memory register holding the rowid counter */
11812};
11813
11814/*
11815** Size of the column cache
11816*/
11817#ifndef SQLITE_N_COLCACHE
11818# define SQLITE_N_COLCACHE 10
11819#endif
11820
11821/*
11822** At least one instance of the following structure is created for each
11823** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
11824** statement. All such objects are stored in the linked list headed at
11825** Parse.pTriggerPrg and deleted once statement compilation has been
11826** completed.
11827**
11828** A Vdbe sub-program that implements the body and WHEN clause of trigger
11829** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
11830** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
11831** The Parse.pTriggerPrg list never contains two entries with the same
11832** values for both pTrigger and orconf.
11833**
11834** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
11835** accessed (or set to 0 for triggers fired as a result of INSERT
11836** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
11837** a mask of new.* columns used by the program.
11838*/
11839struct TriggerPrg {
11840  Trigger *pTrigger;      /* Trigger this program was coded from */
11841  TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
11842  SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
11843  int orconf;             /* Default ON CONFLICT policy */
11844  u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
11845};
11846
11847/*
11848** The yDbMask datatype for the bitmask of all attached databases.
11849*/
11850#if SQLITE_MAX_ATTACHED>30
11851  typedef sqlite3_uint64 yDbMask;
11852#else
11853  typedef unsigned int yDbMask;
11854#endif
11855
11856/*
11857** An SQL parser context.  A copy of this structure is passed through
11858** the parser and down into all the parser action routine in order to
11859** carry around information that is global to the entire parse.
11860**
11861** The structure is divided into two parts.  When the parser and code
11862** generate call themselves recursively, the first part of the structure
11863** is constant but the second part is reset at the beginning and end of
11864** each recursion.
11865**
11866** The nTableLock and aTableLock variables are only used if the shared-cache
11867** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
11868** used to store the set of table-locks required by the statement being
11869** compiled. Function sqlite3TableLock() is used to add entries to the
11870** list.
11871*/
11872struct Parse {
11873  sqlite3 *db;         /* The main database structure */
11874  char *zErrMsg;       /* An error message */
11875  Vdbe *pVdbe;         /* An engine for executing database bytecode */
11876  int rc;              /* Return code from execution */
11877  u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
11878  u8 checkSchema;      /* Causes schema cookie check after an error */
11879  u8 nested;           /* Number of nested calls to the parser/code generator */
11880  u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
11881  u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
11882  u8 mayAbort;         /* True if statement may throw an ABORT exception */
11883  u8 hasCompound;      /* Need to invoke convertCompoundSelectToSubquery() */
11884  u8 okConstFactor;    /* OK to factor out constants */
11885  int aTempReg[8];     /* Holding area for temporary registers */
11886  int nRangeReg;       /* Size of the temporary register block */
11887  int iRangeReg;       /* First register in temporary register block */
11888  int nErr;            /* Number of errors seen */
11889  int nTab;            /* Number of previously allocated VDBE cursors */
11890  int nMem;            /* Number of memory cells used so far */
11891  int nSet;            /* Number of sets used so far */
11892  int nOnce;           /* Number of OP_Once instructions so far */
11893  int nOpAlloc;        /* Number of slots allocated for Vdbe.aOp[] */
11894  int iFixedOp;        /* Never back out opcodes iFixedOp-1 or earlier */
11895  int ckBase;          /* Base register of data during check constraints */
11896  int iPartIdxTab;     /* Table corresponding to a partial index */
11897  int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
11898  int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
11899  int nLabel;          /* Number of labels used */
11900  int *aLabel;         /* Space to hold the labels */
11901  struct yColCache {
11902    int iTable;           /* Table cursor number */
11903    i16 iColumn;          /* Table column number */
11904    u8 tempReg;           /* iReg is a temp register that needs to be freed */
11905    int iLevel;           /* Nesting level */
11906    int iReg;             /* Reg with value of this column. 0 means none. */
11907    int lru;              /* Least recently used entry has the smallest value */
11908  } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
11909  ExprList *pConstExpr;/* Constant expressions */
11910  Token constraintName;/* Name of the constraint currently being parsed */
11911  yDbMask writeMask;   /* Start a write transaction on these databases */
11912  yDbMask cookieMask;  /* Bitmask of schema verified databases */
11913  int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
11914  int regRowid;        /* Register holding rowid of CREATE TABLE entry */
11915  int regRoot;         /* Register holding root page number for new objects */
11916  int nMaxArg;         /* Max args passed to user function by sub-program */
11917#ifndef SQLITE_OMIT_SHARED_CACHE
11918  int nTableLock;        /* Number of locks in aTableLock */
11919  TableLock *aTableLock; /* Required table locks for shared-cache mode */
11920#endif
11921  AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
11922
11923  /* Information used while coding trigger programs. */
11924  Parse *pToplevel;    /* Parse structure for main program (or NULL) */
11925  Table *pTriggerTab;  /* Table triggers are being coded for */
11926  int addrCrTab;       /* Address of OP_CreateTable opcode on CREATE TABLE */
11927  int addrSkipPK;      /* Address of instruction to skip PRIMARY KEY index */
11928  u32 nQueryLoop;      /* Est number of iterations of a query (10*log2(N)) */
11929  u32 oldmask;         /* Mask of old.* columns referenced */
11930  u32 newmask;         /* Mask of new.* columns referenced */
11931  u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
11932  u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
11933  u8 disableTriggers;  /* True to disable triggers */
11934
11935  /************************************************************************
11936  ** Above is constant between recursions.  Below is reset before and after
11937  ** each recursion.  The boundary between these two regions is determined
11938  ** using offsetof(Parse,nVar) so the nVar field must be the first field
11939  ** in the recursive region.
11940  ************************************************************************/
11941
11942  int nVar;                 /* Number of '?' variables seen in the SQL so far */
11943  int nzVar;                /* Number of available slots in azVar[] */
11944  u8 iPkSortOrder;          /* ASC or DESC for INTEGER PRIMARY KEY */
11945  u8 bFreeWith;             /* True if pWith should be freed with parser */
11946  u8 explain;               /* True if the EXPLAIN flag is found on the query */
11947#ifndef SQLITE_OMIT_VIRTUALTABLE
11948  u8 declareVtab;           /* True if inside sqlite3_declare_vtab() */
11949  int nVtabLock;            /* Number of virtual tables to lock */
11950#endif
11951  int nAlias;               /* Number of aliased result set columns */
11952  int nHeight;              /* Expression tree height of current sub-select */
11953#ifndef SQLITE_OMIT_EXPLAIN
11954  int iSelectId;            /* ID of current select for EXPLAIN output */
11955  int iNextSelectId;        /* Next available select ID for EXPLAIN output */
11956#endif
11957  char **azVar;             /* Pointers to names of parameters */
11958  Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */
11959  const char *zTail;        /* All SQL text past the last semicolon parsed */
11960  Table *pNewTable;         /* A table being constructed by CREATE TABLE */
11961  Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
11962  const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
11963  Token sNameToken;         /* Token with unqualified schema object name */
11964  Token sLastToken;         /* The last token parsed */
11965#ifndef SQLITE_OMIT_VIRTUALTABLE
11966  Token sArg;               /* Complete text of a module argument */
11967  Table **apVtabLock;       /* Pointer to virtual tables needing locking */
11968#endif
11969  Table *pZombieTab;        /* List of Table objects to delete after code gen */
11970  TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
11971  With *pWith;              /* Current WITH clause, or NULL */
11972};
11973
11974/*
11975** Return true if currently inside an sqlite3_declare_vtab() call.
11976*/
11977#ifdef SQLITE_OMIT_VIRTUALTABLE
11978  #define IN_DECLARE_VTAB 0
11979#else
11980  #define IN_DECLARE_VTAB (pParse->declareVtab)
11981#endif
11982
11983/*
11984** An instance of the following structure can be declared on a stack and used
11985** to save the Parse.zAuthContext value so that it can be restored later.
11986*/
11987struct AuthContext {
11988  const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
11989  Parse *pParse;              /* The Parse structure */
11990};
11991
11992/*
11993** Bitfield flags for P5 value in various opcodes.
11994*/
11995#define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
11996#define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
11997#define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
11998#define OPFLAG_APPEND        0x08    /* This is likely to be an append */
11999#define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
12000#define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
12001#define OPFLAG_LENGTHARG     0x40    /* OP_Column only used for length() */
12002#define OPFLAG_TYPEOFARG     0x80    /* OP_Column only used for typeof() */
12003#define OPFLAG_BULKCSR       0x01    /* OP_Open** used to open bulk cursor */
12004#define OPFLAG_P2ISREG       0x02    /* P2 to OP_Open** is a register number */
12005#define OPFLAG_PERMUTE       0x01    /* OP_Compare: use the permutation */
12006
12007/*
12008 * Each trigger present in the database schema is stored as an instance of
12009 * struct Trigger.
12010 *
12011 * Pointers to instances of struct Trigger are stored in two ways.
12012 * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
12013 *    database). This allows Trigger structures to be retrieved by name.
12014 * 2. All triggers associated with a single table form a linked list, using the
12015 *    pNext member of struct Trigger. A pointer to the first element of the
12016 *    linked list is stored as the "pTrigger" member of the associated
12017 *    struct Table.
12018 *
12019 * The "step_list" member points to the first element of a linked list
12020 * containing the SQL statements specified as the trigger program.
12021 */
12022struct Trigger {
12023  char *zName;            /* The name of the trigger                        */
12024  char *table;            /* The table or view to which the trigger applies */
12025  u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
12026  u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
12027  Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
12028  IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
12029                             the <column-list> is stored here */
12030  Schema *pSchema;        /* Schema containing the trigger */
12031  Schema *pTabSchema;     /* Schema containing the table */
12032  TriggerStep *step_list; /* Link list of trigger program steps             */
12033  Trigger *pNext;         /* Next trigger associated with the table */
12034};
12035
12036/*
12037** A trigger is either a BEFORE or an AFTER trigger.  The following constants
12038** determine which.
12039**
12040** If there are multiple triggers, you might of some BEFORE and some AFTER.
12041** In that cases, the constants below can be ORed together.
12042*/
12043#define TRIGGER_BEFORE  1
12044#define TRIGGER_AFTER   2
12045
12046/*
12047 * An instance of struct TriggerStep is used to store a single SQL statement
12048 * that is a part of a trigger-program.
12049 *
12050 * Instances of struct TriggerStep are stored in a singly linked list (linked
12051 * using the "pNext" member) referenced by the "step_list" member of the
12052 * associated struct Trigger instance. The first element of the linked list is
12053 * the first step of the trigger-program.
12054 *
12055 * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
12056 * "SELECT" statement. The meanings of the other members is determined by the
12057 * value of "op" as follows:
12058 *
12059 * (op == TK_INSERT)
12060 * orconf    -> stores the ON CONFLICT algorithm
12061 * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
12062 *              this stores a pointer to the SELECT statement. Otherwise NULL.
12063 * target    -> A token holding the quoted name of the table to insert into.
12064 * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
12065 *              this stores values to be inserted. Otherwise NULL.
12066 * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
12067 *              statement, then this stores the column-names to be
12068 *              inserted into.
12069 *
12070 * (op == TK_DELETE)
12071 * target    -> A token holding the quoted name of the table to delete from.
12072 * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
12073 *              Otherwise NULL.
12074 *
12075 * (op == TK_UPDATE)
12076 * target    -> A token holding the quoted name of the table to update rows of.
12077 * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
12078 *              Otherwise NULL.
12079 * pExprList -> A list of the columns to update and the expressions to update
12080 *              them to. See sqlite3Update() documentation of "pChanges"
12081 *              argument.
12082 *
12083 */
12084struct TriggerStep {
12085  u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
12086  u8 orconf;           /* OE_Rollback etc. */
12087  Trigger *pTrig;      /* The trigger that this step is a part of */
12088  Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
12089  Token target;        /* Target table for DELETE, UPDATE, INSERT */
12090  Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
12091  ExprList *pExprList; /* SET clause for UPDATE. */
12092  IdList *pIdList;     /* Column names for INSERT */
12093  TriggerStep *pNext;  /* Next in the link-list */
12094  TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
12095};
12096
12097/*
12098** The following structure contains information used by the sqliteFix...
12099** routines as they walk the parse tree to make database references
12100** explicit.
12101*/
12102typedef struct DbFixer DbFixer;
12103struct DbFixer {
12104  Parse *pParse;      /* The parsing context.  Error messages written here */
12105  Schema *pSchema;    /* Fix items to this schema */
12106  int bVarOnly;       /* Check for variable references only */
12107  const char *zDb;    /* Make sure all objects are contained in this database */
12108  const char *zType;  /* Type of the container - used for error messages */
12109  const Token *pName; /* Name of the container - used for error messages */
12110};
12111
12112/*
12113** An objected used to accumulate the text of a string where we
12114** do not necessarily know how big the string will be in the end.
12115*/
12116struct StrAccum {
12117  sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
12118  char *zBase;         /* A base allocation.  Not from malloc. */
12119  char *zText;         /* The string collected so far */
12120  int  nChar;          /* Length of the string so far */
12121  int  nAlloc;         /* Amount of space allocated in zText */
12122  int  mxAlloc;        /* Maximum allowed string length */
12123  u8   useMalloc;      /* 0: none,  1: sqlite3DbMalloc,  2: sqlite3_malloc */
12124  u8   accError;       /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
12125};
12126#define STRACCUM_NOMEM   1
12127#define STRACCUM_TOOBIG  2
12128
12129/*
12130** A pointer to this structure is used to communicate information
12131** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
12132*/
12133typedef struct {
12134  sqlite3 *db;        /* The database being initialized */
12135  char **pzErrMsg;    /* Error message stored here */
12136  int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
12137  int rc;             /* Result code stored here */
12138} InitData;
12139
12140/*
12141** Structure containing global configuration data for the SQLite library.
12142**
12143** This structure also contains some state information.
12144*/
12145struct Sqlite3Config {
12146  int bMemstat;                     /* True to enable memory status */
12147  int bCoreMutex;                   /* True to enable core mutexing */
12148  int bFullMutex;                   /* True to enable full mutexing */
12149  int bOpenUri;                     /* True to interpret filenames as URIs */
12150  int bUseCis;                      /* Use covering indices for full-scans */
12151  int mxStrlen;                     /* Maximum string length */
12152  int neverCorrupt;                 /* Database is always well-formed */
12153  int szLookaside;                  /* Default lookaside buffer size */
12154  int nLookaside;                   /* Default lookaside buffer count */
12155  sqlite3_mem_methods m;            /* Low-level memory allocation interface */
12156  sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
12157  sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */
12158  void *pHeap;                      /* Heap storage space */
12159  int nHeap;                        /* Size of pHeap[] */
12160  int mnReq, mxReq;                 /* Min and max heap requests sizes */
12161  sqlite3_int64 szMmap;             /* mmap() space per open file */
12162  sqlite3_int64 mxMmap;             /* Maximum value for szMmap */
12163  void *pScratch;                   /* Scratch memory */
12164  int szScratch;                    /* Size of each scratch buffer */
12165  int nScratch;                     /* Number of scratch buffers */
12166  void *pPage;                      /* Page cache memory */
12167  int szPage;                       /* Size of each page in pPage[] */
12168  int nPage;                        /* Number of pages in pPage[] */
12169  int mxParserStack;                /* maximum depth of the parser stack */
12170  int sharedCacheEnabled;           /* true if shared-cache mode enabled */
12171  /* The above might be initialized to non-zero.  The following need to always
12172  ** initially be zero, however. */
12173  int isInit;                       /* True after initialization has finished */
12174  int inProgress;                   /* True while initialization in progress */
12175  int isMutexInit;                  /* True after mutexes are initialized */
12176  int isMallocInit;                 /* True after malloc is initialized */
12177  int isPCacheInit;                 /* True after malloc is initialized */
12178  int nRefInitMutex;                /* Number of users of pInitMutex */
12179  sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
12180  void (*xLog)(void*,int,const char*); /* Function for logging */
12181  void *pLogArg;                       /* First argument to xLog() */
12182#ifdef SQLITE_ENABLE_SQLLOG
12183  void(*xSqllog)(void*,sqlite3*,const char*, int);
12184  void *pSqllogArg;
12185#endif
12186#ifdef SQLITE_VDBE_COVERAGE
12187  /* The following callback (if not NULL) is invoked on every VDBE branch
12188  ** operation.  Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
12189  */
12190  void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx);  /* Callback */
12191  void *pVdbeBranchArg;                                     /* 1st argument */
12192#endif
12193#ifndef SQLITE_OMIT_BUILTIN_TEST
12194  int (*xTestCallback)(int);        /* Invoked by sqlite3FaultSim() */
12195#endif
12196  int bLocaltimeFault;              /* True to fail localtime() calls */
12197};
12198
12199/*
12200** This macro is used inside of assert() statements to indicate that
12201** the assert is only valid on a well-formed database.  Instead of:
12202**
12203**     assert( X );
12204**
12205** One writes:
12206**
12207**     assert( X || CORRUPT_DB );
12208**
12209** CORRUPT_DB is true during normal operation.  CORRUPT_DB does not indicate
12210** that the database is definitely corrupt, only that it might be corrupt.
12211** For most test cases, CORRUPT_DB is set to false using a special
12212** sqlite3_test_control().  This enables assert() statements to prove
12213** things that are always true for well-formed databases.
12214*/
12215#define CORRUPT_DB  (sqlite3Config.neverCorrupt==0)
12216
12217/*
12218** Context pointer passed down through the tree-walk.
12219*/
12220struct Walker {
12221  int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
12222  int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
12223  void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
12224  Parse *pParse;                            /* Parser context.  */
12225  int walkerDepth;                          /* Number of subqueries */
12226  union {                                   /* Extra data for callback */
12227    NameContext *pNC;                          /* Naming context */
12228    int i;                                     /* Integer value */
12229    SrcList *pSrcList;                         /* FROM clause */
12230    struct SrcCount *pSrcCount;                /* Counting column references */
12231  } u;
12232};
12233
12234/* Forward declarations */
12235SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
12236SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
12237SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
12238SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
12239SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
12240
12241/*
12242** Return code from the parse-tree walking primitives and their
12243** callbacks.
12244*/
12245#define WRC_Continue    0   /* Continue down into children */
12246#define WRC_Prune       1   /* Omit children but continue walking siblings */
12247#define WRC_Abort       2   /* Abandon the tree walk */
12248
12249/*
12250** An instance of this structure represents a set of one or more CTEs
12251** (common table expressions) created by a single WITH clause.
12252*/
12253struct With {
12254  int nCte;                       /* Number of CTEs in the WITH clause */
12255  With *pOuter;                   /* Containing WITH clause, or NULL */
12256  struct Cte {                    /* For each CTE in the WITH clause.... */
12257    char *zName;                    /* Name of this CTE */
12258    ExprList *pCols;                /* List of explicit column names, or NULL */
12259    Select *pSelect;                /* The definition of this CTE */
12260    const char *zErr;               /* Error message for circular references */
12261  } a[1];
12262};
12263
12264/*
12265** Assuming zIn points to the first byte of a UTF-8 character,
12266** advance zIn to point to the first byte of the next UTF-8 character.
12267*/
12268#define SQLITE_SKIP_UTF8(zIn) {                        \
12269  if( (*(zIn++))>=0xc0 ){                              \
12270    while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
12271  }                                                    \
12272}
12273
12274/*
12275** The SQLITE_*_BKPT macros are substitutes for the error codes with
12276** the same name but without the _BKPT suffix.  These macros invoke
12277** routines that report the line-number on which the error originated
12278** using sqlite3_log().  The routines also provide a convenient place
12279** to set a debugger breakpoint.
12280*/
12281SQLITE_PRIVATE int sqlite3CorruptError(int);
12282SQLITE_PRIVATE int sqlite3MisuseError(int);
12283SQLITE_PRIVATE int sqlite3CantopenError(int);
12284#define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
12285#define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
12286#define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
12287
12288
12289/*
12290** FTS4 is really an extension for FTS3.  It is enabled using the
12291** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
12292** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
12293*/
12294#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
12295# define SQLITE_ENABLE_FTS3
12296#endif
12297
12298/*
12299** The ctype.h header is needed for non-ASCII systems.  It is also
12300** needed by FTS3 when FTS3 is included in the amalgamation.
12301*/
12302#if !defined(SQLITE_ASCII) || \
12303    (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
12304# include <ctype.h>
12305#endif
12306
12307/*
12308** The following macros mimic the standard library functions toupper(),
12309** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
12310** sqlite versions only work for ASCII characters, regardless of locale.
12311*/
12312#ifdef SQLITE_ASCII
12313# define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
12314# define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
12315# define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
12316# define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
12317# define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
12318# define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
12319# define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
12320#else
12321# define sqlite3Toupper(x)   toupper((unsigned char)(x))
12322# define sqlite3Isspace(x)   isspace((unsigned char)(x))
12323# define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
12324# define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
12325# define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
12326# define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
12327# define sqlite3Tolower(x)   tolower((unsigned char)(x))
12328#endif
12329
12330/*
12331** Internal function prototypes
12332*/
12333#define sqlite3StrICmp sqlite3_stricmp
12334SQLITE_PRIVATE int sqlite3Strlen30(const char*);
12335#define sqlite3StrNICmp sqlite3_strnicmp
12336
12337SQLITE_PRIVATE int sqlite3MallocInit(void);
12338SQLITE_PRIVATE void sqlite3MallocEnd(void);
12339SQLITE_PRIVATE void *sqlite3Malloc(int);
12340SQLITE_PRIVATE void *sqlite3MallocZero(int);
12341SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
12342SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
12343SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
12344SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
12345SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
12346SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
12347SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
12348SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
12349SQLITE_PRIVATE int sqlite3MallocSize(void*);
12350SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
12351SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
12352SQLITE_PRIVATE void sqlite3ScratchFree(void*);
12353SQLITE_PRIVATE void *sqlite3PageMalloc(int);
12354SQLITE_PRIVATE void sqlite3PageFree(void*);
12355SQLITE_PRIVATE void sqlite3MemSetDefault(void);
12356SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
12357SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
12358
12359/*
12360** On systems with ample stack space and that support alloca(), make
12361** use of alloca() to obtain space for large automatic objects.  By default,
12362** obtain space from malloc().
12363**
12364** The alloca() routine never returns NULL.  This will cause code paths
12365** that deal with sqlite3StackAlloc() failures to be unreachable.
12366*/
12367#ifdef SQLITE_USE_ALLOCA
12368# define sqlite3StackAllocRaw(D,N)   alloca(N)
12369# define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
12370# define sqlite3StackFree(D,P)
12371#else
12372# define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
12373# define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
12374# define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
12375#endif
12376
12377#ifdef SQLITE_ENABLE_MEMSYS3
12378SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
12379#endif
12380#ifdef SQLITE_ENABLE_MEMSYS5
12381SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
12382#endif
12383
12384
12385#ifndef SQLITE_MUTEX_OMIT
12386SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
12387SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
12388SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
12389SQLITE_PRIVATE   int sqlite3MutexInit(void);
12390SQLITE_PRIVATE   int sqlite3MutexEnd(void);
12391#endif
12392
12393SQLITE_PRIVATE int sqlite3StatusValue(int);
12394SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
12395SQLITE_PRIVATE void sqlite3StatusSet(int, int);
12396
12397#ifndef SQLITE_OMIT_FLOATING_POINT
12398SQLITE_PRIVATE   int sqlite3IsNaN(double);
12399#else
12400# define sqlite3IsNaN(X)  0
12401#endif
12402
12403/*
12404** An instance of the following structure holds information about SQL
12405** functions arguments that are the parameters to the printf() function.
12406*/
12407struct PrintfArguments {
12408  int nArg;                /* Total number of arguments */
12409  int nUsed;               /* Number of arguments used so far */
12410  sqlite3_value **apArg;   /* The argument values */
12411};
12412
12413#define SQLITE_PRINTF_INTERNAL 0x01
12414#define SQLITE_PRINTF_SQLFUNC  0x02
12415SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, u32, const char*, va_list);
12416SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, u32, const char*, ...);
12417SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
12418SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
12419SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
12420#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
12421SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
12422#endif
12423#if defined(SQLITE_TEST)
12424SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
12425#endif
12426
12427/* Output formatting for SQLITE_TESTCTRL_EXPLAIN */
12428#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
12429SQLITE_PRIVATE   void sqlite3ExplainBegin(Vdbe*);
12430SQLITE_PRIVATE   void sqlite3ExplainPrintf(Vdbe*, const char*, ...);
12431SQLITE_PRIVATE   void sqlite3ExplainNL(Vdbe*);
12432SQLITE_PRIVATE   void sqlite3ExplainPush(Vdbe*);
12433SQLITE_PRIVATE   void sqlite3ExplainPop(Vdbe*);
12434SQLITE_PRIVATE   void sqlite3ExplainFinish(Vdbe*);
12435SQLITE_PRIVATE   void sqlite3ExplainSelect(Vdbe*, Select*);
12436SQLITE_PRIVATE   void sqlite3ExplainExpr(Vdbe*, Expr*);
12437SQLITE_PRIVATE   void sqlite3ExplainExprList(Vdbe*, ExprList*);
12438SQLITE_PRIVATE   const char *sqlite3VdbeExplanation(Vdbe*);
12439#else
12440# define sqlite3ExplainBegin(X)
12441# define sqlite3ExplainSelect(A,B)
12442# define sqlite3ExplainExpr(A,B)
12443# define sqlite3ExplainExprList(A,B)
12444# define sqlite3ExplainFinish(X)
12445# define sqlite3VdbeExplanation(X) 0
12446#endif
12447
12448
12449SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
12450SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
12451SQLITE_PRIVATE int sqlite3Dequote(char*);
12452SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
12453SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
12454SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
12455SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
12456SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
12457SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
12458SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
12459SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
12460SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
12461SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
12462SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
12463SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
12464SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
12465SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
12466SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
12467SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
12468SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
12469SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
12470SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
12471SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
12472SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
12473SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
12474SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
12475SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
12476SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
12477SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
12478SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
12479SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
12480SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
12481SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
12482SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
12483SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
12484SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
12485SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
12486SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
12487SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
12488SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
12489SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
12490SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
12491SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
12492SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
12493SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
12494                    sqlite3_vfs**,char**,char **);
12495SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
12496SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
12497
12498#ifdef SQLITE_OMIT_BUILTIN_TEST
12499# define sqlite3FaultSim(X) SQLITE_OK
12500#else
12501SQLITE_PRIVATE   int sqlite3FaultSim(int);
12502#endif
12503
12504SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
12505SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
12506SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
12507SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
12508SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
12509SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
12510SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
12511
12512SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
12513SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
12514SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
12515SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
12516SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
12517
12518SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
12519
12520#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
12521SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
12522#else
12523# define sqlite3ViewGetColumnNames(A,B) 0
12524#endif
12525
12526SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
12527SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
12528SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
12529#ifndef SQLITE_OMIT_AUTOINCREMENT
12530SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
12531SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
12532#else
12533# define sqlite3AutoincrementBegin(X)
12534# define sqlite3AutoincrementEnd(X)
12535#endif
12536SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
12537SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
12538SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
12539SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
12540SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
12541SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
12542SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
12543                                      Token*, Select*, Expr*, IdList*);
12544SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
12545SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
12546SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
12547SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
12548SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
12549SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
12550SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
12551SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
12552                          Expr*, int, int);
12553SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
12554SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
12555SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
12556                         Expr*,ExprList*,u16,Expr*,Expr*);
12557SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
12558SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
12559SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
12560SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
12561#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
12562SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
12563#endif
12564SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
12565SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
12566SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
12567SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
12568SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo*);
12569SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
12570SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
12571SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
12572SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
12573SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
12574SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
12575SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
12576SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
12577SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
12578SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
12579SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
12580SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*);
12581SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
12582SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
12583SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
12584SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
12585SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
12586SQLITE_PRIVATE void sqlite3ExprCodeAtInit(Parse*, Expr*, int, u8);
12587SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
12588SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
12589SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
12590SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, u8);
12591#define SQLITE_ECEL_DUP      0x01  /* Deep, not shallow copies */
12592#define SQLITE_ECEL_FACTOR   0x02  /* Factor out constant terms */
12593SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
12594SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
12595SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
12596SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
12597SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
12598SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
12599SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
12600SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
12601SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
12602SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
12603SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
12604SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int);
12605SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
12606SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
12607SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
12608SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
12609SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
12610SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
12611SQLITE_PRIVATE void sqlite3PrngSaveState(void);
12612SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
12613SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
12614SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
12615SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
12616SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
12617SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
12618SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
12619SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
12620SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
12621SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
12622SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
12623SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
12624SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
12625SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
12626SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
12627SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
12628SQLITE_PRIVATE int sqlite3IsRowid(const char*);
12629SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8);
12630SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*);
12631SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
12632SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
12633SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
12634                                     u8,u8,int,int*);
12635SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
12636SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int, u8*, int*, int*);
12637SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
12638SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
12639SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
12640SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
12641SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
12642SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
12643SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
12644SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
12645SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
12646SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
12647SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
12648SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
12649SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
12650SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
12651SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
12652SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
12653SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
12654SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
12655SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
12656
12657#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
12658SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
12659#endif
12660
12661#ifndef SQLITE_OMIT_TRIGGER
12662SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
12663                           Expr*,int, int);
12664SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
12665SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
12666SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
12667SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
12668SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
12669SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
12670                            int, int, int);
12671SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
12672  void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
12673SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
12674SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
12675SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
12676                                        Select*,u8);
12677SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
12678SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
12679SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
12680SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
12681SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
12682# define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
12683#else
12684# define sqlite3TriggersExist(B,C,D,E,F) 0
12685# define sqlite3DeleteTrigger(A,B)
12686# define sqlite3DropTriggerPtr(A,B)
12687# define sqlite3UnlinkAndDeleteTrigger(A,B,C)
12688# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
12689# define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
12690# define sqlite3TriggerList(X, Y) 0
12691# define sqlite3ParseToplevel(p) p
12692# define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
12693#endif
12694
12695SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
12696SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
12697SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
12698#ifndef SQLITE_OMIT_AUTHORIZATION
12699SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
12700SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
12701SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
12702SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
12703SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
12704#else
12705# define sqlite3AuthRead(a,b,c,d)
12706# define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
12707# define sqlite3AuthContextPush(a,b,c)
12708# define sqlite3AuthContextPop(a)  ((void)(a))
12709#endif
12710SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
12711SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
12712SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
12713SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
12714SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
12715SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
12716SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
12717SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
12718SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
12719SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
12720SQLITE_PRIVATE int sqlite3Atoi(const char*);
12721SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
12722SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
12723SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
12724SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
12725SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
12726#ifndef SQLITE_OMIT_VIRTUALTABLE
12727SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
12728#endif
12729SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
12730
12731/*
12732** Routines to read and write variable-length integers.  These used to
12733** be defined locally, but now we use the varint routines in the util.c
12734** file.  Code should use the MACRO forms below, as the Varint32 versions
12735** are coded to assume the single byte case is already handled (which
12736** the MACRO form does).
12737*/
12738SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
12739SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
12740SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
12741SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
12742SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
12743
12744/*
12745** The header of a record consists of a sequence variable-length integers.
12746** These integers are almost always small and are encoded as a single byte.
12747** The following macros take advantage this fact to provide a fast encode
12748** and decode of the integers in a record header.  It is faster for the common
12749** case where the integer is a single byte.  It is a little slower when the
12750** integer is two or more bytes.  But overall it is faster.
12751**
12752** The following expressions are equivalent:
12753**
12754**     x = sqlite3GetVarint32( A, &B );
12755**     x = sqlite3PutVarint32( A, B );
12756**
12757**     x = getVarint32( A, B );
12758**     x = putVarint32( A, B );
12759**
12760*/
12761#define getVarint32(A,B)  \
12762  (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
12763#define putVarint32(A,B)  \
12764  (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
12765  sqlite3PutVarint32((A),(B)))
12766#define getVarint    sqlite3GetVarint
12767#define putVarint    sqlite3PutVarint
12768
12769
12770SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
12771SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
12772SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
12773SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
12774SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
12775SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
12776SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
12777SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
12778SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
12779SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
12780
12781#if defined(SQLITE_TEST)
12782SQLITE_PRIVATE const char *sqlite3ErrName(int);
12783#endif
12784
12785SQLITE_PRIVATE const char *sqlite3ErrStr(int);
12786SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
12787SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
12788SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
12789SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
12790SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*);
12791SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
12792SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
12793SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
12794SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
12795SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
12796SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
12797SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
12798SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
12799SQLITE_PRIVATE int sqlite3AbsInt32(int);
12800#ifdef SQLITE_ENABLE_8_3_NAMES
12801SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
12802#else
12803# define sqlite3FileSuffix3(X,Y)
12804#endif
12805SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,int);
12806
12807SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
12808SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
12809SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
12810                        void(*)(void*));
12811SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
12812SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
12813SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
12814SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
12815SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
12816SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
12817#ifndef SQLITE_AMALGAMATION
12818SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
12819SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
12820SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
12821SQLITE_PRIVATE const Token sqlite3IntTokens[];
12822SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
12823SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
12824#ifndef SQLITE_OMIT_WSD
12825SQLITE_PRIVATE int sqlite3PendingByte;
12826#endif
12827#endif
12828SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
12829SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
12830SQLITE_PRIVATE void sqlite3AlterFunctions(void);
12831SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
12832SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
12833SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
12834SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
12835SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
12836SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
12837SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
12838SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
12839SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
12840SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
12841SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
12842SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
12843SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
12844SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
12845SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
12846SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
12847SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
12848SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
12849SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
12850SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
12851SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
12852SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
12853SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
12854SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
12855SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
12856SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
12857SQLITE_PRIVATE void sqlite3SchemaClear(void *);
12858SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
12859SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
12860SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
12861SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
12862SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
12863SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
12864#ifdef SQLITE_DEBUG
12865SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
12866#endif
12867SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
12868  void (*)(sqlite3_context*,int,sqlite3_value **),
12869  void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
12870  FuncDestructor *pDestructor
12871);
12872SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
12873SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
12874
12875SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
12876SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
12877SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
12878SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum*,int);
12879SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
12880SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
12881SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
12882SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
12883
12884SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
12885SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
12886
12887#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
12888SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
12889SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(Parse*,Index*,UnpackedRecord**,Expr*,u8,int,int*);
12890SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
12891#endif
12892
12893/*
12894** The interface to the LEMON-generated parser
12895*/
12896SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
12897SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
12898SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
12899#ifdef YYTRACKMAXSTACKDEPTH
12900SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
12901#endif
12902
12903SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
12904#ifndef SQLITE_OMIT_LOAD_EXTENSION
12905SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
12906#else
12907# define sqlite3CloseExtensions(X)
12908#endif
12909
12910#ifndef SQLITE_OMIT_SHARED_CACHE
12911SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
12912#else
12913  #define sqlite3TableLock(v,w,x,y,z)
12914#endif
12915
12916#ifdef SQLITE_TEST
12917SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
12918#endif
12919
12920#ifdef SQLITE_OMIT_VIRTUALTABLE
12921#  define sqlite3VtabClear(Y)
12922#  define sqlite3VtabSync(X,Y) SQLITE_OK
12923#  define sqlite3VtabRollback(X)
12924#  define sqlite3VtabCommit(X)
12925#  define sqlite3VtabInSync(db) 0
12926#  define sqlite3VtabLock(X)
12927#  define sqlite3VtabUnlock(X)
12928#  define sqlite3VtabUnlockList(X)
12929#  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
12930#  define sqlite3GetVTable(X,Y)  ((VTable*)0)
12931#else
12932SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
12933SQLITE_PRIVATE    void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
12934SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, Vdbe*);
12935SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
12936SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
12937SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
12938SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
12939SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
12940SQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);
12941SQLITE_PRIVATE    void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
12942SQLITE_PRIVATE    VTable *sqlite3GetVTable(sqlite3*, Table*);
12943#  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
12944#endif
12945SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
12946SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
12947SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
12948SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
12949SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
12950SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
12951SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
12952SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
12953SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
12954SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
12955SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
12956SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
12957SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
12958SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
12959SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
12960SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
12961SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
12962SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
12963SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
12964SQLITE_PRIVATE const char *sqlite3JournalModename(int);
12965#ifndef SQLITE_OMIT_WAL
12966SQLITE_PRIVATE   int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
12967SQLITE_PRIVATE   int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
12968#endif
12969#ifndef SQLITE_OMIT_CTE
12970SQLITE_PRIVATE   With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
12971SQLITE_PRIVATE   void sqlite3WithDelete(sqlite3*,With*);
12972SQLITE_PRIVATE   void sqlite3WithPush(Parse*, With*, u8);
12973#else
12974#define sqlite3WithPush(x,y,z)
12975#define sqlite3WithDelete(x,y)
12976#endif
12977
12978/* Declarations for functions in fkey.c. All of these are replaced by
12979** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
12980** key functionality is available. If OMIT_TRIGGER is defined but
12981** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
12982** this case foreign keys are parsed, but no other functionality is
12983** provided (enforcement of FK constraints requires the triggers sub-system).
12984*/
12985#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
12986SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
12987SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
12988SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
12989SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
12990SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
12991SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
12992#else
12993  #define sqlite3FkActions(a,b,c,d,e,f)
12994  #define sqlite3FkCheck(a,b,c,d,e,f)
12995  #define sqlite3FkDropTable(a,b,c)
12996  #define sqlite3FkOldmask(a,b)         0
12997  #define sqlite3FkRequired(a,b,c,d)    0
12998#endif
12999#ifndef SQLITE_OMIT_FOREIGN_KEY
13000SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
13001SQLITE_PRIVATE   int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
13002#else
13003  #define sqlite3FkDelete(a,b)
13004  #define sqlite3FkLocateIndex(a,b,c,d,e)
13005#endif
13006
13007
13008/*
13009** Available fault injectors.  Should be numbered beginning with 0.
13010*/
13011#define SQLITE_FAULTINJECTOR_MALLOC     0
13012#define SQLITE_FAULTINJECTOR_COUNT      1
13013
13014/*
13015** The interface to the code in fault.c used for identifying "benign"
13016** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
13017** is not defined.
13018*/
13019#ifndef SQLITE_OMIT_BUILTIN_TEST
13020SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
13021SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
13022#else
13023  #define sqlite3BeginBenignMalloc()
13024  #define sqlite3EndBenignMalloc()
13025#endif
13026
13027#define IN_INDEX_ROWID           1
13028#define IN_INDEX_EPH             2
13029#define IN_INDEX_INDEX_ASC       3
13030#define IN_INDEX_INDEX_DESC      4
13031SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
13032
13033#ifdef SQLITE_ENABLE_ATOMIC_WRITE
13034SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
13035SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
13036SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
13037SQLITE_PRIVATE   int sqlite3JournalExists(sqlite3_file *p);
13038#else
13039  #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
13040  #define sqlite3JournalExists(p) 1
13041#endif
13042
13043SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
13044SQLITE_PRIVATE int sqlite3MemJournalSize(void);
13045SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
13046
13047#if SQLITE_MAX_EXPR_DEPTH>0
13048SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
13049SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
13050SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
13051#else
13052  #define sqlite3ExprSetHeight(x,y)
13053  #define sqlite3SelectExprHeight(x) 0
13054  #define sqlite3ExprCheckHeight(x,y)
13055#endif
13056
13057SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
13058SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
13059
13060#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
13061SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
13062SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
13063SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
13064#else
13065  #define sqlite3ConnectionBlocked(x,y)
13066  #define sqlite3ConnectionUnlocked(x)
13067  #define sqlite3ConnectionClosed(x)
13068#endif
13069
13070#ifdef SQLITE_DEBUG
13071SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
13072#endif
13073
13074/*
13075** If the SQLITE_ENABLE IOTRACE exists then the global variable
13076** sqlite3IoTrace is a pointer to a printf-like routine used to
13077** print I/O tracing messages.
13078*/
13079#ifdef SQLITE_ENABLE_IOTRACE
13080# define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
13081SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
13082SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
13083#else
13084# define IOTRACE(A)
13085# define sqlite3VdbeIOTraceSql(X)
13086#endif
13087
13088/*
13089** These routines are available for the mem2.c debugging memory allocator
13090** only.  They are used to verify that different "types" of memory
13091** allocations are properly tracked by the system.
13092**
13093** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
13094** the MEMTYPE_* macros defined below.  The type must be a bitmask with
13095** a single bit set.
13096**
13097** sqlite3MemdebugHasType() returns true if any of the bits in its second
13098** argument match the type set by the previous sqlite3MemdebugSetType().
13099** sqlite3MemdebugHasType() is intended for use inside assert() statements.
13100**
13101** sqlite3MemdebugNoType() returns true if none of the bits in its second
13102** argument match the type set by the previous sqlite3MemdebugSetType().
13103**
13104** Perhaps the most important point is the difference between MEMTYPE_HEAP
13105** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
13106** it might have been allocated by lookaside, except the allocation was
13107** too large or lookaside was already full.  It is important to verify
13108** that allocations that might have been satisfied by lookaside are not
13109** passed back to non-lookaside free() routines.  Asserts such as the
13110** example above are placed on the non-lookaside free() routines to verify
13111** this constraint.
13112**
13113** All of this is no-op for a production build.  It only comes into
13114** play when the SQLITE_MEMDEBUG compile-time option is used.
13115*/
13116#ifdef SQLITE_MEMDEBUG
13117SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
13118SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
13119SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
13120#else
13121# define sqlite3MemdebugSetType(X,Y)  /* no-op */
13122# define sqlite3MemdebugHasType(X,Y)  1
13123# define sqlite3MemdebugNoType(X,Y)   1
13124#endif
13125#define MEMTYPE_HEAP       0x01  /* General heap allocations */
13126#define MEMTYPE_LOOKASIDE  0x02  /* Might have been lookaside memory */
13127#define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
13128#define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
13129#define MEMTYPE_DB         0x10  /* Uses sqlite3DbMalloc, not sqlite_malloc */
13130
13131#endif /* _SQLITEINT_H_ */
13132
13133/************** End of sqliteInt.h *******************************************/
13134/************** Begin file global.c ******************************************/
13135/*
13136** 2008 June 13
13137**
13138** The author disclaims copyright to this source code.  In place of
13139** a legal notice, here is a blessing:
13140**
13141**    May you do good and not evil.
13142**    May you find forgiveness for yourself and forgive others.
13143**    May you share freely, never taking more than you give.
13144**
13145*************************************************************************
13146**
13147** This file contains definitions of global variables and contants.
13148*/
13149
13150/* An array to map all upper-case characters into their corresponding
13151** lower-case character.
13152**
13153** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
13154** handle case conversions for the UTF character set since the tables
13155** involved are nearly as big or bigger than SQLite itself.
13156*/
13157SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
13158#ifdef SQLITE_ASCII
13159      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
13160     18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
13161     36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
13162     54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
13163    104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
13164    122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
13165    108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
13166    126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
13167    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
13168    162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
13169    180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
13170    198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
13171    216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
13172    234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
13173    252,253,254,255
13174#endif
13175#ifdef SQLITE_EBCDIC
13176      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
13177     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
13178     32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
13179     48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
13180     64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
13181     80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
13182     96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
13183    112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
13184    128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
13185    144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
13186    160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
13187    176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
13188    192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
13189    208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
13190    224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
13191    239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
13192#endif
13193};
13194
13195/*
13196** The following 256 byte lookup table is used to support SQLites built-in
13197** equivalents to the following standard library functions:
13198**
13199**   isspace()                        0x01
13200**   isalpha()                        0x02
13201**   isdigit()                        0x04
13202**   isalnum()                        0x06
13203**   isxdigit()                       0x08
13204**   toupper()                        0x20
13205**   SQLite identifier character      0x40
13206**
13207** Bit 0x20 is set if the mapped character requires translation to upper
13208** case. i.e. if the character is a lower-case ASCII character.
13209** If x is a lower-case ASCII character, then its upper-case equivalent
13210** is (x - 0x20). Therefore toupper() can be implemented as:
13211**
13212**   (x & ~(map[x]&0x20))
13213**
13214** Standard function tolower() is implemented using the sqlite3UpperToLower[]
13215** array. tolower() is used more often than toupper() by SQLite.
13216**
13217** Bit 0x40 is set if the character non-alphanumeric and can be used in an
13218** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
13219** non-ASCII UTF character. Hence the test for whether or not a character is
13220** part of an identifier is 0x46.
13221**
13222** SQLite's versions are identical to the standard versions assuming a
13223** locale of "C". They are implemented as macros in sqliteInt.h.
13224*/
13225#ifdef SQLITE_ASCII
13226SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
13227  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
13228  0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
13229  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
13230  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
13231  0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
13232  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
13233  0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
13234  0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
13235
13236  0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
13237  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
13238  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
13239  0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
13240  0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
13241  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
13242  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
13243  0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
13244
13245  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
13246  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
13247  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
13248  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
13249  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
13250  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
13251  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
13252  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
13253
13254  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
13255  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
13256  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
13257  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
13258  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
13259  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
13260  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
13261  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
13262};
13263#endif
13264
13265#ifndef SQLITE_USE_URI
13266# define  SQLITE_USE_URI 0
13267#endif
13268
13269#ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
13270# define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
13271#endif
13272
13273/*
13274** The following singleton contains the global configuration for
13275** the SQLite library.
13276*/
13277SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
13278   SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
13279   1,                         /* bCoreMutex */
13280   SQLITE_THREADSAFE==1,      /* bFullMutex */
13281   SQLITE_USE_URI,            /* bOpenUri */
13282   SQLITE_ALLOW_COVERING_INDEX_SCAN,   /* bUseCis */
13283   0x7ffffffe,                /* mxStrlen */
13284   0,                         /* neverCorrupt */
13285   128,                       /* szLookaside */
13286   500,                       /* nLookaside */
13287   {0,0,0,0,0,0,0,0},         /* m */
13288   {0,0,0,0,0,0,0,0,0},       /* mutex */
13289   {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
13290   (void*)0,                  /* pHeap */
13291   0,                         /* nHeap */
13292   0, 0,                      /* mnHeap, mxHeap */
13293   SQLITE_DEFAULT_MMAP_SIZE,  /* szMmap */
13294   SQLITE_MAX_MMAP_SIZE,      /* mxMmap */
13295   (void*)0,                  /* pScratch */
13296   0,                         /* szScratch */
13297   0,                         /* nScratch */
13298   (void*)0,                  /* pPage */
13299   0,                         /* szPage */
13300   0,                         /* nPage */
13301   0,                         /* mxParserStack */
13302   0,                         /* sharedCacheEnabled */
13303   /* All the rest should always be initialized to zero */
13304   0,                         /* isInit */
13305   0,                         /* inProgress */
13306   0,                         /* isMutexInit */
13307   0,                         /* isMallocInit */
13308   0,                         /* isPCacheInit */
13309   0,                         /* nRefInitMutex */
13310   0,                         /* pInitMutex */
13311   0,                         /* xLog */
13312   0,                         /* pLogArg */
13313#ifdef SQLITE_ENABLE_SQLLOG
13314   0,                         /* xSqllog */
13315   0,                         /* pSqllogArg */
13316#endif
13317#ifdef SQLITE_VDBE_COVERAGE
13318   0,                         /* xVdbeBranch */
13319   0,                         /* pVbeBranchArg */
13320#endif
13321#ifndef SQLITE_OMIT_BUILTIN_TEST
13322   0,                         /* xTestCallback */
13323#endif
13324   0                          /* bLocaltimeFault */
13325};
13326
13327/*
13328** Hash table for global functions - functions common to all
13329** database connections.  After initialization, this table is
13330** read-only.
13331*/
13332SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
13333
13334/*
13335** Constant tokens for values 0 and 1.
13336*/
13337SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
13338   { "0", 1 },
13339   { "1", 1 }
13340};
13341
13342
13343/*
13344** The value of the "pending" byte must be 0x40000000 (1 byte past the
13345** 1-gibabyte boundary) in a compatible database.  SQLite never uses
13346** the database page that contains the pending byte.  It never attempts
13347** to read or write that page.  The pending byte page is set assign
13348** for use by the VFS layers as space for managing file locks.
13349**
13350** During testing, it is often desirable to move the pending byte to
13351** a different position in the file.  This allows code that has to
13352** deal with the pending byte to run on files that are much smaller
13353** than 1 GiB.  The sqlite3_test_control() interface can be used to
13354** move the pending byte.
13355**
13356** IMPORTANT:  Changing the pending byte to any value other than
13357** 0x40000000 results in an incompatible database file format!
13358** Changing the pending byte during operating results in undefined
13359** and dileterious behavior.
13360*/
13361#ifndef SQLITE_OMIT_WSD
13362SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
13363#endif
13364
13365/*
13366** Properties of opcodes.  The OPFLG_INITIALIZER macro is
13367** created by mkopcodeh.awk during compilation.  Data is obtained
13368** from the comments following the "case OP_xxxx:" statements in
13369** the vdbe.c file.
13370*/
13371SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
13372
13373/************** End of global.c **********************************************/
13374/************** Begin file ctime.c *******************************************/
13375/*
13376** 2010 February 23
13377**
13378** The author disclaims copyright to this source code.  In place of
13379** a legal notice, here is a blessing:
13380**
13381**    May you do good and not evil.
13382**    May you find forgiveness for yourself and forgive others.
13383**    May you share freely, never taking more than you give.
13384**
13385*************************************************************************
13386**
13387** This file implements routines used to report what compile-time options
13388** SQLite was built with.
13389*/
13390
13391#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
13392
13393
13394/*
13395** An array of names of all compile-time options.  This array should
13396** be sorted A-Z.
13397**
13398** This array looks large, but in a typical installation actually uses
13399** only a handful of compile-time options, so most times this array is usually
13400** rather short and uses little memory space.
13401*/
13402static const char * const azCompileOpt[] = {
13403
13404/* These macros are provided to "stringify" the value of the define
13405** for those options in which the value is meaningful. */
13406#define CTIMEOPT_VAL_(opt) #opt
13407#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
13408
13409#ifdef SQLITE_32BIT_ROWID
13410  "32BIT_ROWID",
13411#endif
13412#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
13413  "4_BYTE_ALIGNED_MALLOC",
13414#endif
13415#ifdef SQLITE_CASE_SENSITIVE_LIKE
13416  "CASE_SENSITIVE_LIKE",
13417#endif
13418#ifdef SQLITE_CHECK_PAGES
13419  "CHECK_PAGES",
13420#endif
13421#ifdef SQLITE_COVERAGE_TEST
13422  "COVERAGE_TEST",
13423#endif
13424#ifdef SQLITE_DEBUG
13425  "DEBUG",
13426#endif
13427#ifdef SQLITE_DEFAULT_LOCKING_MODE
13428  "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
13429#endif
13430#if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
13431  "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
13432#endif
13433#ifdef SQLITE_DISABLE_DIRSYNC
13434  "DISABLE_DIRSYNC",
13435#endif
13436#ifdef SQLITE_DISABLE_LFS
13437  "DISABLE_LFS",
13438#endif
13439#ifdef SQLITE_ENABLE_ATOMIC_WRITE
13440  "ENABLE_ATOMIC_WRITE",
13441#endif
13442#ifdef SQLITE_ENABLE_CEROD
13443  "ENABLE_CEROD",
13444#endif
13445#ifdef SQLITE_ENABLE_COLUMN_METADATA
13446  "ENABLE_COLUMN_METADATA",
13447#endif
13448#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
13449  "ENABLE_EXPENSIVE_ASSERT",
13450#endif
13451#ifdef SQLITE_ENABLE_FTS1
13452  "ENABLE_FTS1",
13453#endif
13454#ifdef SQLITE_ENABLE_FTS2
13455  "ENABLE_FTS2",
13456#endif
13457#ifdef SQLITE_ENABLE_FTS3
13458  "ENABLE_FTS3",
13459#endif
13460#ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
13461  "ENABLE_FTS3_PARENTHESIS",
13462#endif
13463#ifdef SQLITE_ENABLE_FTS4
13464  "ENABLE_FTS4",
13465#endif
13466#ifdef SQLITE_ENABLE_ICU
13467  "ENABLE_ICU",
13468#endif
13469#ifdef SQLITE_ENABLE_IOTRACE
13470  "ENABLE_IOTRACE",
13471#endif
13472#ifdef SQLITE_ENABLE_LOAD_EXTENSION
13473  "ENABLE_LOAD_EXTENSION",
13474#endif
13475#ifdef SQLITE_ENABLE_LOCKING_STYLE
13476  "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
13477#endif
13478#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
13479  "ENABLE_MEMORY_MANAGEMENT",
13480#endif
13481#ifdef SQLITE_ENABLE_MEMSYS3
13482  "ENABLE_MEMSYS3",
13483#endif
13484#ifdef SQLITE_ENABLE_MEMSYS5
13485  "ENABLE_MEMSYS5",
13486#endif
13487#ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
13488  "ENABLE_OVERSIZE_CELL_CHECK",
13489#endif
13490#ifdef SQLITE_ENABLE_RTREE
13491  "ENABLE_RTREE",
13492#endif
13493#if defined(SQLITE_ENABLE_STAT4)
13494  "ENABLE_STAT4",
13495#elif defined(SQLITE_ENABLE_STAT3)
13496  "ENABLE_STAT3",
13497#endif
13498#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
13499  "ENABLE_UNLOCK_NOTIFY",
13500#endif
13501#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
13502  "ENABLE_UPDATE_DELETE_LIMIT",
13503#endif
13504#ifdef SQLITE_HAS_CODEC
13505  "HAS_CODEC",
13506#endif
13507#ifdef SQLITE_HAVE_ISNAN
13508  "HAVE_ISNAN",
13509#endif
13510#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
13511  "HOMEGROWN_RECURSIVE_MUTEX",
13512#endif
13513#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
13514  "IGNORE_AFP_LOCK_ERRORS",
13515#endif
13516#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
13517  "IGNORE_FLOCK_LOCK_ERRORS",
13518#endif
13519#ifdef SQLITE_INT64_TYPE
13520  "INT64_TYPE",
13521#endif
13522#ifdef SQLITE_LOCK_TRACE
13523  "LOCK_TRACE",
13524#endif
13525#if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
13526  "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
13527#endif
13528#ifdef SQLITE_MAX_SCHEMA_RETRY
13529  "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
13530#endif
13531#ifdef SQLITE_MEMDEBUG
13532  "MEMDEBUG",
13533#endif
13534#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
13535  "MIXED_ENDIAN_64BIT_FLOAT",
13536#endif
13537#ifdef SQLITE_NO_SYNC
13538  "NO_SYNC",
13539#endif
13540#ifdef SQLITE_OMIT_ALTERTABLE
13541  "OMIT_ALTERTABLE",
13542#endif
13543#ifdef SQLITE_OMIT_ANALYZE
13544  "OMIT_ANALYZE",
13545#endif
13546#ifdef SQLITE_OMIT_ATTACH
13547  "OMIT_ATTACH",
13548#endif
13549#ifdef SQLITE_OMIT_AUTHORIZATION
13550  "OMIT_AUTHORIZATION",
13551#endif
13552#ifdef SQLITE_OMIT_AUTOINCREMENT
13553  "OMIT_AUTOINCREMENT",
13554#endif
13555#ifdef SQLITE_OMIT_AUTOINIT
13556  "OMIT_AUTOINIT",
13557#endif
13558#ifdef SQLITE_OMIT_AUTOMATIC_INDEX
13559  "OMIT_AUTOMATIC_INDEX",
13560#endif
13561#ifdef SQLITE_OMIT_AUTORESET
13562  "OMIT_AUTORESET",
13563#endif
13564#ifdef SQLITE_OMIT_AUTOVACUUM
13565  "OMIT_AUTOVACUUM",
13566#endif
13567#ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
13568  "OMIT_BETWEEN_OPTIMIZATION",
13569#endif
13570#ifdef SQLITE_OMIT_BLOB_LITERAL
13571  "OMIT_BLOB_LITERAL",
13572#endif
13573#ifdef SQLITE_OMIT_BTREECOUNT
13574  "OMIT_BTREECOUNT",
13575#endif
13576#ifdef SQLITE_OMIT_BUILTIN_TEST
13577  "OMIT_BUILTIN_TEST",
13578#endif
13579#ifdef SQLITE_OMIT_CAST
13580  "OMIT_CAST",
13581#endif
13582#ifdef SQLITE_OMIT_CHECK
13583  "OMIT_CHECK",
13584#endif
13585#ifdef SQLITE_OMIT_COMPLETE
13586  "OMIT_COMPLETE",
13587#endif
13588#ifdef SQLITE_OMIT_COMPOUND_SELECT
13589  "OMIT_COMPOUND_SELECT",
13590#endif
13591#ifdef SQLITE_OMIT_CTE
13592  "OMIT_CTE",
13593#endif
13594#ifdef SQLITE_OMIT_DATETIME_FUNCS
13595  "OMIT_DATETIME_FUNCS",
13596#endif
13597#ifdef SQLITE_OMIT_DECLTYPE
13598  "OMIT_DECLTYPE",
13599#endif
13600#ifdef SQLITE_OMIT_DEPRECATED
13601  "OMIT_DEPRECATED",
13602#endif
13603#ifdef SQLITE_OMIT_DISKIO
13604  "OMIT_DISKIO",
13605#endif
13606#ifdef SQLITE_OMIT_EXPLAIN
13607  "OMIT_EXPLAIN",
13608#endif
13609#ifdef SQLITE_OMIT_FLAG_PRAGMAS
13610  "OMIT_FLAG_PRAGMAS",
13611#endif
13612#ifdef SQLITE_OMIT_FLOATING_POINT
13613  "OMIT_FLOATING_POINT",
13614#endif
13615#ifdef SQLITE_OMIT_FOREIGN_KEY
13616  "OMIT_FOREIGN_KEY",
13617#endif
13618#ifdef SQLITE_OMIT_GET_TABLE
13619  "OMIT_GET_TABLE",
13620#endif
13621#ifdef SQLITE_OMIT_INCRBLOB
13622  "OMIT_INCRBLOB",
13623#endif
13624#ifdef SQLITE_OMIT_INTEGRITY_CHECK
13625  "OMIT_INTEGRITY_CHECK",
13626#endif
13627#ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
13628  "OMIT_LIKE_OPTIMIZATION",
13629#endif
13630#ifdef SQLITE_OMIT_LOAD_EXTENSION
13631  "OMIT_LOAD_EXTENSION",
13632#endif
13633#ifdef SQLITE_OMIT_LOCALTIME
13634  "OMIT_LOCALTIME",
13635#endif
13636#ifdef SQLITE_OMIT_LOOKASIDE
13637  "OMIT_LOOKASIDE",
13638#endif
13639#ifdef SQLITE_OMIT_MEMORYDB
13640  "OMIT_MEMORYDB",
13641#endif
13642#ifdef SQLITE_OMIT_OR_OPTIMIZATION
13643  "OMIT_OR_OPTIMIZATION",
13644#endif
13645#ifdef SQLITE_OMIT_PAGER_PRAGMAS
13646  "OMIT_PAGER_PRAGMAS",
13647#endif
13648#ifdef SQLITE_OMIT_PRAGMA
13649  "OMIT_PRAGMA",
13650#endif
13651#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
13652  "OMIT_PROGRESS_CALLBACK",
13653#endif
13654#ifdef SQLITE_OMIT_QUICKBALANCE
13655  "OMIT_QUICKBALANCE",
13656#endif
13657#ifdef SQLITE_OMIT_REINDEX
13658  "OMIT_REINDEX",
13659#endif
13660#ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
13661  "OMIT_SCHEMA_PRAGMAS",
13662#endif
13663#ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
13664  "OMIT_SCHEMA_VERSION_PRAGMAS",
13665#endif
13666#ifdef SQLITE_OMIT_SHARED_CACHE
13667  "OMIT_SHARED_CACHE",
13668#endif
13669#ifdef SQLITE_OMIT_SUBQUERY
13670  "OMIT_SUBQUERY",
13671#endif
13672#ifdef SQLITE_OMIT_TCL_VARIABLE
13673  "OMIT_TCL_VARIABLE",
13674#endif
13675#ifdef SQLITE_OMIT_TEMPDB
13676  "OMIT_TEMPDB",
13677#endif
13678#ifdef SQLITE_OMIT_TRACE
13679  "OMIT_TRACE",
13680#endif
13681#ifdef SQLITE_OMIT_TRIGGER
13682  "OMIT_TRIGGER",
13683#endif
13684#ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
13685  "OMIT_TRUNCATE_OPTIMIZATION",
13686#endif
13687#ifdef SQLITE_OMIT_UTF16
13688  "OMIT_UTF16",
13689#endif
13690#ifdef SQLITE_OMIT_VACUUM
13691  "OMIT_VACUUM",
13692#endif
13693#ifdef SQLITE_OMIT_VIEW
13694  "OMIT_VIEW",
13695#endif
13696#ifdef SQLITE_OMIT_VIRTUALTABLE
13697  "OMIT_VIRTUALTABLE",
13698#endif
13699#ifdef SQLITE_OMIT_WAL
13700  "OMIT_WAL",
13701#endif
13702#ifdef SQLITE_OMIT_WSD
13703  "OMIT_WSD",
13704#endif
13705#ifdef SQLITE_OMIT_XFER_OPT
13706  "OMIT_XFER_OPT",
13707#endif
13708#ifdef SQLITE_PERFORMANCE_TRACE
13709  "PERFORMANCE_TRACE",
13710#endif
13711#ifdef SQLITE_PROXY_DEBUG
13712  "PROXY_DEBUG",
13713#endif
13714#ifdef SQLITE_RTREE_INT_ONLY
13715  "RTREE_INT_ONLY",
13716#endif
13717#ifdef SQLITE_SECURE_DELETE
13718  "SECURE_DELETE",
13719#endif
13720#ifdef SQLITE_SMALL_STACK
13721  "SMALL_STACK",
13722#endif
13723#ifdef SQLITE_SOUNDEX
13724  "SOUNDEX",
13725#endif
13726#ifdef SQLITE_SYSTEM_MALLOC
13727  "SYSTEM_MALLOC",
13728#endif
13729#ifdef SQLITE_TCL
13730  "TCL",
13731#endif
13732#if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
13733  "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
13734#endif
13735#ifdef SQLITE_TEST
13736  "TEST",
13737#endif
13738#if defined(SQLITE_THREADSAFE)
13739  "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
13740#endif
13741#ifdef SQLITE_USE_ALLOCA
13742  "USE_ALLOCA",
13743#endif
13744#ifdef SQLITE_WIN32_MALLOC
13745  "WIN32_MALLOC",
13746#endif
13747#ifdef SQLITE_ZERO_MALLOC
13748  "ZERO_MALLOC"
13749#endif
13750};
13751
13752/*
13753** Given the name of a compile-time option, return true if that option
13754** was used and false if not.
13755**
13756** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
13757** is not required for a match.
13758*/
13759SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
13760  int i, n;
13761  if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
13762  n = sqlite3Strlen30(zOptName);
13763
13764  /* Since ArraySize(azCompileOpt) is normally in single digits, a
13765  ** linear search is adequate.  No need for a binary search. */
13766  for(i=0; i<ArraySize(azCompileOpt); i++){
13767    if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
13768     && sqlite3CtypeMap[(unsigned char)azCompileOpt[i][n]]==0
13769    ){
13770      return 1;
13771    }
13772  }
13773  return 0;
13774}
13775
13776/*
13777** Return the N-th compile-time option string.  If N is out of range,
13778** return a NULL pointer.
13779*/
13780SQLITE_API const char *sqlite3_compileoption_get(int N){
13781  if( N>=0 && N<ArraySize(azCompileOpt) ){
13782    return azCompileOpt[N];
13783  }
13784  return 0;
13785}
13786
13787#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
13788
13789/************** End of ctime.c ***********************************************/
13790/************** Begin file status.c ******************************************/
13791/*
13792** 2008 June 18
13793**
13794** The author disclaims copyright to this source code.  In place of
13795** a legal notice, here is a blessing:
13796**
13797**    May you do good and not evil.
13798**    May you find forgiveness for yourself and forgive others.
13799**    May you share freely, never taking more than you give.
13800**
13801*************************************************************************
13802**
13803** This module implements the sqlite3_status() interface and related
13804** functionality.
13805*/
13806/************** Include vdbeInt.h in the middle of status.c ******************/
13807/************** Begin file vdbeInt.h *****************************************/
13808/*
13809** 2003 September 6
13810**
13811** The author disclaims copyright to this source code.  In place of
13812** a legal notice, here is a blessing:
13813**
13814**    May you do good and not evil.
13815**    May you find forgiveness for yourself and forgive others.
13816**    May you share freely, never taking more than you give.
13817**
13818*************************************************************************
13819** This is the header file for information that is private to the
13820** VDBE.  This information used to all be at the top of the single
13821** source code file "vdbe.c".  When that file became too big (over
13822** 6000 lines long) it was split up into several smaller files and
13823** this header information was factored out.
13824*/
13825#ifndef _VDBEINT_H_
13826#define _VDBEINT_H_
13827
13828/*
13829** The maximum number of times that a statement will try to reparse
13830** itself before giving up and returning SQLITE_SCHEMA.
13831*/
13832#ifndef SQLITE_MAX_SCHEMA_RETRY
13833# define SQLITE_MAX_SCHEMA_RETRY 50
13834#endif
13835
13836/*
13837** SQL is translated into a sequence of instructions to be
13838** executed by a virtual machine.  Each instruction is an instance
13839** of the following structure.
13840*/
13841typedef struct VdbeOp Op;
13842
13843/*
13844** Boolean values
13845*/
13846typedef unsigned Bool;
13847
13848/* Opaque type used by code in vdbesort.c */
13849typedef struct VdbeSorter VdbeSorter;
13850
13851/* Opaque type used by the explainer */
13852typedef struct Explain Explain;
13853
13854/* Elements of the linked list at Vdbe.pAuxData */
13855typedef struct AuxData AuxData;
13856
13857/*
13858** A cursor is a pointer into a single BTree within a database file.
13859** The cursor can seek to a BTree entry with a particular key, or
13860** loop over all entries of the Btree.  You can also insert new BTree
13861** entries or retrieve the key or data from the entry that the cursor
13862** is currently pointing to.
13863**
13864** Cursors can also point to virtual tables, sorters, or "pseudo-tables".
13865** A pseudo-table is a single-row table implemented by registers.
13866**
13867** Every cursor that the virtual machine has open is represented by an
13868** instance of the following structure.
13869*/
13870struct VdbeCursor {
13871  BtCursor *pCursor;    /* The cursor structure of the backend */
13872  Btree *pBt;           /* Separate file holding temporary table */
13873  KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
13874  int seekResult;       /* Result of previous sqlite3BtreeMoveto() */
13875  int pseudoTableReg;   /* Register holding pseudotable content. */
13876  i16 nField;           /* Number of fields in the header */
13877  u16 nHdrParsed;       /* Number of header fields parsed so far */
13878  i8 iDb;               /* Index of cursor database in db->aDb[] (or -1) */
13879  u8 nullRow;           /* True if pointing to a row with no data */
13880  u8 rowidIsValid;      /* True if lastRowid is valid */
13881  u8 deferredMoveto;    /* A call to sqlite3BtreeMoveto() is needed */
13882  Bool isEphemeral:1;   /* True for an ephemeral table */
13883  Bool useRandomRowid:1;/* Generate new record numbers semi-randomly */
13884  Bool isTable:1;       /* True if a table requiring integer keys */
13885  Bool isOrdered:1;     /* True if the underlying table is BTREE_UNORDERED */
13886  sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
13887  i64 seqCount;         /* Sequence counter */
13888  i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
13889  i64 lastRowid;        /* Rowid being deleted by OP_Delete */
13890  VdbeSorter *pSorter;  /* Sorter object for OP_SorterOpen cursors */
13891
13892  /* Cached information about the header for the data record that the
13893  ** cursor is currently pointing to.  Only valid if cacheStatus matches
13894  ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
13895  ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
13896  ** the cache is out of date.
13897  **
13898  ** aRow might point to (ephemeral) data for the current row, or it might
13899  ** be NULL.
13900  */
13901  u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
13902  u32 payloadSize;      /* Total number of bytes in the record */
13903  u32 szRow;            /* Byte available in aRow */
13904  u32 iHdrOffset;       /* Offset to next unparsed byte of the header */
13905  const u8 *aRow;       /* Data for the current row, if all on one page */
13906  u32 aType[1];         /* Type values for all entries in the record */
13907  /* 2*nField extra array elements allocated for aType[], beyond the one
13908  ** static element declared in the structure.  nField total array slots for
13909  ** aType[] and nField+1 array slots for aOffset[] */
13910};
13911typedef struct VdbeCursor VdbeCursor;
13912
13913/*
13914** When a sub-program is executed (OP_Program), a structure of this type
13915** is allocated to store the current value of the program counter, as
13916** well as the current memory cell array and various other frame specific
13917** values stored in the Vdbe struct. When the sub-program is finished,
13918** these values are copied back to the Vdbe from the VdbeFrame structure,
13919** restoring the state of the VM to as it was before the sub-program
13920** began executing.
13921**
13922** The memory for a VdbeFrame object is allocated and managed by a memory
13923** cell in the parent (calling) frame. When the memory cell is deleted or
13924** overwritten, the VdbeFrame object is not freed immediately. Instead, it
13925** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
13926** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
13927** this instead of deleting the VdbeFrame immediately is to avoid recursive
13928** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
13929** child frame are released.
13930**
13931** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
13932** set to NULL if the currently executing frame is the main program.
13933*/
13934typedef struct VdbeFrame VdbeFrame;
13935struct VdbeFrame {
13936  Vdbe *v;                /* VM this frame belongs to */
13937  VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
13938  Op *aOp;                /* Program instructions for parent frame */
13939  Mem *aMem;              /* Array of memory cells for parent frame */
13940  u8 *aOnceFlag;          /* Array of OP_Once flags for parent frame */
13941  VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
13942  void *token;            /* Copy of SubProgram.token */
13943  i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
13944  int nCursor;            /* Number of entries in apCsr */
13945  int pc;                 /* Program Counter in parent (calling) frame */
13946  int nOp;                /* Size of aOp array */
13947  int nMem;               /* Number of entries in aMem */
13948  int nOnceFlag;          /* Number of entries in aOnceFlag */
13949  int nChildMem;          /* Number of memory cells for child frame */
13950  int nChildCsr;          /* Number of cursors for child frame */
13951  int nChange;            /* Statement changes (Vdbe.nChanges)     */
13952};
13953
13954#define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
13955
13956/*
13957** A value for VdbeCursor.cacheValid that means the cache is always invalid.
13958*/
13959#define CACHE_STALE 0
13960
13961/*
13962** Internally, the vdbe manipulates nearly all SQL values as Mem
13963** structures. Each Mem struct may cache multiple representations (string,
13964** integer etc.) of the same value.
13965*/
13966struct Mem {
13967  sqlite3 *db;        /* The associated database connection */
13968  char *z;            /* String or BLOB value */
13969  double r;           /* Real value */
13970  union {
13971    i64 i;              /* Integer value used when MEM_Int is set in flags */
13972    int nZero;          /* Used when bit MEM_Zero is set in flags */
13973    FuncDef *pDef;      /* Used only when flags==MEM_Agg */
13974    RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
13975    VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
13976  } u;
13977  int n;              /* Number of characters in string value, excluding '\0' */
13978  u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
13979  u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
13980#ifdef SQLITE_DEBUG
13981  Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
13982  void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
13983#endif
13984  void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
13985  char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
13986};
13987
13988/* One or more of the following flags are set to indicate the validOK
13989** representations of the value stored in the Mem struct.
13990**
13991** If the MEM_Null flag is set, then the value is an SQL NULL value.
13992** No other flags may be set in this case.
13993**
13994** If the MEM_Str flag is set then Mem.z points at a string representation.
13995** Usually this is encoded in the same unicode encoding as the main
13996** database (see below for exceptions). If the MEM_Term flag is also
13997** set, then the string is nul terminated. The MEM_Int and MEM_Real
13998** flags may coexist with the MEM_Str flag.
13999*/
14000#define MEM_Null      0x0001   /* Value is NULL */
14001#define MEM_Str       0x0002   /* Value is a string */
14002#define MEM_Int       0x0004   /* Value is an integer */
14003#define MEM_Real      0x0008   /* Value is a real number */
14004#define MEM_Blob      0x0010   /* Value is a BLOB */
14005#define MEM_AffMask   0x001f   /* Mask of affinity bits */
14006#define MEM_RowSet    0x0020   /* Value is a RowSet object */
14007#define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
14008#define MEM_Undefined 0x0080   /* Value is undefined */
14009#define MEM_Cleared   0x0100   /* NULL set by OP_Null, not from data */
14010#define MEM_TypeMask  0x01ff   /* Mask of type bits */
14011
14012
14013/* Whenever Mem contains a valid string or blob representation, one of
14014** the following flags must be set to determine the memory management
14015** policy for Mem.z.  The MEM_Term flag tells us whether or not the
14016** string is \000 or \u0000 terminated
14017*/
14018#define MEM_Term      0x0200   /* String rep is nul terminated */
14019#define MEM_Dyn       0x0400   /* Need to call Mem.xDel() on Mem.z */
14020#define MEM_Static    0x0800   /* Mem.z points to a static string */
14021#define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
14022#define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
14023#define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
14024#ifdef SQLITE_OMIT_INCRBLOB
14025  #undef MEM_Zero
14026  #define MEM_Zero 0x0000
14027#endif
14028
14029/*
14030** Clear any existing type flags from a Mem and replace them with f
14031*/
14032#define MemSetTypeFlag(p, f) \
14033   ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
14034
14035/*
14036** Return true if a memory cell is not marked as invalid.  This macro
14037** is for use inside assert() statements only.
14038*/
14039#ifdef SQLITE_DEBUG
14040#define memIsValid(M)  ((M)->flags & MEM_Undefined)==0
14041#endif
14042
14043/*
14044** Each auxilliary data pointer stored by a user defined function
14045** implementation calling sqlite3_set_auxdata() is stored in an instance
14046** of this structure. All such structures associated with a single VM
14047** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
14048** when the VM is halted (if not before).
14049*/
14050struct AuxData {
14051  int iOp;                        /* Instruction number of OP_Function opcode */
14052  int iArg;                       /* Index of function argument. */
14053  void *pAux;                     /* Aux data pointer */
14054  void (*xDelete)(void *);        /* Destructor for the aux data */
14055  AuxData *pNext;                 /* Next element in list */
14056};
14057
14058/*
14059** The "context" argument for a installable function.  A pointer to an
14060** instance of this structure is the first argument to the routines used
14061** implement the SQL functions.
14062**
14063** There is a typedef for this structure in sqlite.h.  So all routines,
14064** even the public interface to SQLite, can use a pointer to this structure.
14065** But this file is the only place where the internal details of this
14066** structure are known.
14067**
14068** This structure is defined inside of vdbeInt.h because it uses substructures
14069** (Mem) which are only defined there.
14070*/
14071struct sqlite3_context {
14072  FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
14073  Mem s;                /* The return value is stored here */
14074  Mem *pMem;            /* Memory cell used to store aggregate context */
14075  CollSeq *pColl;       /* Collating sequence */
14076  Vdbe *pVdbe;          /* The VM that owns this context */
14077  int iOp;              /* Instruction number of OP_Function */
14078  int isError;          /* Error code returned by the function. */
14079  u8 skipFlag;          /* Skip skip accumulator loading if true */
14080  u8 fErrorOrAux;       /* isError!=0 or pVdbe->pAuxData modified */
14081};
14082
14083/*
14084** An Explain object accumulates indented output which is helpful
14085** in describing recursive data structures.
14086*/
14087struct Explain {
14088  Vdbe *pVdbe;       /* Attach the explanation to this Vdbe */
14089  StrAccum str;      /* The string being accumulated */
14090  int nIndent;       /* Number of elements in aIndent */
14091  u16 aIndent[100];  /* Levels of indentation */
14092  char zBase[100];   /* Initial space */
14093};
14094
14095/* A bitfield type for use inside of structures.  Always follow with :N where
14096** N is the number of bits.
14097*/
14098typedef unsigned bft;  /* Bit Field Type */
14099
14100/*
14101** An instance of the virtual machine.  This structure contains the complete
14102** state of the virtual machine.
14103**
14104** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
14105** is really a pointer to an instance of this structure.
14106**
14107** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
14108** any virtual table method invocations made by the vdbe program. It is
14109** set to 2 for xDestroy method calls and 1 for all other methods. This
14110** variable is used for two purposes: to allow xDestroy methods to execute
14111** "DROP TABLE" statements and to prevent some nasty side effects of
14112** malloc failure when SQLite is invoked recursively by a virtual table
14113** method function.
14114*/
14115struct Vdbe {
14116  sqlite3 *db;            /* The database connection that owns this statement */
14117  Op *aOp;                /* Space to hold the virtual machine's program */
14118  Mem *aMem;              /* The memory locations */
14119  Mem **apArg;            /* Arguments to currently executing user function */
14120  Mem *aColName;          /* Column names to return */
14121  Mem *pResultSet;        /* Pointer to an array of results */
14122  Parse *pParse;          /* Parsing context used to create this Vdbe */
14123  int nMem;               /* Number of memory locations currently allocated */
14124  int nOp;                /* Number of instructions in the program */
14125  int nCursor;            /* Number of slots in apCsr[] */
14126  u32 magic;              /* Magic number for sanity checking */
14127  char *zErrMsg;          /* Error message written here */
14128  Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
14129  VdbeCursor **apCsr;     /* One element of this array for each open cursor */
14130  Mem *aVar;              /* Values for the OP_Variable opcode. */
14131  char **azVar;           /* Name of variables */
14132  ynVar nVar;             /* Number of entries in aVar[] */
14133  ynVar nzVar;            /* Number of entries in azVar[] */
14134  u32 cacheCtr;           /* VdbeCursor row cache generation counter */
14135  int pc;                 /* The program counter */
14136  int rc;                 /* Value to return */
14137  u16 nResColumn;         /* Number of columns in one row of the result set */
14138  u8 errorAction;         /* Recovery action to do in case of an error */
14139  u8 minWriteFileFormat;  /* Minimum file format for writable database files */
14140  bft explain:2;          /* True if EXPLAIN present on SQL command */
14141  bft inVtabMethod:2;     /* See comments above */
14142  bft changeCntOn:1;      /* True to update the change-counter */
14143  bft expired:1;          /* True if the VM needs to be recompiled */
14144  bft runOnlyOnce:1;      /* Automatically expire on reset */
14145  bft usesStmtJournal:1;  /* True if uses a statement journal */
14146  bft readOnly:1;         /* True for statements that do not write */
14147  bft bIsReader:1;        /* True for statements that read */
14148  bft isPrepareV2:1;      /* True if prepared with prepare_v2() */
14149  bft doingRerun:1;       /* True if rerunning after an auto-reprepare */
14150  int nChange;            /* Number of db changes made since last reset */
14151  yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
14152  yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
14153  int iStatement;         /* Statement number (or 0 if has not opened stmt) */
14154  u32 aCounter[5];        /* Counters used by sqlite3_stmt_status() */
14155#ifndef SQLITE_OMIT_TRACE
14156  i64 startTime;          /* Time when query started - used for profiling */
14157#endif
14158  i64 iCurrentTime;       /* Value of julianday('now') for this statement */
14159  i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
14160  i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
14161  i64 nStmtDefImmCons;    /* Number of def. imm constraints when stmt started */
14162  char *zSql;             /* Text of the SQL statement that generated this */
14163  void *pFree;            /* Free this when deleting the vdbe */
14164#ifdef SQLITE_ENABLE_TREE_EXPLAIN
14165  Explain *pExplain;      /* The explainer */
14166  char *zExplain;         /* Explanation of data structures */
14167#endif
14168  VdbeFrame *pFrame;      /* Parent frame */
14169  VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
14170  int nFrame;             /* Number of frames in pFrame list */
14171  u32 expmask;            /* Binding to these vars invalidates VM */
14172  SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
14173  int nOnceFlag;          /* Size of array aOnceFlag[] */
14174  u8 *aOnceFlag;          /* Flags for OP_Once */
14175  AuxData *pAuxData;      /* Linked list of auxdata allocations */
14176};
14177
14178/*
14179** The following are allowed values for Vdbe.magic
14180*/
14181#define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
14182#define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
14183#define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
14184#define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
14185
14186/*
14187** Function prototypes
14188*/
14189SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
14190void sqliteVdbePopStack(Vdbe*,int);
14191SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
14192#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
14193SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
14194#endif
14195SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
14196SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
14197SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
14198SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
14199SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe*, int, int);
14200
14201int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
14202SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
14203SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
14204SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
14205SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
14206SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
14207SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
14208SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
14209SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
14210SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
14211SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
14212SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
14213SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
14214SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
14215SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
14216#ifdef SQLITE_OMIT_FLOATING_POINT
14217# define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
14218#else
14219SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
14220#endif
14221SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
14222SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
14223SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
14224SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
14225SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
14226SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
14227SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
14228SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
14229SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
14230SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
14231SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
14232SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,int,Mem*);
14233SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
14234SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
14235#define VdbeMemDynamic(X)  \
14236  (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
14237#define VdbeMemRelease(X)  \
14238  if( VdbeMemDynamic(X) ) sqlite3VdbeMemReleaseExternal(X);
14239SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
14240SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
14241SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
14242SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
14243SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
14244SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
14245SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
14246
14247SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, VdbeCursor *);
14248SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
14249SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
14250SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
14251SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
14252SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *, const VdbeCursor *, int *);
14253SQLITE_PRIVATE int sqlite3VdbeSorterWrite(sqlite3 *, const VdbeCursor *, Mem *);
14254SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
14255
14256#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
14257SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
14258SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
14259#else
14260# define sqlite3VdbeEnter(X)
14261# define sqlite3VdbeLeave(X)
14262#endif
14263
14264#ifdef SQLITE_DEBUG
14265SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
14266SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
14267#endif
14268
14269#ifndef SQLITE_OMIT_FOREIGN_KEY
14270SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
14271#else
14272# define sqlite3VdbeCheckFk(p,i) 0
14273#endif
14274
14275SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
14276#ifdef SQLITE_DEBUG
14277SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
14278SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
14279#endif
14280SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
14281
14282#ifndef SQLITE_OMIT_INCRBLOB
14283SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
14284  #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
14285#else
14286  #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
14287  #define ExpandBlob(P) SQLITE_OK
14288#endif
14289
14290#endif /* !defined(_VDBEINT_H_) */
14291
14292/************** End of vdbeInt.h *********************************************/
14293/************** Continuing where we left off in status.c *********************/
14294
14295/*
14296** Variables in which to record status information.
14297*/
14298typedef struct sqlite3StatType sqlite3StatType;
14299static SQLITE_WSD struct sqlite3StatType {
14300  int nowValue[10];         /* Current value */
14301  int mxValue[10];          /* Maximum value */
14302} sqlite3Stat = { {0,}, {0,} };
14303
14304
14305/* The "wsdStat" macro will resolve to the status information
14306** state vector.  If writable static data is unsupported on the target,
14307** we have to locate the state vector at run-time.  In the more common
14308** case where writable static data is supported, wsdStat can refer directly
14309** to the "sqlite3Stat" state vector declared above.
14310*/
14311#ifdef SQLITE_OMIT_WSD
14312# define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
14313# define wsdStat x[0]
14314#else
14315# define wsdStatInit
14316# define wsdStat sqlite3Stat
14317#endif
14318
14319/*
14320** Return the current value of a status parameter.
14321*/
14322SQLITE_PRIVATE int sqlite3StatusValue(int op){
14323  wsdStatInit;
14324  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
14325  return wsdStat.nowValue[op];
14326}
14327
14328/*
14329** Add N to the value of a status record.  It is assumed that the
14330** caller holds appropriate locks.
14331*/
14332SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
14333  wsdStatInit;
14334  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
14335  wsdStat.nowValue[op] += N;
14336  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
14337    wsdStat.mxValue[op] = wsdStat.nowValue[op];
14338  }
14339}
14340
14341/*
14342** Set the value of a status to X.
14343*/
14344SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
14345  wsdStatInit;
14346  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
14347  wsdStat.nowValue[op] = X;
14348  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
14349    wsdStat.mxValue[op] = wsdStat.nowValue[op];
14350  }
14351}
14352
14353/*
14354** Query status information.
14355**
14356** This implementation assumes that reading or writing an aligned
14357** 32-bit integer is an atomic operation.  If that assumption is not true,
14358** then this routine is not threadsafe.
14359*/
14360SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
14361  wsdStatInit;
14362  if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
14363    return SQLITE_MISUSE_BKPT;
14364  }
14365  *pCurrent = wsdStat.nowValue[op];
14366  *pHighwater = wsdStat.mxValue[op];
14367  if( resetFlag ){
14368    wsdStat.mxValue[op] = wsdStat.nowValue[op];
14369  }
14370  return SQLITE_OK;
14371}
14372
14373/*
14374** Query status information for a single database connection
14375*/
14376SQLITE_API int sqlite3_db_status(
14377  sqlite3 *db,          /* The database connection whose status is desired */
14378  int op,               /* Status verb */
14379  int *pCurrent,        /* Write current value here */
14380  int *pHighwater,      /* Write high-water mark here */
14381  int resetFlag         /* Reset high-water mark if true */
14382){
14383  int rc = SQLITE_OK;   /* Return code */
14384  sqlite3_mutex_enter(db->mutex);
14385  switch( op ){
14386    case SQLITE_DBSTATUS_LOOKASIDE_USED: {
14387      *pCurrent = db->lookaside.nOut;
14388      *pHighwater = db->lookaside.mxOut;
14389      if( resetFlag ){
14390        db->lookaside.mxOut = db->lookaside.nOut;
14391      }
14392      break;
14393    }
14394
14395    case SQLITE_DBSTATUS_LOOKASIDE_HIT:
14396    case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
14397    case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
14398      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
14399      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
14400      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
14401      assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
14402      assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
14403      *pCurrent = 0;
14404      *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
14405      if( resetFlag ){
14406        db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
14407      }
14408      break;
14409    }
14410
14411    /*
14412    ** Return an approximation for the amount of memory currently used
14413    ** by all pagers associated with the given database connection.  The
14414    ** highwater mark is meaningless and is returned as zero.
14415    */
14416    case SQLITE_DBSTATUS_CACHE_USED: {
14417      int totalUsed = 0;
14418      int i;
14419      sqlite3BtreeEnterAll(db);
14420      for(i=0; i<db->nDb; i++){
14421        Btree *pBt = db->aDb[i].pBt;
14422        if( pBt ){
14423          Pager *pPager = sqlite3BtreePager(pBt);
14424          totalUsed += sqlite3PagerMemUsed(pPager);
14425        }
14426      }
14427      sqlite3BtreeLeaveAll(db);
14428      *pCurrent = totalUsed;
14429      *pHighwater = 0;
14430      break;
14431    }
14432
14433    /*
14434    ** *pCurrent gets an accurate estimate of the amount of memory used
14435    ** to store the schema for all databases (main, temp, and any ATTACHed
14436    ** databases.  *pHighwater is set to zero.
14437    */
14438    case SQLITE_DBSTATUS_SCHEMA_USED: {
14439      int i;                      /* Used to iterate through schemas */
14440      int nByte = 0;              /* Used to accumulate return value */
14441
14442      sqlite3BtreeEnterAll(db);
14443      db->pnBytesFreed = &nByte;
14444      for(i=0; i<db->nDb; i++){
14445        Schema *pSchema = db->aDb[i].pSchema;
14446        if( ALWAYS(pSchema!=0) ){
14447          HashElem *p;
14448
14449          nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
14450              pSchema->tblHash.count
14451            + pSchema->trigHash.count
14452            + pSchema->idxHash.count
14453            + pSchema->fkeyHash.count
14454          );
14455          nByte += sqlite3MallocSize(pSchema->tblHash.ht);
14456          nByte += sqlite3MallocSize(pSchema->trigHash.ht);
14457          nByte += sqlite3MallocSize(pSchema->idxHash.ht);
14458          nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
14459
14460          for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
14461            sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
14462          }
14463          for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
14464            sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
14465          }
14466        }
14467      }
14468      db->pnBytesFreed = 0;
14469      sqlite3BtreeLeaveAll(db);
14470
14471      *pHighwater = 0;
14472      *pCurrent = nByte;
14473      break;
14474    }
14475
14476    /*
14477    ** *pCurrent gets an accurate estimate of the amount of memory used
14478    ** to store all prepared statements.
14479    ** *pHighwater is set to zero.
14480    */
14481    case SQLITE_DBSTATUS_STMT_USED: {
14482      struct Vdbe *pVdbe;         /* Used to iterate through VMs */
14483      int nByte = 0;              /* Used to accumulate return value */
14484
14485      db->pnBytesFreed = &nByte;
14486      for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
14487        sqlite3VdbeClearObject(db, pVdbe);
14488        sqlite3DbFree(db, pVdbe);
14489      }
14490      db->pnBytesFreed = 0;
14491
14492      *pHighwater = 0;
14493      *pCurrent = nByte;
14494
14495      break;
14496    }
14497
14498    /*
14499    ** Set *pCurrent to the total cache hits or misses encountered by all
14500    ** pagers the database handle is connected to. *pHighwater is always set
14501    ** to zero.
14502    */
14503    case SQLITE_DBSTATUS_CACHE_HIT:
14504    case SQLITE_DBSTATUS_CACHE_MISS:
14505    case SQLITE_DBSTATUS_CACHE_WRITE:{
14506      int i;
14507      int nRet = 0;
14508      assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
14509      assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
14510
14511      for(i=0; i<db->nDb; i++){
14512        if( db->aDb[i].pBt ){
14513          Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
14514          sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
14515        }
14516      }
14517      *pHighwater = 0;
14518      *pCurrent = nRet;
14519      break;
14520    }
14521
14522    /* Set *pCurrent to non-zero if there are unresolved deferred foreign
14523    ** key constraints.  Set *pCurrent to zero if all foreign key constraints
14524    ** have been satisfied.  The *pHighwater is always set to zero.
14525    */
14526    case SQLITE_DBSTATUS_DEFERRED_FKS: {
14527      *pHighwater = 0;
14528      *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
14529      break;
14530    }
14531
14532    default: {
14533      rc = SQLITE_ERROR;
14534    }
14535  }
14536  sqlite3_mutex_leave(db->mutex);
14537  return rc;
14538}
14539
14540/************** End of status.c **********************************************/
14541/************** Begin file date.c ********************************************/
14542/*
14543** 2003 October 31
14544**
14545** The author disclaims copyright to this source code.  In place of
14546** a legal notice, here is a blessing:
14547**
14548**    May you do good and not evil.
14549**    May you find forgiveness for yourself and forgive others.
14550**    May you share freely, never taking more than you give.
14551**
14552*************************************************************************
14553** This file contains the C functions that implement date and time
14554** functions for SQLite.
14555**
14556** There is only one exported symbol in this file - the function
14557** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
14558** All other code has file scope.
14559**
14560** SQLite processes all times and dates as Julian Day numbers.  The
14561** dates and times are stored as the number of days since noon
14562** in Greenwich on November 24, 4714 B.C. according to the Gregorian
14563** calendar system.
14564**
14565** 1970-01-01 00:00:00 is JD 2440587.5
14566** 2000-01-01 00:00:00 is JD 2451544.5
14567**
14568** This implemention requires years to be expressed as a 4-digit number
14569** which means that only dates between 0000-01-01 and 9999-12-31 can
14570** be represented, even though julian day numbers allow a much wider
14571** range of dates.
14572**
14573** The Gregorian calendar system is used for all dates and times,
14574** even those that predate the Gregorian calendar.  Historians usually
14575** use the Julian calendar for dates prior to 1582-10-15 and for some
14576** dates afterwards, depending on locale.  Beware of this difference.
14577**
14578** The conversion algorithms are implemented based on descriptions
14579** in the following text:
14580**
14581**      Jean Meeus
14582**      Astronomical Algorithms, 2nd Edition, 1998
14583**      ISBM 0-943396-61-1
14584**      Willmann-Bell, Inc
14585**      Richmond, Virginia (USA)
14586*/
14587/* #include <stdlib.h> */
14588/* #include <assert.h> */
14589#include <time.h>
14590
14591#ifndef SQLITE_OMIT_DATETIME_FUNCS
14592
14593
14594/*
14595** A structure for holding a single date and time.
14596*/
14597typedef struct DateTime DateTime;
14598struct DateTime {
14599  sqlite3_int64 iJD; /* The julian day number times 86400000 */
14600  int Y, M, D;       /* Year, month, and day */
14601  int h, m;          /* Hour and minutes */
14602  int tz;            /* Timezone offset in minutes */
14603  double s;          /* Seconds */
14604  char validYMD;     /* True (1) if Y,M,D are valid */
14605  char validHMS;     /* True (1) if h,m,s are valid */
14606  char validJD;      /* True (1) if iJD is valid */
14607  char validTZ;      /* True (1) if tz is valid */
14608};
14609
14610
14611/*
14612** Convert zDate into one or more integers.  Additional arguments
14613** come in groups of 5 as follows:
14614**
14615**       N       number of digits in the integer
14616**       min     minimum allowed value of the integer
14617**       max     maximum allowed value of the integer
14618**       nextC   first character after the integer
14619**       pVal    where to write the integers value.
14620**
14621** Conversions continue until one with nextC==0 is encountered.
14622** The function returns the number of successful conversions.
14623*/
14624static int getDigits(const char *zDate, ...){
14625  va_list ap;
14626  int val;
14627  int N;
14628  int min;
14629  int max;
14630  int nextC;
14631  int *pVal;
14632  int cnt = 0;
14633  va_start(ap, zDate);
14634  do{
14635    N = va_arg(ap, int);
14636    min = va_arg(ap, int);
14637    max = va_arg(ap, int);
14638    nextC = va_arg(ap, int);
14639    pVal = va_arg(ap, int*);
14640    val = 0;
14641    while( N-- ){
14642      if( !sqlite3Isdigit(*zDate) ){
14643        goto end_getDigits;
14644      }
14645      val = val*10 + *zDate - '0';
14646      zDate++;
14647    }
14648    if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
14649      goto end_getDigits;
14650    }
14651    *pVal = val;
14652    zDate++;
14653    cnt++;
14654  }while( nextC );
14655end_getDigits:
14656  va_end(ap);
14657  return cnt;
14658}
14659
14660/*
14661** Parse a timezone extension on the end of a date-time.
14662** The extension is of the form:
14663**
14664**        (+/-)HH:MM
14665**
14666** Or the "zulu" notation:
14667**
14668**        Z
14669**
14670** If the parse is successful, write the number of minutes
14671** of change in p->tz and return 0.  If a parser error occurs,
14672** return non-zero.
14673**
14674** A missing specifier is not considered an error.
14675*/
14676static int parseTimezone(const char *zDate, DateTime *p){
14677  int sgn = 0;
14678  int nHr, nMn;
14679  int c;
14680  while( sqlite3Isspace(*zDate) ){ zDate++; }
14681  p->tz = 0;
14682  c = *zDate;
14683  if( c=='-' ){
14684    sgn = -1;
14685  }else if( c=='+' ){
14686    sgn = +1;
14687  }else if( c=='Z' || c=='z' ){
14688    zDate++;
14689    goto zulu_time;
14690  }else{
14691    return c!=0;
14692  }
14693  zDate++;
14694  if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
14695    return 1;
14696  }
14697  zDate += 5;
14698  p->tz = sgn*(nMn + nHr*60);
14699zulu_time:
14700  while( sqlite3Isspace(*zDate) ){ zDate++; }
14701  return *zDate!=0;
14702}
14703
14704/*
14705** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
14706** The HH, MM, and SS must each be exactly 2 digits.  The
14707** fractional seconds FFFF can be one or more digits.
14708**
14709** Return 1 if there is a parsing error and 0 on success.
14710*/
14711static int parseHhMmSs(const char *zDate, DateTime *p){
14712  int h, m, s;
14713  double ms = 0.0;
14714  if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
14715    return 1;
14716  }
14717  zDate += 5;
14718  if( *zDate==':' ){
14719    zDate++;
14720    if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
14721      return 1;
14722    }
14723    zDate += 2;
14724    if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
14725      double rScale = 1.0;
14726      zDate++;
14727      while( sqlite3Isdigit(*zDate) ){
14728        ms = ms*10.0 + *zDate - '0';
14729        rScale *= 10.0;
14730        zDate++;
14731      }
14732      ms /= rScale;
14733    }
14734  }else{
14735    s = 0;
14736  }
14737  p->validJD = 0;
14738  p->validHMS = 1;
14739  p->h = h;
14740  p->m = m;
14741  p->s = s + ms;
14742  if( parseTimezone(zDate, p) ) return 1;
14743  p->validTZ = (p->tz!=0)?1:0;
14744  return 0;
14745}
14746
14747/*
14748** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
14749** that the YYYY-MM-DD is according to the Gregorian calendar.
14750**
14751** Reference:  Meeus page 61
14752*/
14753static void computeJD(DateTime *p){
14754  int Y, M, D, A, B, X1, X2;
14755
14756  if( p->validJD ) return;
14757  if( p->validYMD ){
14758    Y = p->Y;
14759    M = p->M;
14760    D = p->D;
14761  }else{
14762    Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
14763    M = 1;
14764    D = 1;
14765  }
14766  if( M<=2 ){
14767    Y--;
14768    M += 12;
14769  }
14770  A = Y/100;
14771  B = 2 - A + (A/4);
14772  X1 = 36525*(Y+4716)/100;
14773  X2 = 306001*(M+1)/10000;
14774  p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
14775  p->validJD = 1;
14776  if( p->validHMS ){
14777    p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
14778    if( p->validTZ ){
14779      p->iJD -= p->tz*60000;
14780      p->validYMD = 0;
14781      p->validHMS = 0;
14782      p->validTZ = 0;
14783    }
14784  }
14785}
14786
14787/*
14788** Parse dates of the form
14789**
14790**     YYYY-MM-DD HH:MM:SS.FFF
14791**     YYYY-MM-DD HH:MM:SS
14792**     YYYY-MM-DD HH:MM
14793**     YYYY-MM-DD
14794**
14795** Write the result into the DateTime structure and return 0
14796** on success and 1 if the input string is not a well-formed
14797** date.
14798*/
14799static int parseYyyyMmDd(const char *zDate, DateTime *p){
14800  int Y, M, D, neg;
14801
14802  if( zDate[0]=='-' ){
14803    zDate++;
14804    neg = 1;
14805  }else{
14806    neg = 0;
14807  }
14808  if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
14809    return 1;
14810  }
14811  zDate += 10;
14812  while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
14813  if( parseHhMmSs(zDate, p)==0 ){
14814    /* We got the time */
14815  }else if( *zDate==0 ){
14816    p->validHMS = 0;
14817  }else{
14818    return 1;
14819  }
14820  p->validJD = 0;
14821  p->validYMD = 1;
14822  p->Y = neg ? -Y : Y;
14823  p->M = M;
14824  p->D = D;
14825  if( p->validTZ ){
14826    computeJD(p);
14827  }
14828  return 0;
14829}
14830
14831/*
14832** Set the time to the current time reported by the VFS.
14833**
14834** Return the number of errors.
14835*/
14836static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
14837  p->iJD = sqlite3StmtCurrentTime(context);
14838  if( p->iJD>0 ){
14839    p->validJD = 1;
14840    return 0;
14841  }else{
14842    return 1;
14843  }
14844}
14845
14846/*
14847** Attempt to parse the given string into a Julian Day Number.  Return
14848** the number of errors.
14849**
14850** The following are acceptable forms for the input string:
14851**
14852**      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
14853**      DDDD.DD
14854**      now
14855**
14856** In the first form, the +/-HH:MM is always optional.  The fractional
14857** seconds extension (the ".FFF") is optional.  The seconds portion
14858** (":SS.FFF") is option.  The year and date can be omitted as long
14859** as there is a time string.  The time string can be omitted as long
14860** as there is a year and date.
14861*/
14862static int parseDateOrTime(
14863  sqlite3_context *context,
14864  const char *zDate,
14865  DateTime *p
14866){
14867  double r;
14868  if( parseYyyyMmDd(zDate,p)==0 ){
14869    return 0;
14870  }else if( parseHhMmSs(zDate, p)==0 ){
14871    return 0;
14872  }else if( sqlite3StrICmp(zDate,"now")==0){
14873    return setDateTimeToCurrent(context, p);
14874  }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
14875    p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
14876    p->validJD = 1;
14877    return 0;
14878  }
14879  return 1;
14880}
14881
14882/*
14883** Compute the Year, Month, and Day from the julian day number.
14884*/
14885static void computeYMD(DateTime *p){
14886  int Z, A, B, C, D, E, X1;
14887  if( p->validYMD ) return;
14888  if( !p->validJD ){
14889    p->Y = 2000;
14890    p->M = 1;
14891    p->D = 1;
14892  }else{
14893    Z = (int)((p->iJD + 43200000)/86400000);
14894    A = (int)((Z - 1867216.25)/36524.25);
14895    A = Z + 1 + A - (A/4);
14896    B = A + 1524;
14897    C = (int)((B - 122.1)/365.25);
14898    D = (36525*C)/100;
14899    E = (int)((B-D)/30.6001);
14900    X1 = (int)(30.6001*E);
14901    p->D = B - D - X1;
14902    p->M = E<14 ? E-1 : E-13;
14903    p->Y = p->M>2 ? C - 4716 : C - 4715;
14904  }
14905  p->validYMD = 1;
14906}
14907
14908/*
14909** Compute the Hour, Minute, and Seconds from the julian day number.
14910*/
14911static void computeHMS(DateTime *p){
14912  int s;
14913  if( p->validHMS ) return;
14914  computeJD(p);
14915  s = (int)((p->iJD + 43200000) % 86400000);
14916  p->s = s/1000.0;
14917  s = (int)p->s;
14918  p->s -= s;
14919  p->h = s/3600;
14920  s -= p->h*3600;
14921  p->m = s/60;
14922  p->s += s - p->m*60;
14923  p->validHMS = 1;
14924}
14925
14926/*
14927** Compute both YMD and HMS
14928*/
14929static void computeYMD_HMS(DateTime *p){
14930  computeYMD(p);
14931  computeHMS(p);
14932}
14933
14934/*
14935** Clear the YMD and HMS and the TZ
14936*/
14937static void clearYMD_HMS_TZ(DateTime *p){
14938  p->validYMD = 0;
14939  p->validHMS = 0;
14940  p->validTZ = 0;
14941}
14942
14943/*
14944** On recent Windows platforms, the localtime_s() function is available
14945** as part of the "Secure CRT". It is essentially equivalent to
14946** localtime_r() available under most POSIX platforms, except that the
14947** order of the parameters is reversed.
14948**
14949** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
14950**
14951** If the user has not indicated to use localtime_r() or localtime_s()
14952** already, check for an MSVC build environment that provides
14953** localtime_s().
14954*/
14955#if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
14956     defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
14957#define HAVE_LOCALTIME_S 1
14958#endif
14959
14960#ifndef SQLITE_OMIT_LOCALTIME
14961/*
14962** The following routine implements the rough equivalent of localtime_r()
14963** using whatever operating-system specific localtime facility that
14964** is available.  This routine returns 0 on success and
14965** non-zero on any kind of error.
14966**
14967** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
14968** routine will always fail.
14969**
14970** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
14971** library function localtime_r() is used to assist in the calculation of
14972** local time.
14973*/
14974static int osLocaltime(time_t *t, struct tm *pTm){
14975  int rc;
14976#if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
14977      && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
14978  struct tm *pX;
14979#if SQLITE_THREADSAFE>0
14980  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14981#endif
14982  sqlite3_mutex_enter(mutex);
14983  pX = localtime(t);
14984#ifndef SQLITE_OMIT_BUILTIN_TEST
14985  if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
14986#endif
14987  if( pX ) *pTm = *pX;
14988  sqlite3_mutex_leave(mutex);
14989  rc = pX==0;
14990#else
14991#ifndef SQLITE_OMIT_BUILTIN_TEST
14992  if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
14993#endif
14994#if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
14995  rc = localtime_r(t, pTm)==0;
14996#else
14997  rc = localtime_s(pTm, t);
14998#endif /* HAVE_LOCALTIME_R */
14999#endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
15000  return rc;
15001}
15002#endif /* SQLITE_OMIT_LOCALTIME */
15003
15004
15005#ifndef SQLITE_OMIT_LOCALTIME
15006/*
15007** Compute the difference (in milliseconds) between localtime and UTC
15008** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
15009** return this value and set *pRc to SQLITE_OK.
15010**
15011** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
15012** is undefined in this case.
15013*/
15014static sqlite3_int64 localtimeOffset(
15015  DateTime *p,                    /* Date at which to calculate offset */
15016  sqlite3_context *pCtx,          /* Write error here if one occurs */
15017  int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */
15018){
15019  DateTime x, y;
15020  time_t t;
15021  struct tm sLocal;
15022
15023  /* Initialize the contents of sLocal to avoid a compiler warning. */
15024  memset(&sLocal, 0, sizeof(sLocal));
15025
15026  x = *p;
15027  computeYMD_HMS(&x);
15028  if( x.Y<1971 || x.Y>=2038 ){
15029    /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
15030    ** works for years between 1970 and 2037. For dates outside this range,
15031    ** SQLite attempts to map the year into an equivalent year within this
15032    ** range, do the calculation, then map the year back.
15033    */
15034    x.Y = 2000;
15035    x.M = 1;
15036    x.D = 1;
15037    x.h = 0;
15038    x.m = 0;
15039    x.s = 0.0;
15040  } else {
15041    int s = (int)(x.s + 0.5);
15042    x.s = s;
15043  }
15044  x.tz = 0;
15045  x.validJD = 0;
15046  computeJD(&x);
15047  t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
15048  if( osLocaltime(&t, &sLocal) ){
15049    sqlite3_result_error(pCtx, "local time unavailable", -1);
15050    *pRc = SQLITE_ERROR;
15051    return 0;
15052  }
15053  y.Y = sLocal.tm_year + 1900;
15054  y.M = sLocal.tm_mon + 1;
15055  y.D = sLocal.tm_mday;
15056  y.h = sLocal.tm_hour;
15057  y.m = sLocal.tm_min;
15058  y.s = sLocal.tm_sec;
15059  y.validYMD = 1;
15060  y.validHMS = 1;
15061  y.validJD = 0;
15062  y.validTZ = 0;
15063  computeJD(&y);
15064  *pRc = SQLITE_OK;
15065  return y.iJD - x.iJD;
15066}
15067#endif /* SQLITE_OMIT_LOCALTIME */
15068
15069/*
15070** Process a modifier to a date-time stamp.  The modifiers are
15071** as follows:
15072**
15073**     NNN days
15074**     NNN hours
15075**     NNN minutes
15076**     NNN.NNNN seconds
15077**     NNN months
15078**     NNN years
15079**     start of month
15080**     start of year
15081**     start of week
15082**     start of day
15083**     weekday N
15084**     unixepoch
15085**     localtime
15086**     utc
15087**
15088** Return 0 on success and 1 if there is any kind of error. If the error
15089** is in a system call (i.e. localtime()), then an error message is written
15090** to context pCtx. If the error is an unrecognized modifier, no error is
15091** written to pCtx.
15092*/
15093static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
15094  int rc = 1;
15095  int n;
15096  double r;
15097  char *z, zBuf[30];
15098  z = zBuf;
15099  for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
15100    z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
15101  }
15102  z[n] = 0;
15103  switch( z[0] ){
15104#ifndef SQLITE_OMIT_LOCALTIME
15105    case 'l': {
15106      /*    localtime
15107      **
15108      ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
15109      ** show local time.
15110      */
15111      if( strcmp(z, "localtime")==0 ){
15112        computeJD(p);
15113        p->iJD += localtimeOffset(p, pCtx, &rc);
15114        clearYMD_HMS_TZ(p);
15115      }
15116      break;
15117    }
15118#endif
15119    case 'u': {
15120      /*
15121      **    unixepoch
15122      **
15123      ** Treat the current value of p->iJD as the number of
15124      ** seconds since 1970.  Convert to a real julian day number.
15125      */
15126      if( strcmp(z, "unixepoch")==0 && p->validJD ){
15127        p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
15128        clearYMD_HMS_TZ(p);
15129        rc = 0;
15130      }
15131#ifndef SQLITE_OMIT_LOCALTIME
15132      else if( strcmp(z, "utc")==0 ){
15133        sqlite3_int64 c1;
15134        computeJD(p);
15135        c1 = localtimeOffset(p, pCtx, &rc);
15136        if( rc==SQLITE_OK ){
15137          p->iJD -= c1;
15138          clearYMD_HMS_TZ(p);
15139          p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
15140        }
15141      }
15142#endif
15143      break;
15144    }
15145    case 'w': {
15146      /*
15147      **    weekday N
15148      **
15149      ** Move the date to the same time on the next occurrence of
15150      ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
15151      ** date is already on the appropriate weekday, this is a no-op.
15152      */
15153      if( strncmp(z, "weekday ", 8)==0
15154               && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
15155               && (n=(int)r)==r && n>=0 && r<7 ){
15156        sqlite3_int64 Z;
15157        computeYMD_HMS(p);
15158        p->validTZ = 0;
15159        p->validJD = 0;
15160        computeJD(p);
15161        Z = ((p->iJD + 129600000)/86400000) % 7;
15162        if( Z>n ) Z -= 7;
15163        p->iJD += (n - Z)*86400000;
15164        clearYMD_HMS_TZ(p);
15165        rc = 0;
15166      }
15167      break;
15168    }
15169    case 's': {
15170      /*
15171      **    start of TTTTT
15172      **
15173      ** Move the date backwards to the beginning of the current day,
15174      ** or month or year.
15175      */
15176      if( strncmp(z, "start of ", 9)!=0 ) break;
15177      z += 9;
15178      computeYMD(p);
15179      p->validHMS = 1;
15180      p->h = p->m = 0;
15181      p->s = 0.0;
15182      p->validTZ = 0;
15183      p->validJD = 0;
15184      if( strcmp(z,"month")==0 ){
15185        p->D = 1;
15186        rc = 0;
15187      }else if( strcmp(z,"year")==0 ){
15188        computeYMD(p);
15189        p->M = 1;
15190        p->D = 1;
15191        rc = 0;
15192      }else if( strcmp(z,"day")==0 ){
15193        rc = 0;
15194      }
15195      break;
15196    }
15197    case '+':
15198    case '-':
15199    case '0':
15200    case '1':
15201    case '2':
15202    case '3':
15203    case '4':
15204    case '5':
15205    case '6':
15206    case '7':
15207    case '8':
15208    case '9': {
15209      double rRounder;
15210      for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
15211      if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
15212        rc = 1;
15213        break;
15214      }
15215      if( z[n]==':' ){
15216        /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
15217        ** specified number of hours, minutes, seconds, and fractional seconds
15218        ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
15219        ** omitted.
15220        */
15221        const char *z2 = z;
15222        DateTime tx;
15223        sqlite3_int64 day;
15224        if( !sqlite3Isdigit(*z2) ) z2++;
15225        memset(&tx, 0, sizeof(tx));
15226        if( parseHhMmSs(z2, &tx) ) break;
15227        computeJD(&tx);
15228        tx.iJD -= 43200000;
15229        day = tx.iJD/86400000;
15230        tx.iJD -= day*86400000;
15231        if( z[0]=='-' ) tx.iJD = -tx.iJD;
15232        computeJD(p);
15233        clearYMD_HMS_TZ(p);
15234        p->iJD += tx.iJD;
15235        rc = 0;
15236        break;
15237      }
15238      z += n;
15239      while( sqlite3Isspace(*z) ) z++;
15240      n = sqlite3Strlen30(z);
15241      if( n>10 || n<3 ) break;
15242      if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
15243      computeJD(p);
15244      rc = 0;
15245      rRounder = r<0 ? -0.5 : +0.5;
15246      if( n==3 && strcmp(z,"day")==0 ){
15247        p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
15248      }else if( n==4 && strcmp(z,"hour")==0 ){
15249        p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
15250      }else if( n==6 && strcmp(z,"minute")==0 ){
15251        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
15252      }else if( n==6 && strcmp(z,"second")==0 ){
15253        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
15254      }else if( n==5 && strcmp(z,"month")==0 ){
15255        int x, y;
15256        computeYMD_HMS(p);
15257        p->M += (int)r;
15258        x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
15259        p->Y += x;
15260        p->M -= x*12;
15261        p->validJD = 0;
15262        computeJD(p);
15263        y = (int)r;
15264        if( y!=r ){
15265          p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
15266        }
15267      }else if( n==4 && strcmp(z,"year")==0 ){
15268        int y = (int)r;
15269        computeYMD_HMS(p);
15270        p->Y += y;
15271        p->validJD = 0;
15272        computeJD(p);
15273        if( y!=r ){
15274          p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
15275        }
15276      }else{
15277        rc = 1;
15278      }
15279      clearYMD_HMS_TZ(p);
15280      break;
15281    }
15282    default: {
15283      break;
15284    }
15285  }
15286  return rc;
15287}
15288
15289/*
15290** Process time function arguments.  argv[0] is a date-time stamp.
15291** argv[1] and following are modifiers.  Parse them all and write
15292** the resulting time into the DateTime structure p.  Return 0
15293** on success and 1 if there are any errors.
15294**
15295** If there are zero parameters (if even argv[0] is undefined)
15296** then assume a default value of "now" for argv[0].
15297*/
15298static int isDate(
15299  sqlite3_context *context,
15300  int argc,
15301  sqlite3_value **argv,
15302  DateTime *p
15303){
15304  int i;
15305  const unsigned char *z;
15306  int eType;
15307  memset(p, 0, sizeof(*p));
15308  if( argc==0 ){
15309    return setDateTimeToCurrent(context, p);
15310  }
15311  if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
15312                   || eType==SQLITE_INTEGER ){
15313    p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
15314    p->validJD = 1;
15315  }else{
15316    z = sqlite3_value_text(argv[0]);
15317    if( !z || parseDateOrTime(context, (char*)z, p) ){
15318      return 1;
15319    }
15320  }
15321  for(i=1; i<argc; i++){
15322    z = sqlite3_value_text(argv[i]);
15323    if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
15324  }
15325  return 0;
15326}
15327
15328
15329/*
15330** The following routines implement the various date and time functions
15331** of SQLite.
15332*/
15333
15334/*
15335**    julianday( TIMESTRING, MOD, MOD, ...)
15336**
15337** Return the julian day number of the date specified in the arguments
15338*/
15339static void juliandayFunc(
15340  sqlite3_context *context,
15341  int argc,
15342  sqlite3_value **argv
15343){
15344  DateTime x;
15345  if( isDate(context, argc, argv, &x)==0 ){
15346    computeJD(&x);
15347    sqlite3_result_double(context, x.iJD/86400000.0);
15348  }
15349}
15350
15351/*
15352**    datetime( TIMESTRING, MOD, MOD, ...)
15353**
15354** Return YYYY-MM-DD HH:MM:SS
15355*/
15356static void datetimeFunc(
15357  sqlite3_context *context,
15358  int argc,
15359  sqlite3_value **argv
15360){
15361  DateTime x;
15362  if( isDate(context, argc, argv, &x)==0 ){
15363    char zBuf[100];
15364    computeYMD_HMS(&x);
15365    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
15366                     x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
15367    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
15368  }
15369}
15370
15371/*
15372**    time( TIMESTRING, MOD, MOD, ...)
15373**
15374** Return HH:MM:SS
15375*/
15376static void timeFunc(
15377  sqlite3_context *context,
15378  int argc,
15379  sqlite3_value **argv
15380){
15381  DateTime x;
15382  if( isDate(context, argc, argv, &x)==0 ){
15383    char zBuf[100];
15384    computeHMS(&x);
15385    sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
15386    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
15387  }
15388}
15389
15390/*
15391**    date( TIMESTRING, MOD, MOD, ...)
15392**
15393** Return YYYY-MM-DD
15394*/
15395static void dateFunc(
15396  sqlite3_context *context,
15397  int argc,
15398  sqlite3_value **argv
15399){
15400  DateTime x;
15401  if( isDate(context, argc, argv, &x)==0 ){
15402    char zBuf[100];
15403    computeYMD(&x);
15404    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
15405    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
15406  }
15407}
15408
15409/*
15410**    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
15411**
15412** Return a string described by FORMAT.  Conversions as follows:
15413**
15414**   %d  day of month
15415**   %f  ** fractional seconds  SS.SSS
15416**   %H  hour 00-24
15417**   %j  day of year 000-366
15418**   %J  ** Julian day number
15419**   %m  month 01-12
15420**   %M  minute 00-59
15421**   %s  seconds since 1970-01-01
15422**   %S  seconds 00-59
15423**   %w  day of week 0-6  sunday==0
15424**   %W  week of year 00-53
15425**   %Y  year 0000-9999
15426**   %%  %
15427*/
15428static void strftimeFunc(
15429  sqlite3_context *context,
15430  int argc,
15431  sqlite3_value **argv
15432){
15433  DateTime x;
15434  u64 n;
15435  size_t i,j;
15436  char *z;
15437  sqlite3 *db;
15438  const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
15439  char zBuf[100];
15440  if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
15441  db = sqlite3_context_db_handle(context);
15442  for(i=0, n=1; zFmt[i]; i++, n++){
15443    if( zFmt[i]=='%' ){
15444      switch( zFmt[i+1] ){
15445        case 'd':
15446        case 'H':
15447        case 'm':
15448        case 'M':
15449        case 'S':
15450        case 'W':
15451          n++;
15452          /* fall thru */
15453        case 'w':
15454        case '%':
15455          break;
15456        case 'f':
15457          n += 8;
15458          break;
15459        case 'j':
15460          n += 3;
15461          break;
15462        case 'Y':
15463          n += 8;
15464          break;
15465        case 's':
15466        case 'J':
15467          n += 50;
15468          break;
15469        default:
15470          return;  /* ERROR.  return a NULL */
15471      }
15472      i++;
15473    }
15474  }
15475  testcase( n==sizeof(zBuf)-1 );
15476  testcase( n==sizeof(zBuf) );
15477  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
15478  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
15479  if( n<sizeof(zBuf) ){
15480    z = zBuf;
15481  }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
15482    sqlite3_result_error_toobig(context);
15483    return;
15484  }else{
15485    z = sqlite3DbMallocRaw(db, (int)n);
15486    if( z==0 ){
15487      sqlite3_result_error_nomem(context);
15488      return;
15489    }
15490  }
15491  computeJD(&x);
15492  computeYMD_HMS(&x);
15493  for(i=j=0; zFmt[i]; i++){
15494    if( zFmt[i]!='%' ){
15495      z[j++] = zFmt[i];
15496    }else{
15497      i++;
15498      switch( zFmt[i] ){
15499        case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
15500        case 'f': {
15501          double s = x.s;
15502          if( s>59.999 ) s = 59.999;
15503          sqlite3_snprintf(7, &z[j],"%06.3f", s);
15504          j += sqlite3Strlen30(&z[j]);
15505          break;
15506        }
15507        case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
15508        case 'W': /* Fall thru */
15509        case 'j': {
15510          int nDay;             /* Number of days since 1st day of year */
15511          DateTime y = x;
15512          y.validJD = 0;
15513          y.M = 1;
15514          y.D = 1;
15515          computeJD(&y);
15516          nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
15517          if( zFmt[i]=='W' ){
15518            int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
15519            wd = (int)(((x.iJD+43200000)/86400000)%7);
15520            sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
15521            j += 2;
15522          }else{
15523            sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
15524            j += 3;
15525          }
15526          break;
15527        }
15528        case 'J': {
15529          sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
15530          j+=sqlite3Strlen30(&z[j]);
15531          break;
15532        }
15533        case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
15534        case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
15535        case 's': {
15536          sqlite3_snprintf(30,&z[j],"%lld",
15537                           (i64)(x.iJD/1000 - 21086676*(i64)10000));
15538          j += sqlite3Strlen30(&z[j]);
15539          break;
15540        }
15541        case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
15542        case 'w': {
15543          z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
15544          break;
15545        }
15546        case 'Y': {
15547          sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
15548          break;
15549        }
15550        default:   z[j++] = '%'; break;
15551      }
15552    }
15553  }
15554  z[j] = 0;
15555  sqlite3_result_text(context, z, -1,
15556                      z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
15557}
15558
15559/*
15560** current_time()
15561**
15562** This function returns the same value as time('now').
15563*/
15564static void ctimeFunc(
15565  sqlite3_context *context,
15566  int NotUsed,
15567  sqlite3_value **NotUsed2
15568){
15569  UNUSED_PARAMETER2(NotUsed, NotUsed2);
15570  timeFunc(context, 0, 0);
15571}
15572
15573/*
15574** current_date()
15575**
15576** This function returns the same value as date('now').
15577*/
15578static void cdateFunc(
15579  sqlite3_context *context,
15580  int NotUsed,
15581  sqlite3_value **NotUsed2
15582){
15583  UNUSED_PARAMETER2(NotUsed, NotUsed2);
15584  dateFunc(context, 0, 0);
15585}
15586
15587/*
15588** current_timestamp()
15589**
15590** This function returns the same value as datetime('now').
15591*/
15592static void ctimestampFunc(
15593  sqlite3_context *context,
15594  int NotUsed,
15595  sqlite3_value **NotUsed2
15596){
15597  UNUSED_PARAMETER2(NotUsed, NotUsed2);
15598  datetimeFunc(context, 0, 0);
15599}
15600#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
15601
15602#ifdef SQLITE_OMIT_DATETIME_FUNCS
15603/*
15604** If the library is compiled to omit the full-scale date and time
15605** handling (to get a smaller binary), the following minimal version
15606** of the functions current_time(), current_date() and current_timestamp()
15607** are included instead. This is to support column declarations that
15608** include "DEFAULT CURRENT_TIME" etc.
15609**
15610** This function uses the C-library functions time(), gmtime()
15611** and strftime(). The format string to pass to strftime() is supplied
15612** as the user-data for the function.
15613*/
15614static void currentTimeFunc(
15615  sqlite3_context *context,
15616  int argc,
15617  sqlite3_value **argv
15618){
15619  time_t t;
15620  char *zFormat = (char *)sqlite3_user_data(context);
15621  sqlite3 *db;
15622  sqlite3_int64 iT;
15623  struct tm *pTm;
15624  struct tm sNow;
15625  char zBuf[20];
15626
15627  UNUSED_PARAMETER(argc);
15628  UNUSED_PARAMETER(argv);
15629
15630  iT = sqlite3StmtCurrentTime(context);
15631  if( iT<=0 ) return;
15632  t = iT/1000 - 10000*(sqlite3_int64)21086676;
15633#ifdef HAVE_GMTIME_R
15634  pTm = gmtime_r(&t, &sNow);
15635#else
15636  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
15637  pTm = gmtime(&t);
15638  if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
15639  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
15640#endif
15641  if( pTm ){
15642    strftime(zBuf, 20, zFormat, &sNow);
15643    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
15644  }
15645}
15646#endif
15647
15648/*
15649** This function registered all of the above C functions as SQL
15650** functions.  This should be the only routine in this file with
15651** external linkage.
15652*/
15653SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
15654  static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
15655#ifndef SQLITE_OMIT_DATETIME_FUNCS
15656    FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
15657    FUNCTION(date,             -1, 0, 0, dateFunc      ),
15658    FUNCTION(time,             -1, 0, 0, timeFunc      ),
15659    FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
15660    FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
15661    FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
15662    FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
15663    FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
15664#else
15665    STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
15666    STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
15667    STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
15668#endif
15669  };
15670  int i;
15671  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
15672  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
15673
15674  for(i=0; i<ArraySize(aDateTimeFuncs); i++){
15675    sqlite3FuncDefInsert(pHash, &aFunc[i]);
15676  }
15677}
15678
15679/************** End of date.c ************************************************/
15680/************** Begin file os.c **********************************************/
15681/*
15682** 2005 November 29
15683**
15684** The author disclaims copyright to this source code.  In place of
15685** a legal notice, here is a blessing:
15686**
15687**    May you do good and not evil.
15688**    May you find forgiveness for yourself and forgive others.
15689**    May you share freely, never taking more than you give.
15690**
15691******************************************************************************
15692**
15693** This file contains OS interface code that is common to all
15694** architectures.
15695*/
15696#define _SQLITE_OS_C_ 1
15697#undef _SQLITE_OS_C_
15698
15699/*
15700** The default SQLite sqlite3_vfs implementations do not allocate
15701** memory (actually, os_unix.c allocates a small amount of memory
15702** from within OsOpen()), but some third-party implementations may.
15703** So we test the effects of a malloc() failing and the sqlite3OsXXX()
15704** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
15705**
15706** The following functions are instrumented for malloc() failure
15707** testing:
15708**
15709**     sqlite3OsRead()
15710**     sqlite3OsWrite()
15711**     sqlite3OsSync()
15712**     sqlite3OsFileSize()
15713**     sqlite3OsLock()
15714**     sqlite3OsCheckReservedLock()
15715**     sqlite3OsFileControl()
15716**     sqlite3OsShmMap()
15717**     sqlite3OsOpen()
15718**     sqlite3OsDelete()
15719**     sqlite3OsAccess()
15720**     sqlite3OsFullPathname()
15721**
15722*/
15723#if defined(SQLITE_TEST)
15724SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
15725  #define DO_OS_MALLOC_TEST(x)                                       \
15726  if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
15727    void *pTstAlloc = sqlite3Malloc(10);                             \
15728    if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
15729    sqlite3_free(pTstAlloc);                                         \
15730  }
15731#else
15732  #define DO_OS_MALLOC_TEST(x)
15733#endif
15734
15735/*
15736** The following routines are convenience wrappers around methods
15737** of the sqlite3_file object.  This is mostly just syntactic sugar. All
15738** of this would be completely automatic if SQLite were coded using
15739** C++ instead of plain old C.
15740*/
15741SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
15742  int rc = SQLITE_OK;
15743  if( pId->pMethods ){
15744    rc = pId->pMethods->xClose(pId);
15745    pId->pMethods = 0;
15746  }
15747  return rc;
15748}
15749SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
15750  DO_OS_MALLOC_TEST(id);
15751  return id->pMethods->xRead(id, pBuf, amt, offset);
15752}
15753SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
15754  DO_OS_MALLOC_TEST(id);
15755  return id->pMethods->xWrite(id, pBuf, amt, offset);
15756}
15757SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
15758  return id->pMethods->xTruncate(id, size);
15759}
15760SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
15761  DO_OS_MALLOC_TEST(id);
15762  return id->pMethods->xSync(id, flags);
15763}
15764SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
15765  DO_OS_MALLOC_TEST(id);
15766  return id->pMethods->xFileSize(id, pSize);
15767}
15768SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
15769  DO_OS_MALLOC_TEST(id);
15770  return id->pMethods->xLock(id, lockType);
15771}
15772SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
15773  return id->pMethods->xUnlock(id, lockType);
15774}
15775SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
15776  DO_OS_MALLOC_TEST(id);
15777  return id->pMethods->xCheckReservedLock(id, pResOut);
15778}
15779
15780/*
15781** Use sqlite3OsFileControl() when we are doing something that might fail
15782** and we need to know about the failures.  Use sqlite3OsFileControlHint()
15783** when simply tossing information over the wall to the VFS and we do not
15784** really care if the VFS receives and understands the information since it
15785** is only a hint and can be safely ignored.  The sqlite3OsFileControlHint()
15786** routine has no return value since the return value would be meaningless.
15787*/
15788SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
15789#ifdef SQLITE_TEST
15790  if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
15791    /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
15792    ** is using a regular VFS, it is called after the corresponding
15793    ** transaction has been committed. Injecting a fault at this point
15794    ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
15795    ** but the transaction is committed anyway.
15796    **
15797    ** The core must call OsFileControl() though, not OsFileControlHint(),
15798    ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
15799    ** means the commit really has failed and an error should be returned
15800    ** to the user.  */
15801    DO_OS_MALLOC_TEST(id);
15802  }
15803#endif
15804  return id->pMethods->xFileControl(id, op, pArg);
15805}
15806SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
15807  (void)id->pMethods->xFileControl(id, op, pArg);
15808}
15809
15810SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
15811  int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
15812  return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
15813}
15814SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
15815  return id->pMethods->xDeviceCharacteristics(id);
15816}
15817SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
15818  return id->pMethods->xShmLock(id, offset, n, flags);
15819}
15820SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
15821  id->pMethods->xShmBarrier(id);
15822}
15823SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
15824  return id->pMethods->xShmUnmap(id, deleteFlag);
15825}
15826SQLITE_PRIVATE int sqlite3OsShmMap(
15827  sqlite3_file *id,               /* Database file handle */
15828  int iPage,
15829  int pgsz,
15830  int bExtend,                    /* True to extend file if necessary */
15831  void volatile **pp              /* OUT: Pointer to mapping */
15832){
15833  DO_OS_MALLOC_TEST(id);
15834  return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
15835}
15836
15837#if SQLITE_MAX_MMAP_SIZE>0
15838/* The real implementation of xFetch and xUnfetch */
15839SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
15840  DO_OS_MALLOC_TEST(id);
15841  return id->pMethods->xFetch(id, iOff, iAmt, pp);
15842}
15843SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
15844  return id->pMethods->xUnfetch(id, iOff, p);
15845}
15846#else
15847/* No-op stubs to use when memory-mapped I/O is disabled */
15848SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
15849  *pp = 0;
15850  return SQLITE_OK;
15851}
15852SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
15853  return SQLITE_OK;
15854}
15855#endif
15856
15857/*
15858** The next group of routines are convenience wrappers around the
15859** VFS methods.
15860*/
15861SQLITE_PRIVATE int sqlite3OsOpen(
15862  sqlite3_vfs *pVfs,
15863  const char *zPath,
15864  sqlite3_file *pFile,
15865  int flags,
15866  int *pFlagsOut
15867){
15868  int rc;
15869  DO_OS_MALLOC_TEST(0);
15870  /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
15871  ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
15872  ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
15873  ** reaching the VFS. */
15874  rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
15875  assert( rc==SQLITE_OK || pFile->pMethods==0 );
15876  return rc;
15877}
15878SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
15879  DO_OS_MALLOC_TEST(0);
15880  assert( dirSync==0 || dirSync==1 );
15881  return pVfs->xDelete(pVfs, zPath, dirSync);
15882}
15883SQLITE_PRIVATE int sqlite3OsAccess(
15884  sqlite3_vfs *pVfs,
15885  const char *zPath,
15886  int flags,
15887  int *pResOut
15888){
15889  DO_OS_MALLOC_TEST(0);
15890  return pVfs->xAccess(pVfs, zPath, flags, pResOut);
15891}
15892SQLITE_PRIVATE int sqlite3OsFullPathname(
15893  sqlite3_vfs *pVfs,
15894  const char *zPath,
15895  int nPathOut,
15896  char *zPathOut
15897){
15898  DO_OS_MALLOC_TEST(0);
15899  zPathOut[0] = 0;
15900  return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
15901}
15902#ifndef SQLITE_OMIT_LOAD_EXTENSION
15903SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
15904  return pVfs->xDlOpen(pVfs, zPath);
15905}
15906SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
15907  pVfs->xDlError(pVfs, nByte, zBufOut);
15908}
15909SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
15910  return pVfs->xDlSym(pVfs, pHdle, zSym);
15911}
15912SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
15913  pVfs->xDlClose(pVfs, pHandle);
15914}
15915#endif /* SQLITE_OMIT_LOAD_EXTENSION */
15916SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
15917  return pVfs->xRandomness(pVfs, nByte, zBufOut);
15918}
15919SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
15920  return pVfs->xSleep(pVfs, nMicro);
15921}
15922SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
15923  int rc;
15924  /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
15925  ** method to get the current date and time if that method is available
15926  ** (if iVersion is 2 or greater and the function pointer is not NULL) and
15927  ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
15928  ** unavailable.
15929  */
15930  if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
15931    rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
15932  }else{
15933    double r;
15934    rc = pVfs->xCurrentTime(pVfs, &r);
15935    *pTimeOut = (sqlite3_int64)(r*86400000.0);
15936  }
15937  return rc;
15938}
15939
15940SQLITE_PRIVATE int sqlite3OsOpenMalloc(
15941  sqlite3_vfs *pVfs,
15942  const char *zFile,
15943  sqlite3_file **ppFile,
15944  int flags,
15945  int *pOutFlags
15946){
15947  int rc = SQLITE_NOMEM;
15948  sqlite3_file *pFile;
15949  pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
15950  if( pFile ){
15951    rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
15952    if( rc!=SQLITE_OK ){
15953      sqlite3_free(pFile);
15954    }else{
15955      *ppFile = pFile;
15956    }
15957  }
15958  return rc;
15959}
15960SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
15961  int rc = SQLITE_OK;
15962  assert( pFile );
15963  rc = sqlite3OsClose(pFile);
15964  sqlite3_free(pFile);
15965  return rc;
15966}
15967
15968/*
15969** This function is a wrapper around the OS specific implementation of
15970** sqlite3_os_init(). The purpose of the wrapper is to provide the
15971** ability to simulate a malloc failure, so that the handling of an
15972** error in sqlite3_os_init() by the upper layers can be tested.
15973*/
15974SQLITE_PRIVATE int sqlite3OsInit(void){
15975  void *p = sqlite3_malloc(10);
15976  if( p==0 ) return SQLITE_NOMEM;
15977  sqlite3_free(p);
15978  return sqlite3_os_init();
15979}
15980
15981/*
15982** The list of all registered VFS implementations.
15983*/
15984static sqlite3_vfs * SQLITE_WSD vfsList = 0;
15985#define vfsList GLOBAL(sqlite3_vfs *, vfsList)
15986
15987/*
15988** Locate a VFS by name.  If no name is given, simply return the
15989** first VFS on the list.
15990*/
15991SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
15992  sqlite3_vfs *pVfs = 0;
15993#if SQLITE_THREADSAFE
15994  sqlite3_mutex *mutex;
15995#endif
15996#ifndef SQLITE_OMIT_AUTOINIT
15997  int rc = sqlite3_initialize();
15998  if( rc ) return 0;
15999#endif
16000#if SQLITE_THREADSAFE
16001  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
16002#endif
16003  sqlite3_mutex_enter(mutex);
16004  for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
16005    if( zVfs==0 ) break;
16006    if( strcmp(zVfs, pVfs->zName)==0 ) break;
16007  }
16008  sqlite3_mutex_leave(mutex);
16009  return pVfs;
16010}
16011
16012/*
16013** Unlink a VFS from the linked list
16014*/
16015static void vfsUnlink(sqlite3_vfs *pVfs){
16016  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
16017  if( pVfs==0 ){
16018    /* No-op */
16019  }else if( vfsList==pVfs ){
16020    vfsList = pVfs->pNext;
16021  }else if( vfsList ){
16022    sqlite3_vfs *p = vfsList;
16023    while( p->pNext && p->pNext!=pVfs ){
16024      p = p->pNext;
16025    }
16026    if( p->pNext==pVfs ){
16027      p->pNext = pVfs->pNext;
16028    }
16029  }
16030}
16031
16032/*
16033** Register a VFS with the system.  It is harmless to register the same
16034** VFS multiple times.  The new VFS becomes the default if makeDflt is
16035** true.
16036*/
16037SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
16038  MUTEX_LOGIC(sqlite3_mutex *mutex;)
16039#ifndef SQLITE_OMIT_AUTOINIT
16040  int rc = sqlite3_initialize();
16041  if( rc ) return rc;
16042#endif
16043  MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
16044  sqlite3_mutex_enter(mutex);
16045  vfsUnlink(pVfs);
16046  if( makeDflt || vfsList==0 ){
16047    pVfs->pNext = vfsList;
16048    vfsList = pVfs;
16049  }else{
16050    pVfs->pNext = vfsList->pNext;
16051    vfsList->pNext = pVfs;
16052  }
16053  assert(vfsList);
16054  sqlite3_mutex_leave(mutex);
16055  return SQLITE_OK;
16056}
16057
16058/*
16059** Unregister a VFS so that it is no longer accessible.
16060*/
16061SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
16062#if SQLITE_THREADSAFE
16063  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
16064#endif
16065  sqlite3_mutex_enter(mutex);
16066  vfsUnlink(pVfs);
16067  sqlite3_mutex_leave(mutex);
16068  return SQLITE_OK;
16069}
16070
16071/************** End of os.c **************************************************/
16072/************** Begin file fault.c *******************************************/
16073/*
16074** 2008 Jan 22
16075**
16076** The author disclaims copyright to this source code.  In place of
16077** a legal notice, here is a blessing:
16078**
16079**    May you do good and not evil.
16080**    May you find forgiveness for yourself and forgive others.
16081**    May you share freely, never taking more than you give.
16082**
16083*************************************************************************
16084**
16085** This file contains code to support the concept of "benign"
16086** malloc failures (when the xMalloc() or xRealloc() method of the
16087** sqlite3_mem_methods structure fails to allocate a block of memory
16088** and returns 0).
16089**
16090** Most malloc failures are non-benign. After they occur, SQLite
16091** abandons the current operation and returns an error code (usually
16092** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
16093** fatal. For example, if a malloc fails while resizing a hash table, this
16094** is completely recoverable simply by not carrying out the resize. The
16095** hash table will continue to function normally.  So a malloc failure
16096** during a hash table resize is a benign fault.
16097*/
16098
16099
16100#ifndef SQLITE_OMIT_BUILTIN_TEST
16101
16102/*
16103** Global variables.
16104*/
16105typedef struct BenignMallocHooks BenignMallocHooks;
16106static SQLITE_WSD struct BenignMallocHooks {
16107  void (*xBenignBegin)(void);
16108  void (*xBenignEnd)(void);
16109} sqlite3Hooks = { 0, 0 };
16110
16111/* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
16112** structure.  If writable static data is unsupported on the target,
16113** we have to locate the state vector at run-time.  In the more common
16114** case where writable static data is supported, wsdHooks can refer directly
16115** to the "sqlite3Hooks" state vector declared above.
16116*/
16117#ifdef SQLITE_OMIT_WSD
16118# define wsdHooksInit \
16119  BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
16120# define wsdHooks x[0]
16121#else
16122# define wsdHooksInit
16123# define wsdHooks sqlite3Hooks
16124#endif
16125
16126
16127/*
16128** Register hooks to call when sqlite3BeginBenignMalloc() and
16129** sqlite3EndBenignMalloc() are called, respectively.
16130*/
16131SQLITE_PRIVATE void sqlite3BenignMallocHooks(
16132  void (*xBenignBegin)(void),
16133  void (*xBenignEnd)(void)
16134){
16135  wsdHooksInit;
16136  wsdHooks.xBenignBegin = xBenignBegin;
16137  wsdHooks.xBenignEnd = xBenignEnd;
16138}
16139
16140/*
16141** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
16142** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
16143** indicates that subsequent malloc failures are non-benign.
16144*/
16145SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
16146  wsdHooksInit;
16147  if( wsdHooks.xBenignBegin ){
16148    wsdHooks.xBenignBegin();
16149  }
16150}
16151SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
16152  wsdHooksInit;
16153  if( wsdHooks.xBenignEnd ){
16154    wsdHooks.xBenignEnd();
16155  }
16156}
16157
16158#endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
16159
16160/************** End of fault.c ***********************************************/
16161/************** Begin file mem0.c ********************************************/
16162/*
16163** 2008 October 28
16164**
16165** The author disclaims copyright to this source code.  In place of
16166** a legal notice, here is a blessing:
16167**
16168**    May you do good and not evil.
16169**    May you find forgiveness for yourself and forgive others.
16170**    May you share freely, never taking more than you give.
16171**
16172*************************************************************************
16173**
16174** This file contains a no-op memory allocation drivers for use when
16175** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
16176** here always fail.  SQLite will not operate with these drivers.  These
16177** are merely placeholders.  Real drivers must be substituted using
16178** sqlite3_config() before SQLite will operate.
16179*/
16180
16181/*
16182** This version of the memory allocator is the default.  It is
16183** used when no other memory allocator is specified using compile-time
16184** macros.
16185*/
16186#ifdef SQLITE_ZERO_MALLOC
16187
16188/*
16189** No-op versions of all memory allocation routines
16190*/
16191static void *sqlite3MemMalloc(int nByte){ return 0; }
16192static void sqlite3MemFree(void *pPrior){ return; }
16193static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
16194static int sqlite3MemSize(void *pPrior){ return 0; }
16195static int sqlite3MemRoundup(int n){ return n; }
16196static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
16197static void sqlite3MemShutdown(void *NotUsed){ return; }
16198
16199/*
16200** This routine is the only routine in this file with external linkage.
16201**
16202** Populate the low-level memory allocation function pointers in
16203** sqlite3GlobalConfig.m with pointers to the routines in this file.
16204*/
16205SQLITE_PRIVATE void sqlite3MemSetDefault(void){
16206  static const sqlite3_mem_methods defaultMethods = {
16207     sqlite3MemMalloc,
16208     sqlite3MemFree,
16209     sqlite3MemRealloc,
16210     sqlite3MemSize,
16211     sqlite3MemRoundup,
16212     sqlite3MemInit,
16213     sqlite3MemShutdown,
16214     0
16215  };
16216  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
16217}
16218
16219#endif /* SQLITE_ZERO_MALLOC */
16220
16221/************** End of mem0.c ************************************************/
16222/************** Begin file mem1.c ********************************************/
16223/*
16224** 2007 August 14
16225**
16226** The author disclaims copyright to this source code.  In place of
16227** a legal notice, here is a blessing:
16228**
16229**    May you do good and not evil.
16230**    May you find forgiveness for yourself and forgive others.
16231**    May you share freely, never taking more than you give.
16232**
16233*************************************************************************
16234**
16235** This file contains low-level memory allocation drivers for when
16236** SQLite will use the standard C-library malloc/realloc/free interface
16237** to obtain the memory it needs.
16238**
16239** This file contains implementations of the low-level memory allocation
16240** routines specified in the sqlite3_mem_methods object.  The content of
16241** this file is only used if SQLITE_SYSTEM_MALLOC is defined.  The
16242** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
16243** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined.  The
16244** default configuration is to use memory allocation routines in this
16245** file.
16246**
16247** C-preprocessor macro summary:
16248**
16249**    HAVE_MALLOC_USABLE_SIZE     The configure script sets this symbol if
16250**                                the malloc_usable_size() interface exists
16251**                                on the target platform.  Or, this symbol
16252**                                can be set manually, if desired.
16253**                                If an equivalent interface exists by
16254**                                a different name, using a separate -D
16255**                                option to rename it.
16256**
16257**    SQLITE_WITHOUT_ZONEMALLOC   Some older macs lack support for the zone
16258**                                memory allocator.  Set this symbol to enable
16259**                                building on older macs.
16260**
16261**    SQLITE_WITHOUT_MSIZE        Set this symbol to disable the use of
16262**                                _msize() on windows systems.  This might
16263**                                be necessary when compiling for Delphi,
16264**                                for example.
16265*/
16266
16267/*
16268** This version of the memory allocator is the default.  It is
16269** used when no other memory allocator is specified using compile-time
16270** macros.
16271*/
16272#ifdef SQLITE_SYSTEM_MALLOC
16273#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
16274
16275/*
16276** Use the zone allocator available on apple products unless the
16277** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
16278*/
16279#include <sys/sysctl.h>
16280#include <malloc/malloc.h>
16281#include <libkern/OSAtomic.h>
16282static malloc_zone_t* _sqliteZone_;
16283#define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
16284#define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
16285#define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
16286#define SQLITE_MALLOCSIZE(x) \
16287        (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
16288
16289#else /* if not __APPLE__ */
16290
16291/*
16292** Use standard C library malloc and free on non-Apple systems.
16293** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
16294*/
16295#define SQLITE_MALLOC(x)             malloc(x)
16296#define SQLITE_FREE(x)               free(x)
16297#define SQLITE_REALLOC(x,y)          realloc((x),(y))
16298
16299/*
16300** The malloc.h header file is needed for malloc_usable_size() function
16301** on some systems (e.g. Linux).
16302*/
16303#if defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE)
16304#  define SQLITE_USE_MALLOC_H
16305#  define SQLITE_USE_MALLOC_USABLE_SIZE
16306/*
16307** The MSVCRT has malloc_usable_size(), but it is called _msize().  The
16308** use of _msize() is automatic, but can be disabled by compiling with
16309** -DSQLITE_WITHOUT_MSIZE.  Using the _msize() function also requires
16310** the malloc.h header file.
16311*/
16312#elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
16313#  define SQLITE_USE_MALLOC_H
16314#  define SQLITE_USE_MSIZE
16315#endif
16316
16317/*
16318** Include the malloc.h header file, if necessary.  Also set define macro
16319** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
16320** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
16321** The memory size function can always be overridden manually by defining
16322** the macro SQLITE_MALLOCSIZE to the desired function name.
16323*/
16324#if defined(SQLITE_USE_MALLOC_H)
16325#  include <malloc.h>
16326#  if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
16327#    if !defined(SQLITE_MALLOCSIZE)
16328#      define SQLITE_MALLOCSIZE(x)   malloc_usable_size(x)
16329#    endif
16330#  elif defined(SQLITE_USE_MSIZE)
16331#    if !defined(SQLITE_MALLOCSIZE)
16332#      define SQLITE_MALLOCSIZE      _msize
16333#    endif
16334#  endif
16335#endif /* defined(SQLITE_USE_MALLOC_H) */
16336
16337#endif /* __APPLE__ or not __APPLE__ */
16338
16339/*
16340** Like malloc(), but remember the size of the allocation
16341** so that we can find it later using sqlite3MemSize().
16342**
16343** For this low-level routine, we are guaranteed that nByte>0 because
16344** cases of nByte<=0 will be intercepted and dealt with by higher level
16345** routines.
16346*/
16347static void *sqlite3MemMalloc(int nByte){
16348#ifdef SQLITE_MALLOCSIZE
16349  void *p = SQLITE_MALLOC( nByte );
16350  if( p==0 ){
16351    testcase( sqlite3GlobalConfig.xLog!=0 );
16352    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
16353  }
16354  return p;
16355#else
16356  sqlite3_int64 *p;
16357  assert( nByte>0 );
16358  nByte = ROUND8(nByte);
16359  p = SQLITE_MALLOC( nByte+8 );
16360  if( p ){
16361    p[0] = nByte;
16362    p++;
16363  }else{
16364    testcase( sqlite3GlobalConfig.xLog!=0 );
16365    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
16366  }
16367  return (void *)p;
16368#endif
16369}
16370
16371/*
16372** Like free() but works for allocations obtained from sqlite3MemMalloc()
16373** or sqlite3MemRealloc().
16374**
16375** For this low-level routine, we already know that pPrior!=0 since
16376** cases where pPrior==0 will have been intecepted and dealt with
16377** by higher-level routines.
16378*/
16379static void sqlite3MemFree(void *pPrior){
16380#ifdef SQLITE_MALLOCSIZE
16381  SQLITE_FREE(pPrior);
16382#else
16383  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
16384  assert( pPrior!=0 );
16385  p--;
16386  SQLITE_FREE(p);
16387#endif
16388}
16389
16390/*
16391** Report the allocated size of a prior return from xMalloc()
16392** or xRealloc().
16393*/
16394static int sqlite3MemSize(void *pPrior){
16395#ifdef SQLITE_MALLOCSIZE
16396  return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
16397#else
16398  sqlite3_int64 *p;
16399  if( pPrior==0 ) return 0;
16400  p = (sqlite3_int64*)pPrior;
16401  p--;
16402  return (int)p[0];
16403#endif
16404}
16405
16406/*
16407** Like realloc().  Resize an allocation previously obtained from
16408** sqlite3MemMalloc().
16409**
16410** For this low-level interface, we know that pPrior!=0.  Cases where
16411** pPrior==0 while have been intercepted by higher-level routine and
16412** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
16413** cases where nByte<=0 will have been intercepted by higher-level
16414** routines and redirected to xFree.
16415*/
16416static void *sqlite3MemRealloc(void *pPrior, int nByte){
16417#ifdef SQLITE_MALLOCSIZE
16418  void *p = SQLITE_REALLOC(pPrior, nByte);
16419  if( p==0 ){
16420    testcase( sqlite3GlobalConfig.xLog!=0 );
16421    sqlite3_log(SQLITE_NOMEM,
16422      "failed memory resize %u to %u bytes",
16423      SQLITE_MALLOCSIZE(pPrior), nByte);
16424  }
16425  return p;
16426#else
16427  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
16428  assert( pPrior!=0 && nByte>0 );
16429  assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
16430  p--;
16431  p = SQLITE_REALLOC(p, nByte+8 );
16432  if( p ){
16433    p[0] = nByte;
16434    p++;
16435  }else{
16436    testcase( sqlite3GlobalConfig.xLog!=0 );
16437    sqlite3_log(SQLITE_NOMEM,
16438      "failed memory resize %u to %u bytes",
16439      sqlite3MemSize(pPrior), nByte);
16440  }
16441  return (void*)p;
16442#endif
16443}
16444
16445/*
16446** Round up a request size to the next valid allocation size.
16447*/
16448static int sqlite3MemRoundup(int n){
16449  return ROUND8(n);
16450}
16451
16452/*
16453** Initialize this module.
16454*/
16455static int sqlite3MemInit(void *NotUsed){
16456#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
16457  int cpuCount;
16458  size_t len;
16459  if( _sqliteZone_ ){
16460    return SQLITE_OK;
16461  }
16462  len = sizeof(cpuCount);
16463  /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
16464  sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
16465  if( cpuCount>1 ){
16466    /* defer MT decisions to system malloc */
16467    _sqliteZone_ = malloc_default_zone();
16468  }else{
16469    /* only 1 core, use our own zone to contention over global locks,
16470    ** e.g. we have our own dedicated locks */
16471    bool success;
16472    malloc_zone_t* newzone = malloc_create_zone(4096, 0);
16473    malloc_set_zone_name(newzone, "Sqlite_Heap");
16474    do{
16475      success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
16476                                 (void * volatile *)&_sqliteZone_);
16477    }while(!_sqliteZone_);
16478    if( !success ){
16479      /* somebody registered a zone first */
16480      malloc_destroy_zone(newzone);
16481    }
16482  }
16483#endif
16484  UNUSED_PARAMETER(NotUsed);
16485  return SQLITE_OK;
16486}
16487
16488/*
16489** Deinitialize this module.
16490*/
16491static void sqlite3MemShutdown(void *NotUsed){
16492  UNUSED_PARAMETER(NotUsed);
16493  return;
16494}
16495
16496/*
16497** This routine is the only routine in this file with external linkage.
16498**
16499** Populate the low-level memory allocation function pointers in
16500** sqlite3GlobalConfig.m with pointers to the routines in this file.
16501*/
16502SQLITE_PRIVATE void sqlite3MemSetDefault(void){
16503  static const sqlite3_mem_methods defaultMethods = {
16504     sqlite3MemMalloc,
16505     sqlite3MemFree,
16506     sqlite3MemRealloc,
16507     sqlite3MemSize,
16508     sqlite3MemRoundup,
16509     sqlite3MemInit,
16510     sqlite3MemShutdown,
16511     0
16512  };
16513  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
16514}
16515
16516#endif /* SQLITE_SYSTEM_MALLOC */
16517
16518/************** End of mem1.c ************************************************/
16519/************** Begin file mem2.c ********************************************/
16520/*
16521** 2007 August 15
16522**
16523** The author disclaims copyright to this source code.  In place of
16524** a legal notice, here is a blessing:
16525**
16526**    May you do good and not evil.
16527**    May you find forgiveness for yourself and forgive others.
16528**    May you share freely, never taking more than you give.
16529**
16530*************************************************************************
16531**
16532** This file contains low-level memory allocation drivers for when
16533** SQLite will use the standard C-library malloc/realloc/free interface
16534** to obtain the memory it needs while adding lots of additional debugging
16535** information to each allocation in order to help detect and fix memory
16536** leaks and memory usage errors.
16537**
16538** This file contains implementations of the low-level memory allocation
16539** routines specified in the sqlite3_mem_methods object.
16540*/
16541
16542/*
16543** This version of the memory allocator is used only if the
16544** SQLITE_MEMDEBUG macro is defined
16545*/
16546#ifdef SQLITE_MEMDEBUG
16547
16548/*
16549** The backtrace functionality is only available with GLIBC
16550*/
16551#ifdef __GLIBC__
16552  extern int backtrace(void**,int);
16553  extern void backtrace_symbols_fd(void*const*,int,int);
16554#else
16555# define backtrace(A,B) 1
16556# define backtrace_symbols_fd(A,B,C)
16557#endif
16558/* #include <stdio.h> */
16559
16560/*
16561** Each memory allocation looks like this:
16562**
16563**  ------------------------------------------------------------------------
16564**  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
16565**  ------------------------------------------------------------------------
16566**
16567** The application code sees only a pointer to the allocation.  We have
16568** to back up from the allocation pointer to find the MemBlockHdr.  The
16569** MemBlockHdr tells us the size of the allocation and the number of
16570** backtrace pointers.  There is also a guard word at the end of the
16571** MemBlockHdr.
16572*/
16573struct MemBlockHdr {
16574  i64 iSize;                          /* Size of this allocation */
16575  struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
16576  char nBacktrace;                    /* Number of backtraces on this alloc */
16577  char nBacktraceSlots;               /* Available backtrace slots */
16578  u8 nTitle;                          /* Bytes of title; includes '\0' */
16579  u8 eType;                           /* Allocation type code */
16580  int iForeGuard;                     /* Guard word for sanity */
16581};
16582
16583/*
16584** Guard words
16585*/
16586#define FOREGUARD 0x80F5E153
16587#define REARGUARD 0xE4676B53
16588
16589/*
16590** Number of malloc size increments to track.
16591*/
16592#define NCSIZE  1000
16593
16594/*
16595** All of the static variables used by this module are collected
16596** into a single structure named "mem".  This is to keep the
16597** static variables organized and to reduce namespace pollution
16598** when this module is combined with other in the amalgamation.
16599*/
16600static struct {
16601
16602  /*
16603  ** Mutex to control access to the memory allocation subsystem.
16604  */
16605  sqlite3_mutex *mutex;
16606
16607  /*
16608  ** Head and tail of a linked list of all outstanding allocations
16609  */
16610  struct MemBlockHdr *pFirst;
16611  struct MemBlockHdr *pLast;
16612
16613  /*
16614  ** The number of levels of backtrace to save in new allocations.
16615  */
16616  int nBacktrace;
16617  void (*xBacktrace)(int, int, void **);
16618
16619  /*
16620  ** Title text to insert in front of each block
16621  */
16622  int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
16623  char zTitle[100];  /* The title text */
16624
16625  /*
16626  ** sqlite3MallocDisallow() increments the following counter.
16627  ** sqlite3MallocAllow() decrements it.
16628  */
16629  int disallow; /* Do not allow memory allocation */
16630
16631  /*
16632  ** Gather statistics on the sizes of memory allocations.
16633  ** nAlloc[i] is the number of allocation attempts of i*8
16634  ** bytes.  i==NCSIZE is the number of allocation attempts for
16635  ** sizes more than NCSIZE*8 bytes.
16636  */
16637  int nAlloc[NCSIZE];      /* Total number of allocations */
16638  int nCurrent[NCSIZE];    /* Current number of allocations */
16639  int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
16640
16641} mem;
16642
16643
16644/*
16645** Adjust memory usage statistics
16646*/
16647static void adjustStats(int iSize, int increment){
16648  int i = ROUND8(iSize)/8;
16649  if( i>NCSIZE-1 ){
16650    i = NCSIZE - 1;
16651  }
16652  if( increment>0 ){
16653    mem.nAlloc[i]++;
16654    mem.nCurrent[i]++;
16655    if( mem.nCurrent[i]>mem.mxCurrent[i] ){
16656      mem.mxCurrent[i] = mem.nCurrent[i];
16657    }
16658  }else{
16659    mem.nCurrent[i]--;
16660    assert( mem.nCurrent[i]>=0 );
16661  }
16662}
16663
16664/*
16665** Given an allocation, find the MemBlockHdr for that allocation.
16666**
16667** This routine checks the guards at either end of the allocation and
16668** if they are incorrect it asserts.
16669*/
16670static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
16671  struct MemBlockHdr *p;
16672  int *pInt;
16673  u8 *pU8;
16674  int nReserve;
16675
16676  p = (struct MemBlockHdr*)pAllocation;
16677  p--;
16678  assert( p->iForeGuard==(int)FOREGUARD );
16679  nReserve = ROUND8(p->iSize);
16680  pInt = (int*)pAllocation;
16681  pU8 = (u8*)pAllocation;
16682  assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
16683  /* This checks any of the "extra" bytes allocated due
16684  ** to rounding up to an 8 byte boundary to ensure
16685  ** they haven't been overwritten.
16686  */
16687  while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
16688  return p;
16689}
16690
16691/*
16692** Return the number of bytes currently allocated at address p.
16693*/
16694static int sqlite3MemSize(void *p){
16695  struct MemBlockHdr *pHdr;
16696  if( !p ){
16697    return 0;
16698  }
16699  pHdr = sqlite3MemsysGetHeader(p);
16700  return (int)pHdr->iSize;
16701}
16702
16703/*
16704** Initialize the memory allocation subsystem.
16705*/
16706static int sqlite3MemInit(void *NotUsed){
16707  UNUSED_PARAMETER(NotUsed);
16708  assert( (sizeof(struct MemBlockHdr)&7) == 0 );
16709  if( !sqlite3GlobalConfig.bMemstat ){
16710    /* If memory status is enabled, then the malloc.c wrapper will already
16711    ** hold the STATIC_MEM mutex when the routines here are invoked. */
16712    mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16713  }
16714  return SQLITE_OK;
16715}
16716
16717/*
16718** Deinitialize the memory allocation subsystem.
16719*/
16720static void sqlite3MemShutdown(void *NotUsed){
16721  UNUSED_PARAMETER(NotUsed);
16722  mem.mutex = 0;
16723}
16724
16725/*
16726** Round up a request size to the next valid allocation size.
16727*/
16728static int sqlite3MemRoundup(int n){
16729  return ROUND8(n);
16730}
16731
16732/*
16733** Fill a buffer with pseudo-random bytes.  This is used to preset
16734** the content of a new memory allocation to unpredictable values and
16735** to clear the content of a freed allocation to unpredictable values.
16736*/
16737static void randomFill(char *pBuf, int nByte){
16738  unsigned int x, y, r;
16739  x = SQLITE_PTR_TO_INT(pBuf);
16740  y = nByte | 1;
16741  while( nByte >= 4 ){
16742    x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
16743    y = y*1103515245 + 12345;
16744    r = x ^ y;
16745    *(int*)pBuf = r;
16746    pBuf += 4;
16747    nByte -= 4;
16748  }
16749  while( nByte-- > 0 ){
16750    x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
16751    y = y*1103515245 + 12345;
16752    r = x ^ y;
16753    *(pBuf++) = r & 0xff;
16754  }
16755}
16756
16757/*
16758** Allocate nByte bytes of memory.
16759*/
16760static void *sqlite3MemMalloc(int nByte){
16761  struct MemBlockHdr *pHdr;
16762  void **pBt;
16763  char *z;
16764  int *pInt;
16765  void *p = 0;
16766  int totalSize;
16767  int nReserve;
16768  sqlite3_mutex_enter(mem.mutex);
16769  assert( mem.disallow==0 );
16770  nReserve = ROUND8(nByte);
16771  totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
16772               mem.nBacktrace*sizeof(void*) + mem.nTitle;
16773  p = malloc(totalSize);
16774  if( p ){
16775    z = p;
16776    pBt = (void**)&z[mem.nTitle];
16777    pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
16778    pHdr->pNext = 0;
16779    pHdr->pPrev = mem.pLast;
16780    if( mem.pLast ){
16781      mem.pLast->pNext = pHdr;
16782    }else{
16783      mem.pFirst = pHdr;
16784    }
16785    mem.pLast = pHdr;
16786    pHdr->iForeGuard = FOREGUARD;
16787    pHdr->eType = MEMTYPE_HEAP;
16788    pHdr->nBacktraceSlots = mem.nBacktrace;
16789    pHdr->nTitle = mem.nTitle;
16790    if( mem.nBacktrace ){
16791      void *aAddr[40];
16792      pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
16793      memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
16794      assert(pBt[0]);
16795      if( mem.xBacktrace ){
16796        mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
16797      }
16798    }else{
16799      pHdr->nBacktrace = 0;
16800    }
16801    if( mem.nTitle ){
16802      memcpy(z, mem.zTitle, mem.nTitle);
16803    }
16804    pHdr->iSize = nByte;
16805    adjustStats(nByte, +1);
16806    pInt = (int*)&pHdr[1];
16807    pInt[nReserve/sizeof(int)] = REARGUARD;
16808    randomFill((char*)pInt, nByte);
16809    memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
16810    p = (void*)pInt;
16811  }
16812  sqlite3_mutex_leave(mem.mutex);
16813  return p;
16814}
16815
16816/*
16817** Free memory.
16818*/
16819static void sqlite3MemFree(void *pPrior){
16820  struct MemBlockHdr *pHdr;
16821  void **pBt;
16822  char *z;
16823  assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
16824       || mem.mutex!=0 );
16825  pHdr = sqlite3MemsysGetHeader(pPrior);
16826  pBt = (void**)pHdr;
16827  pBt -= pHdr->nBacktraceSlots;
16828  sqlite3_mutex_enter(mem.mutex);
16829  if( pHdr->pPrev ){
16830    assert( pHdr->pPrev->pNext==pHdr );
16831    pHdr->pPrev->pNext = pHdr->pNext;
16832  }else{
16833    assert( mem.pFirst==pHdr );
16834    mem.pFirst = pHdr->pNext;
16835  }
16836  if( pHdr->pNext ){
16837    assert( pHdr->pNext->pPrev==pHdr );
16838    pHdr->pNext->pPrev = pHdr->pPrev;
16839  }else{
16840    assert( mem.pLast==pHdr );
16841    mem.pLast = pHdr->pPrev;
16842  }
16843  z = (char*)pBt;
16844  z -= pHdr->nTitle;
16845  adjustStats((int)pHdr->iSize, -1);
16846  randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
16847                (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
16848  free(z);
16849  sqlite3_mutex_leave(mem.mutex);
16850}
16851
16852/*
16853** Change the size of an existing memory allocation.
16854**
16855** For this debugging implementation, we *always* make a copy of the
16856** allocation into a new place in memory.  In this way, if the
16857** higher level code is using pointer to the old allocation, it is
16858** much more likely to break and we are much more liking to find
16859** the error.
16860*/
16861static void *sqlite3MemRealloc(void *pPrior, int nByte){
16862  struct MemBlockHdr *pOldHdr;
16863  void *pNew;
16864  assert( mem.disallow==0 );
16865  assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
16866  pOldHdr = sqlite3MemsysGetHeader(pPrior);
16867  pNew = sqlite3MemMalloc(nByte);
16868  if( pNew ){
16869    memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
16870    if( nByte>pOldHdr->iSize ){
16871      randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
16872    }
16873    sqlite3MemFree(pPrior);
16874  }
16875  return pNew;
16876}
16877
16878/*
16879** Populate the low-level memory allocation function pointers in
16880** sqlite3GlobalConfig.m with pointers to the routines in this file.
16881*/
16882SQLITE_PRIVATE void sqlite3MemSetDefault(void){
16883  static const sqlite3_mem_methods defaultMethods = {
16884     sqlite3MemMalloc,
16885     sqlite3MemFree,
16886     sqlite3MemRealloc,
16887     sqlite3MemSize,
16888     sqlite3MemRoundup,
16889     sqlite3MemInit,
16890     sqlite3MemShutdown,
16891     0
16892  };
16893  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
16894}
16895
16896/*
16897** Set the "type" of an allocation.
16898*/
16899SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
16900  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
16901    struct MemBlockHdr *pHdr;
16902    pHdr = sqlite3MemsysGetHeader(p);
16903    assert( pHdr->iForeGuard==FOREGUARD );
16904    pHdr->eType = eType;
16905  }
16906}
16907
16908/*
16909** Return TRUE if the mask of type in eType matches the type of the
16910** allocation p.  Also return true if p==NULL.
16911**
16912** This routine is designed for use within an assert() statement, to
16913** verify the type of an allocation.  For example:
16914**
16915**     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
16916*/
16917SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
16918  int rc = 1;
16919  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
16920    struct MemBlockHdr *pHdr;
16921    pHdr = sqlite3MemsysGetHeader(p);
16922    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
16923    if( (pHdr->eType&eType)==0 ){
16924      rc = 0;
16925    }
16926  }
16927  return rc;
16928}
16929
16930/*
16931** Return TRUE if the mask of type in eType matches no bits of the type of the
16932** allocation p.  Also return true if p==NULL.
16933**
16934** This routine is designed for use within an assert() statement, to
16935** verify the type of an allocation.  For example:
16936**
16937**     assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
16938*/
16939SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
16940  int rc = 1;
16941  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
16942    struct MemBlockHdr *pHdr;
16943    pHdr = sqlite3MemsysGetHeader(p);
16944    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
16945    if( (pHdr->eType&eType)!=0 ){
16946      rc = 0;
16947    }
16948  }
16949  return rc;
16950}
16951
16952/*
16953** Set the number of backtrace levels kept for each allocation.
16954** A value of zero turns off backtracing.  The number is always rounded
16955** up to a multiple of 2.
16956*/
16957SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
16958  if( depth<0 ){ depth = 0; }
16959  if( depth>20 ){ depth = 20; }
16960  depth = (depth+1)&0xfe;
16961  mem.nBacktrace = depth;
16962}
16963
16964SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
16965  mem.xBacktrace = xBacktrace;
16966}
16967
16968/*
16969** Set the title string for subsequent allocations.
16970*/
16971SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
16972  unsigned int n = sqlite3Strlen30(zTitle) + 1;
16973  sqlite3_mutex_enter(mem.mutex);
16974  if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
16975  memcpy(mem.zTitle, zTitle, n);
16976  mem.zTitle[n] = 0;
16977  mem.nTitle = ROUND8(n);
16978  sqlite3_mutex_leave(mem.mutex);
16979}
16980
16981SQLITE_PRIVATE void sqlite3MemdebugSync(){
16982  struct MemBlockHdr *pHdr;
16983  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
16984    void **pBt = (void**)pHdr;
16985    pBt -= pHdr->nBacktraceSlots;
16986    mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
16987  }
16988}
16989
16990/*
16991** Open the file indicated and write a log of all unfreed memory
16992** allocations into that log.
16993*/
16994SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
16995  FILE *out;
16996  struct MemBlockHdr *pHdr;
16997  void **pBt;
16998  int i;
16999  out = fopen(zFilename, "w");
17000  if( out==0 ){
17001    fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
17002                    zFilename);
17003    return;
17004  }
17005  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
17006    char *z = (char*)pHdr;
17007    z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
17008    fprintf(out, "**** %lld bytes at %p from %s ****\n",
17009            pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
17010    if( pHdr->nBacktrace ){
17011      fflush(out);
17012      pBt = (void**)pHdr;
17013      pBt -= pHdr->nBacktraceSlots;
17014      backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
17015      fprintf(out, "\n");
17016    }
17017  }
17018  fprintf(out, "COUNTS:\n");
17019  for(i=0; i<NCSIZE-1; i++){
17020    if( mem.nAlloc[i] ){
17021      fprintf(out, "   %5d: %10d %10d %10d\n",
17022            i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
17023    }
17024  }
17025  if( mem.nAlloc[NCSIZE-1] ){
17026    fprintf(out, "   %5d: %10d %10d %10d\n",
17027             NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
17028             mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
17029  }
17030  fclose(out);
17031}
17032
17033/*
17034** Return the number of times sqlite3MemMalloc() has been called.
17035*/
17036SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
17037  int i;
17038  int nTotal = 0;
17039  for(i=0; i<NCSIZE; i++){
17040    nTotal += mem.nAlloc[i];
17041  }
17042  return nTotal;
17043}
17044
17045
17046#endif /* SQLITE_MEMDEBUG */
17047
17048/************** End of mem2.c ************************************************/
17049/************** Begin file mem3.c ********************************************/
17050/*
17051** 2007 October 14
17052**
17053** The author disclaims copyright to this source code.  In place of
17054** a legal notice, here is a blessing:
17055**
17056**    May you do good and not evil.
17057**    May you find forgiveness for yourself and forgive others.
17058**    May you share freely, never taking more than you give.
17059**
17060*************************************************************************
17061** This file contains the C functions that implement a memory
17062** allocation subsystem for use by SQLite.
17063**
17064** This version of the memory allocation subsystem omits all
17065** use of malloc(). The SQLite user supplies a block of memory
17066** before calling sqlite3_initialize() from which allocations
17067** are made and returned by the xMalloc() and xRealloc()
17068** implementations. Once sqlite3_initialize() has been called,
17069** the amount of memory available to SQLite is fixed and cannot
17070** be changed.
17071**
17072** This version of the memory allocation subsystem is included
17073** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
17074*/
17075
17076/*
17077** This version of the memory allocator is only built into the library
17078** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
17079** mean that the library will use a memory-pool by default, just that
17080** it is available. The mempool allocator is activated by calling
17081** sqlite3_config().
17082*/
17083#ifdef SQLITE_ENABLE_MEMSYS3
17084
17085/*
17086** Maximum size (in Mem3Blocks) of a "small" chunk.
17087*/
17088#define MX_SMALL 10
17089
17090
17091/*
17092** Number of freelist hash slots
17093*/
17094#define N_HASH  61
17095
17096/*
17097** A memory allocation (also called a "chunk") consists of two or
17098** more blocks where each block is 8 bytes.  The first 8 bytes are
17099** a header that is not returned to the user.
17100**
17101** A chunk is two or more blocks that is either checked out or
17102** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
17103** size of the allocation in blocks if the allocation is free.
17104** The u.hdr.size4x&1 bit is true if the chunk is checked out and
17105** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
17106** is true if the previous chunk is checked out and false if the
17107** previous chunk is free.  The u.hdr.prevSize field is the size of
17108** the previous chunk in blocks if the previous chunk is on the
17109** freelist. If the previous chunk is checked out, then
17110** u.hdr.prevSize can be part of the data for that chunk and should
17111** not be read or written.
17112**
17113** We often identify a chunk by its index in mem3.aPool[].  When
17114** this is done, the chunk index refers to the second block of
17115** the chunk.  In this way, the first chunk has an index of 1.
17116** A chunk index of 0 means "no such chunk" and is the equivalent
17117** of a NULL pointer.
17118**
17119** The second block of free chunks is of the form u.list.  The
17120** two fields form a double-linked list of chunks of related sizes.
17121** Pointers to the head of the list are stored in mem3.aiSmall[]
17122** for smaller chunks and mem3.aiHash[] for larger chunks.
17123**
17124** The second block of a chunk is user data if the chunk is checked
17125** out.  If a chunk is checked out, the user data may extend into
17126** the u.hdr.prevSize value of the following chunk.
17127*/
17128typedef struct Mem3Block Mem3Block;
17129struct Mem3Block {
17130  union {
17131    struct {
17132      u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
17133      u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
17134    } hdr;
17135    struct {
17136      u32 next;       /* Index in mem3.aPool[] of next free chunk */
17137      u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
17138    } list;
17139  } u;
17140};
17141
17142/*
17143** All of the static variables used by this module are collected
17144** into a single structure named "mem3".  This is to keep the
17145** static variables organized and to reduce namespace pollution
17146** when this module is combined with other in the amalgamation.
17147*/
17148static SQLITE_WSD struct Mem3Global {
17149  /*
17150  ** Memory available for allocation. nPool is the size of the array
17151  ** (in Mem3Blocks) pointed to by aPool less 2.
17152  */
17153  u32 nPool;
17154  Mem3Block *aPool;
17155
17156  /*
17157  ** True if we are evaluating an out-of-memory callback.
17158  */
17159  int alarmBusy;
17160
17161  /*
17162  ** Mutex to control access to the memory allocation subsystem.
17163  */
17164  sqlite3_mutex *mutex;
17165
17166  /*
17167  ** The minimum amount of free space that we have seen.
17168  */
17169  u32 mnMaster;
17170
17171  /*
17172  ** iMaster is the index of the master chunk.  Most new allocations
17173  ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
17174  ** of the current master.  iMaster is 0 if there is not master chunk.
17175  ** The master chunk is not in either the aiHash[] or aiSmall[].
17176  */
17177  u32 iMaster;
17178  u32 szMaster;
17179
17180  /*
17181  ** Array of lists of free blocks according to the block size
17182  ** for smaller chunks, or a hash on the block size for larger
17183  ** chunks.
17184  */
17185  u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
17186  u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
17187} mem3 = { 97535575 };
17188
17189#define mem3 GLOBAL(struct Mem3Global, mem3)
17190
17191/*
17192** Unlink the chunk at mem3.aPool[i] from list it is currently
17193** on.  *pRoot is the list that i is a member of.
17194*/
17195static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
17196  u32 next = mem3.aPool[i].u.list.next;
17197  u32 prev = mem3.aPool[i].u.list.prev;
17198  assert( sqlite3_mutex_held(mem3.mutex) );
17199  if( prev==0 ){
17200    *pRoot = next;
17201  }else{
17202    mem3.aPool[prev].u.list.next = next;
17203  }
17204  if( next ){
17205    mem3.aPool[next].u.list.prev = prev;
17206  }
17207  mem3.aPool[i].u.list.next = 0;
17208  mem3.aPool[i].u.list.prev = 0;
17209}
17210
17211/*
17212** Unlink the chunk at index i from
17213** whatever list is currently a member of.
17214*/
17215static void memsys3Unlink(u32 i){
17216  u32 size, hash;
17217  assert( sqlite3_mutex_held(mem3.mutex) );
17218  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
17219  assert( i>=1 );
17220  size = mem3.aPool[i-1].u.hdr.size4x/4;
17221  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
17222  assert( size>=2 );
17223  if( size <= MX_SMALL ){
17224    memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
17225  }else{
17226    hash = size % N_HASH;
17227    memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
17228  }
17229}
17230
17231/*
17232** Link the chunk at mem3.aPool[i] so that is on the list rooted
17233** at *pRoot.
17234*/
17235static void memsys3LinkIntoList(u32 i, u32 *pRoot){
17236  assert( sqlite3_mutex_held(mem3.mutex) );
17237  mem3.aPool[i].u.list.next = *pRoot;
17238  mem3.aPool[i].u.list.prev = 0;
17239  if( *pRoot ){
17240    mem3.aPool[*pRoot].u.list.prev = i;
17241  }
17242  *pRoot = i;
17243}
17244
17245/*
17246** Link the chunk at index i into either the appropriate
17247** small chunk list, or into the large chunk hash table.
17248*/
17249static void memsys3Link(u32 i){
17250  u32 size, hash;
17251  assert( sqlite3_mutex_held(mem3.mutex) );
17252  assert( i>=1 );
17253  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
17254  size = mem3.aPool[i-1].u.hdr.size4x/4;
17255  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
17256  assert( size>=2 );
17257  if( size <= MX_SMALL ){
17258    memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
17259  }else{
17260    hash = size % N_HASH;
17261    memsys3LinkIntoList(i, &mem3.aiHash[hash]);
17262  }
17263}
17264
17265/*
17266** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
17267** will already be held (obtained by code in malloc.c) if
17268** sqlite3GlobalConfig.bMemStat is true.
17269*/
17270static void memsys3Enter(void){
17271  if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
17272    mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
17273  }
17274  sqlite3_mutex_enter(mem3.mutex);
17275}
17276static void memsys3Leave(void){
17277  sqlite3_mutex_leave(mem3.mutex);
17278}
17279
17280/*
17281** Called when we are unable to satisfy an allocation of nBytes.
17282*/
17283static void memsys3OutOfMemory(int nByte){
17284  if( !mem3.alarmBusy ){
17285    mem3.alarmBusy = 1;
17286    assert( sqlite3_mutex_held(mem3.mutex) );
17287    sqlite3_mutex_leave(mem3.mutex);
17288    sqlite3_release_memory(nByte);
17289    sqlite3_mutex_enter(mem3.mutex);
17290    mem3.alarmBusy = 0;
17291  }
17292}
17293
17294
17295/*
17296** Chunk i is a free chunk that has been unlinked.  Adjust its
17297** size parameters for check-out and return a pointer to the
17298** user portion of the chunk.
17299*/
17300static void *memsys3Checkout(u32 i, u32 nBlock){
17301  u32 x;
17302  assert( sqlite3_mutex_held(mem3.mutex) );
17303  assert( i>=1 );
17304  assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
17305  assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
17306  x = mem3.aPool[i-1].u.hdr.size4x;
17307  mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
17308  mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
17309  mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
17310  return &mem3.aPool[i];
17311}
17312
17313/*
17314** Carve a piece off of the end of the mem3.iMaster free chunk.
17315** Return a pointer to the new allocation.  Or, if the master chunk
17316** is not large enough, return 0.
17317*/
17318static void *memsys3FromMaster(u32 nBlock){
17319  assert( sqlite3_mutex_held(mem3.mutex) );
17320  assert( mem3.szMaster>=nBlock );
17321  if( nBlock>=mem3.szMaster-1 ){
17322    /* Use the entire master */
17323    void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
17324    mem3.iMaster = 0;
17325    mem3.szMaster = 0;
17326    mem3.mnMaster = 0;
17327    return p;
17328  }else{
17329    /* Split the master block.  Return the tail. */
17330    u32 newi, x;
17331    newi = mem3.iMaster + mem3.szMaster - nBlock;
17332    assert( newi > mem3.iMaster+1 );
17333    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
17334    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
17335    mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
17336    mem3.szMaster -= nBlock;
17337    mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
17338    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
17339    mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
17340    if( mem3.szMaster < mem3.mnMaster ){
17341      mem3.mnMaster = mem3.szMaster;
17342    }
17343    return (void*)&mem3.aPool[newi];
17344  }
17345}
17346
17347/*
17348** *pRoot is the head of a list of free chunks of the same size
17349** or same size hash.  In other words, *pRoot is an entry in either
17350** mem3.aiSmall[] or mem3.aiHash[].
17351**
17352** This routine examines all entries on the given list and tries
17353** to coalesce each entries with adjacent free chunks.
17354**
17355** If it sees a chunk that is larger than mem3.iMaster, it replaces
17356** the current mem3.iMaster with the new larger chunk.  In order for
17357** this mem3.iMaster replacement to work, the master chunk must be
17358** linked into the hash tables.  That is not the normal state of
17359** affairs, of course.  The calling routine must link the master
17360** chunk before invoking this routine, then must unlink the (possibly
17361** changed) master chunk once this routine has finished.
17362*/
17363static void memsys3Merge(u32 *pRoot){
17364  u32 iNext, prev, size, i, x;
17365
17366  assert( sqlite3_mutex_held(mem3.mutex) );
17367  for(i=*pRoot; i>0; i=iNext){
17368    iNext = mem3.aPool[i].u.list.next;
17369    size = mem3.aPool[i-1].u.hdr.size4x;
17370    assert( (size&1)==0 );
17371    if( (size&2)==0 ){
17372      memsys3UnlinkFromList(i, pRoot);
17373      assert( i > mem3.aPool[i-1].u.hdr.prevSize );
17374      prev = i - mem3.aPool[i-1].u.hdr.prevSize;
17375      if( prev==iNext ){
17376        iNext = mem3.aPool[prev].u.list.next;
17377      }
17378      memsys3Unlink(prev);
17379      size = i + size/4 - prev;
17380      x = mem3.aPool[prev-1].u.hdr.size4x & 2;
17381      mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
17382      mem3.aPool[prev+size-1].u.hdr.prevSize = size;
17383      memsys3Link(prev);
17384      i = prev;
17385    }else{
17386      size /= 4;
17387    }
17388    if( size>mem3.szMaster ){
17389      mem3.iMaster = i;
17390      mem3.szMaster = size;
17391    }
17392  }
17393}
17394
17395/*
17396** Return a block of memory of at least nBytes in size.
17397** Return NULL if unable.
17398**
17399** This function assumes that the necessary mutexes, if any, are
17400** already held by the caller. Hence "Unsafe".
17401*/
17402static void *memsys3MallocUnsafe(int nByte){
17403  u32 i;
17404  u32 nBlock;
17405  u32 toFree;
17406
17407  assert( sqlite3_mutex_held(mem3.mutex) );
17408  assert( sizeof(Mem3Block)==8 );
17409  if( nByte<=12 ){
17410    nBlock = 2;
17411  }else{
17412    nBlock = (nByte + 11)/8;
17413  }
17414  assert( nBlock>=2 );
17415
17416  /* STEP 1:
17417  ** Look for an entry of the correct size in either the small
17418  ** chunk table or in the large chunk hash table.  This is
17419  ** successful most of the time (about 9 times out of 10).
17420  */
17421  if( nBlock <= MX_SMALL ){
17422    i = mem3.aiSmall[nBlock-2];
17423    if( i>0 ){
17424      memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
17425      return memsys3Checkout(i, nBlock);
17426    }
17427  }else{
17428    int hash = nBlock % N_HASH;
17429    for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
17430      if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
17431        memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
17432        return memsys3Checkout(i, nBlock);
17433      }
17434    }
17435  }
17436
17437  /* STEP 2:
17438  ** Try to satisfy the allocation by carving a piece off of the end
17439  ** of the master chunk.  This step usually works if step 1 fails.
17440  */
17441  if( mem3.szMaster>=nBlock ){
17442    return memsys3FromMaster(nBlock);
17443  }
17444
17445
17446  /* STEP 3:
17447  ** Loop through the entire memory pool.  Coalesce adjacent free
17448  ** chunks.  Recompute the master chunk as the largest free chunk.
17449  ** Then try again to satisfy the allocation by carving a piece off
17450  ** of the end of the master chunk.  This step happens very
17451  ** rarely (we hope!)
17452  */
17453  for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
17454    memsys3OutOfMemory(toFree);
17455    if( mem3.iMaster ){
17456      memsys3Link(mem3.iMaster);
17457      mem3.iMaster = 0;
17458      mem3.szMaster = 0;
17459    }
17460    for(i=0; i<N_HASH; i++){
17461      memsys3Merge(&mem3.aiHash[i]);
17462    }
17463    for(i=0; i<MX_SMALL-1; i++){
17464      memsys3Merge(&mem3.aiSmall[i]);
17465    }
17466    if( mem3.szMaster ){
17467      memsys3Unlink(mem3.iMaster);
17468      if( mem3.szMaster>=nBlock ){
17469        return memsys3FromMaster(nBlock);
17470      }
17471    }
17472  }
17473
17474  /* If none of the above worked, then we fail. */
17475  return 0;
17476}
17477
17478/*
17479** Free an outstanding memory allocation.
17480**
17481** This function assumes that the necessary mutexes, if any, are
17482** already held by the caller. Hence "Unsafe".
17483*/
17484static void memsys3FreeUnsafe(void *pOld){
17485  Mem3Block *p = (Mem3Block*)pOld;
17486  int i;
17487  u32 size, x;
17488  assert( sqlite3_mutex_held(mem3.mutex) );
17489  assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
17490  i = p - mem3.aPool;
17491  assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
17492  size = mem3.aPool[i-1].u.hdr.size4x/4;
17493  assert( i+size<=mem3.nPool+1 );
17494  mem3.aPool[i-1].u.hdr.size4x &= ~1;
17495  mem3.aPool[i+size-1].u.hdr.prevSize = size;
17496  mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
17497  memsys3Link(i);
17498
17499  /* Try to expand the master using the newly freed chunk */
17500  if( mem3.iMaster ){
17501    while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
17502      size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
17503      mem3.iMaster -= size;
17504      mem3.szMaster += size;
17505      memsys3Unlink(mem3.iMaster);
17506      x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
17507      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
17508      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
17509    }
17510    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
17511    while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
17512      memsys3Unlink(mem3.iMaster+mem3.szMaster);
17513      mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
17514      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
17515      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
17516    }
17517  }
17518}
17519
17520/*
17521** Return the size of an outstanding allocation, in bytes.  The
17522** size returned omits the 8-byte header overhead.  This only
17523** works for chunks that are currently checked out.
17524*/
17525static int memsys3Size(void *p){
17526  Mem3Block *pBlock;
17527  if( p==0 ) return 0;
17528  pBlock = (Mem3Block*)p;
17529  assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
17530  return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
17531}
17532
17533/*
17534** Round up a request size to the next valid allocation size.
17535*/
17536static int memsys3Roundup(int n){
17537  if( n<=12 ){
17538    return 12;
17539  }else{
17540    return ((n+11)&~7) - 4;
17541  }
17542}
17543
17544/*
17545** Allocate nBytes of memory.
17546*/
17547static void *memsys3Malloc(int nBytes){
17548  sqlite3_int64 *p;
17549  assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
17550  memsys3Enter();
17551  p = memsys3MallocUnsafe(nBytes);
17552  memsys3Leave();
17553  return (void*)p;
17554}
17555
17556/*
17557** Free memory.
17558*/
17559static void memsys3Free(void *pPrior){
17560  assert( pPrior );
17561  memsys3Enter();
17562  memsys3FreeUnsafe(pPrior);
17563  memsys3Leave();
17564}
17565
17566/*
17567** Change the size of an existing memory allocation
17568*/
17569static void *memsys3Realloc(void *pPrior, int nBytes){
17570  int nOld;
17571  void *p;
17572  if( pPrior==0 ){
17573    return sqlite3_malloc(nBytes);
17574  }
17575  if( nBytes<=0 ){
17576    sqlite3_free(pPrior);
17577    return 0;
17578  }
17579  nOld = memsys3Size(pPrior);
17580  if( nBytes<=nOld && nBytes>=nOld-128 ){
17581    return pPrior;
17582  }
17583  memsys3Enter();
17584  p = memsys3MallocUnsafe(nBytes);
17585  if( p ){
17586    if( nOld<nBytes ){
17587      memcpy(p, pPrior, nOld);
17588    }else{
17589      memcpy(p, pPrior, nBytes);
17590    }
17591    memsys3FreeUnsafe(pPrior);
17592  }
17593  memsys3Leave();
17594  return p;
17595}
17596
17597/*
17598** Initialize this module.
17599*/
17600static int memsys3Init(void *NotUsed){
17601  UNUSED_PARAMETER(NotUsed);
17602  if( !sqlite3GlobalConfig.pHeap ){
17603    return SQLITE_ERROR;
17604  }
17605
17606  /* Store a pointer to the memory block in global structure mem3. */
17607  assert( sizeof(Mem3Block)==8 );
17608  mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
17609  mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
17610
17611  /* Initialize the master block. */
17612  mem3.szMaster = mem3.nPool;
17613  mem3.mnMaster = mem3.szMaster;
17614  mem3.iMaster = 1;
17615  mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
17616  mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
17617  mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
17618
17619  return SQLITE_OK;
17620}
17621
17622/*
17623** Deinitialize this module.
17624*/
17625static void memsys3Shutdown(void *NotUsed){
17626  UNUSED_PARAMETER(NotUsed);
17627  mem3.mutex = 0;
17628  return;
17629}
17630
17631
17632
17633/*
17634** Open the file indicated and write a log of all unfreed memory
17635** allocations into that log.
17636*/
17637SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
17638#ifdef SQLITE_DEBUG
17639  FILE *out;
17640  u32 i, j;
17641  u32 size;
17642  if( zFilename==0 || zFilename[0]==0 ){
17643    out = stdout;
17644  }else{
17645    out = fopen(zFilename, "w");
17646    if( out==0 ){
17647      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
17648                      zFilename);
17649      return;
17650    }
17651  }
17652  memsys3Enter();
17653  fprintf(out, "CHUNKS:\n");
17654  for(i=1; i<=mem3.nPool; i+=size/4){
17655    size = mem3.aPool[i-1].u.hdr.size4x;
17656    if( size/4<=1 ){
17657      fprintf(out, "%p size error\n", &mem3.aPool[i]);
17658      assert( 0 );
17659      break;
17660    }
17661    if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
17662      fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
17663      assert( 0 );
17664      break;
17665    }
17666    if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
17667      fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
17668      assert( 0 );
17669      break;
17670    }
17671    if( size&1 ){
17672      fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
17673    }else{
17674      fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
17675                  i==mem3.iMaster ? " **master**" : "");
17676    }
17677  }
17678  for(i=0; i<MX_SMALL-1; i++){
17679    if( mem3.aiSmall[i]==0 ) continue;
17680    fprintf(out, "small(%2d):", i);
17681    for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
17682      fprintf(out, " %p(%d)", &mem3.aPool[j],
17683              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
17684    }
17685    fprintf(out, "\n");
17686  }
17687  for(i=0; i<N_HASH; i++){
17688    if( mem3.aiHash[i]==0 ) continue;
17689    fprintf(out, "hash(%2d):", i);
17690    for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
17691      fprintf(out, " %p(%d)", &mem3.aPool[j],
17692              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
17693    }
17694    fprintf(out, "\n");
17695  }
17696  fprintf(out, "master=%d\n", mem3.iMaster);
17697  fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
17698  fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
17699  sqlite3_mutex_leave(mem3.mutex);
17700  if( out==stdout ){
17701    fflush(stdout);
17702  }else{
17703    fclose(out);
17704  }
17705#else
17706  UNUSED_PARAMETER(zFilename);
17707#endif
17708}
17709
17710/*
17711** This routine is the only routine in this file with external
17712** linkage.
17713**
17714** Populate the low-level memory allocation function pointers in
17715** sqlite3GlobalConfig.m with pointers to the routines in this file. The
17716** arguments specify the block of memory to manage.
17717**
17718** This routine is only called by sqlite3_config(), and therefore
17719** is not required to be threadsafe (it is not).
17720*/
17721SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
17722  static const sqlite3_mem_methods mempoolMethods = {
17723     memsys3Malloc,
17724     memsys3Free,
17725     memsys3Realloc,
17726     memsys3Size,
17727     memsys3Roundup,
17728     memsys3Init,
17729     memsys3Shutdown,
17730     0
17731  };
17732  return &mempoolMethods;
17733}
17734
17735#endif /* SQLITE_ENABLE_MEMSYS3 */
17736
17737/************** End of mem3.c ************************************************/
17738/************** Begin file mem5.c ********************************************/
17739/*
17740** 2007 October 14
17741**
17742** The author disclaims copyright to this source code.  In place of
17743** a legal notice, here is a blessing:
17744**
17745**    May you do good and not evil.
17746**    May you find forgiveness for yourself and forgive others.
17747**    May you share freely, never taking more than you give.
17748**
17749*************************************************************************
17750** This file contains the C functions that implement a memory
17751** allocation subsystem for use by SQLite.
17752**
17753** This version of the memory allocation subsystem omits all
17754** use of malloc(). The application gives SQLite a block of memory
17755** before calling sqlite3_initialize() from which allocations
17756** are made and returned by the xMalloc() and xRealloc()
17757** implementations. Once sqlite3_initialize() has been called,
17758** the amount of memory available to SQLite is fixed and cannot
17759** be changed.
17760**
17761** This version of the memory allocation subsystem is included
17762** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
17763**
17764** This memory allocator uses the following algorithm:
17765**
17766**   1.  All memory allocations sizes are rounded up to a power of 2.
17767**
17768**   2.  If two adjacent free blocks are the halves of a larger block,
17769**       then the two blocks are coalesed into the single larger block.
17770**
17771**   3.  New memory is allocated from the first available free block.
17772**
17773** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
17774** Concerning Dynamic Storage Allocation". Journal of the Association for
17775** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
17776**
17777** Let n be the size of the largest allocation divided by the minimum
17778** allocation size (after rounding all sizes up to a power of 2.)  Let M
17779** be the maximum amount of memory ever outstanding at one time.  Let
17780** N be the total amount of memory available for allocation.  Robson
17781** proved that this memory allocator will never breakdown due to
17782** fragmentation as long as the following constraint holds:
17783**
17784**      N >=  M*(1 + log2(n)/2) - n + 1
17785**
17786** The sqlite3_status() logic tracks the maximum values of n and M so
17787** that an application can, at any time, verify this constraint.
17788*/
17789
17790/*
17791** This version of the memory allocator is used only when
17792** SQLITE_ENABLE_MEMSYS5 is defined.
17793*/
17794#ifdef SQLITE_ENABLE_MEMSYS5
17795
17796/*
17797** A minimum allocation is an instance of the following structure.
17798** Larger allocations are an array of these structures where the
17799** size of the array is a power of 2.
17800**
17801** The size of this object must be a power of two.  That fact is
17802** verified in memsys5Init().
17803*/
17804typedef struct Mem5Link Mem5Link;
17805struct Mem5Link {
17806  int next;       /* Index of next free chunk */
17807  int prev;       /* Index of previous free chunk */
17808};
17809
17810/*
17811** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
17812** mem5.szAtom is always at least 8 and 32-bit integers are used,
17813** it is not actually possible to reach this limit.
17814*/
17815#define LOGMAX 30
17816
17817/*
17818** Masks used for mem5.aCtrl[] elements.
17819*/
17820#define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
17821#define CTRL_FREE     0x20    /* True if not checked out */
17822
17823/*
17824** All of the static variables used by this module are collected
17825** into a single structure named "mem5".  This is to keep the
17826** static variables organized and to reduce namespace pollution
17827** when this module is combined with other in the amalgamation.
17828*/
17829static SQLITE_WSD struct Mem5Global {
17830  /*
17831  ** Memory available for allocation
17832  */
17833  int szAtom;      /* Smallest possible allocation in bytes */
17834  int nBlock;      /* Number of szAtom sized blocks in zPool */
17835  u8 *zPool;       /* Memory available to be allocated */
17836
17837  /*
17838  ** Mutex to control access to the memory allocation subsystem.
17839  */
17840  sqlite3_mutex *mutex;
17841
17842  /*
17843  ** Performance statistics
17844  */
17845  u64 nAlloc;         /* Total number of calls to malloc */
17846  u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
17847  u64 totalExcess;    /* Total internal fragmentation */
17848  u32 currentOut;     /* Current checkout, including internal fragmentation */
17849  u32 currentCount;   /* Current number of distinct checkouts */
17850  u32 maxOut;         /* Maximum instantaneous currentOut */
17851  u32 maxCount;       /* Maximum instantaneous currentCount */
17852  u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
17853
17854  /*
17855  ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
17856  ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
17857  ** and so forth.
17858  */
17859  int aiFreelist[LOGMAX+1];
17860
17861  /*
17862  ** Space for tracking which blocks are checked out and the size
17863  ** of each block.  One byte per block.
17864  */
17865  u8 *aCtrl;
17866
17867} mem5;
17868
17869/*
17870** Access the static variable through a macro for SQLITE_OMIT_WSD.
17871*/
17872#define mem5 GLOBAL(struct Mem5Global, mem5)
17873
17874/*
17875** Assuming mem5.zPool is divided up into an array of Mem5Link
17876** structures, return a pointer to the idx-th such link.
17877*/
17878#define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
17879
17880/*
17881** Unlink the chunk at mem5.aPool[i] from list it is currently
17882** on.  It should be found on mem5.aiFreelist[iLogsize].
17883*/
17884static void memsys5Unlink(int i, int iLogsize){
17885  int next, prev;
17886  assert( i>=0 && i<mem5.nBlock );
17887  assert( iLogsize>=0 && iLogsize<=LOGMAX );
17888  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
17889
17890  next = MEM5LINK(i)->next;
17891  prev = MEM5LINK(i)->prev;
17892  if( prev<0 ){
17893    mem5.aiFreelist[iLogsize] = next;
17894  }else{
17895    MEM5LINK(prev)->next = next;
17896  }
17897  if( next>=0 ){
17898    MEM5LINK(next)->prev = prev;
17899  }
17900}
17901
17902/*
17903** Link the chunk at mem5.aPool[i] so that is on the iLogsize
17904** free list.
17905*/
17906static void memsys5Link(int i, int iLogsize){
17907  int x;
17908  assert( sqlite3_mutex_held(mem5.mutex) );
17909  assert( i>=0 && i<mem5.nBlock );
17910  assert( iLogsize>=0 && iLogsize<=LOGMAX );
17911  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
17912
17913  x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
17914  MEM5LINK(i)->prev = -1;
17915  if( x>=0 ){
17916    assert( x<mem5.nBlock );
17917    MEM5LINK(x)->prev = i;
17918  }
17919  mem5.aiFreelist[iLogsize] = i;
17920}
17921
17922/*
17923** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
17924** will already be held (obtained by code in malloc.c) if
17925** sqlite3GlobalConfig.bMemStat is true.
17926*/
17927static void memsys5Enter(void){
17928  sqlite3_mutex_enter(mem5.mutex);
17929}
17930static void memsys5Leave(void){
17931  sqlite3_mutex_leave(mem5.mutex);
17932}
17933
17934/*
17935** Return the size of an outstanding allocation, in bytes.  The
17936** size returned omits the 8-byte header overhead.  This only
17937** works for chunks that are currently checked out.
17938*/
17939static int memsys5Size(void *p){
17940  int iSize = 0;
17941  if( p ){
17942    int i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
17943    assert( i>=0 && i<mem5.nBlock );
17944    iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
17945  }
17946  return iSize;
17947}
17948
17949/*
17950** Return a block of memory of at least nBytes in size.
17951** Return NULL if unable.  Return NULL if nBytes==0.
17952**
17953** The caller guarantees that nByte is positive.
17954**
17955** The caller has obtained a mutex prior to invoking this
17956** routine so there is never any chance that two or more
17957** threads can be in this routine at the same time.
17958*/
17959static void *memsys5MallocUnsafe(int nByte){
17960  int i;           /* Index of a mem5.aPool[] slot */
17961  int iBin;        /* Index into mem5.aiFreelist[] */
17962  int iFullSz;     /* Size of allocation rounded up to power of 2 */
17963  int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
17964
17965  /* nByte must be a positive */
17966  assert( nByte>0 );
17967
17968  /* Keep track of the maximum allocation request.  Even unfulfilled
17969  ** requests are counted */
17970  if( (u32)nByte>mem5.maxRequest ){
17971    mem5.maxRequest = nByte;
17972  }
17973
17974  /* Abort if the requested allocation size is larger than the largest
17975  ** power of two that we can represent using 32-bit signed integers.
17976  */
17977  if( nByte > 0x40000000 ){
17978    return 0;
17979  }
17980
17981  /* Round nByte up to the next valid power of two */
17982  for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
17983
17984  /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
17985  ** block.  If not, then split a block of the next larger power of
17986  ** two in order to create a new free block of size iLogsize.
17987  */
17988  for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
17989  if( iBin>LOGMAX ){
17990    testcase( sqlite3GlobalConfig.xLog!=0 );
17991    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
17992    return 0;
17993  }
17994  i = mem5.aiFreelist[iBin];
17995  memsys5Unlink(i, iBin);
17996  while( iBin>iLogsize ){
17997    int newSize;
17998
17999    iBin--;
18000    newSize = 1 << iBin;
18001    mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
18002    memsys5Link(i+newSize, iBin);
18003  }
18004  mem5.aCtrl[i] = iLogsize;
18005
18006  /* Update allocator performance statistics. */
18007  mem5.nAlloc++;
18008  mem5.totalAlloc += iFullSz;
18009  mem5.totalExcess += iFullSz - nByte;
18010  mem5.currentCount++;
18011  mem5.currentOut += iFullSz;
18012  if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
18013  if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
18014
18015#ifdef SQLITE_DEBUG
18016  /* Make sure the allocated memory does not assume that it is set to zero
18017  ** or retains a value from a previous allocation */
18018  memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
18019#endif
18020
18021  /* Return a pointer to the allocated memory. */
18022  return (void*)&mem5.zPool[i*mem5.szAtom];
18023}
18024
18025/*
18026** Free an outstanding memory allocation.
18027*/
18028static void memsys5FreeUnsafe(void *pOld){
18029  u32 size, iLogsize;
18030  int iBlock;
18031
18032  /* Set iBlock to the index of the block pointed to by pOld in
18033  ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
18034  */
18035  iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
18036
18037  /* Check that the pointer pOld points to a valid, non-free block. */
18038  assert( iBlock>=0 && iBlock<mem5.nBlock );
18039  assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
18040  assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
18041
18042  iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
18043  size = 1<<iLogsize;
18044  assert( iBlock+size-1<(u32)mem5.nBlock );
18045
18046  mem5.aCtrl[iBlock] |= CTRL_FREE;
18047  mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
18048  assert( mem5.currentCount>0 );
18049  assert( mem5.currentOut>=(size*mem5.szAtom) );
18050  mem5.currentCount--;
18051  mem5.currentOut -= size*mem5.szAtom;
18052  assert( mem5.currentOut>0 || mem5.currentCount==0 );
18053  assert( mem5.currentCount>0 || mem5.currentOut==0 );
18054
18055  mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
18056  while( ALWAYS(iLogsize<LOGMAX) ){
18057    int iBuddy;
18058    if( (iBlock>>iLogsize) & 1 ){
18059      iBuddy = iBlock - size;
18060    }else{
18061      iBuddy = iBlock + size;
18062    }
18063    assert( iBuddy>=0 );
18064    if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
18065    if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
18066    memsys5Unlink(iBuddy, iLogsize);
18067    iLogsize++;
18068    if( iBuddy<iBlock ){
18069      mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
18070      mem5.aCtrl[iBlock] = 0;
18071      iBlock = iBuddy;
18072    }else{
18073      mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
18074      mem5.aCtrl[iBuddy] = 0;
18075    }
18076    size *= 2;
18077  }
18078
18079#ifdef SQLITE_DEBUG
18080  /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
18081  ** not used after being freed */
18082  memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
18083#endif
18084
18085  memsys5Link(iBlock, iLogsize);
18086}
18087
18088/*
18089** Allocate nBytes of memory.
18090*/
18091static void *memsys5Malloc(int nBytes){
18092  sqlite3_int64 *p = 0;
18093  if( nBytes>0 ){
18094    memsys5Enter();
18095    p = memsys5MallocUnsafe(nBytes);
18096    memsys5Leave();
18097  }
18098  return (void*)p;
18099}
18100
18101/*
18102** Free memory.
18103**
18104** The outer layer memory allocator prevents this routine from
18105** being called with pPrior==0.
18106*/
18107static void memsys5Free(void *pPrior){
18108  assert( pPrior!=0 );
18109  memsys5Enter();
18110  memsys5FreeUnsafe(pPrior);
18111  memsys5Leave();
18112}
18113
18114/*
18115** Change the size of an existing memory allocation.
18116**
18117** The outer layer memory allocator prevents this routine from
18118** being called with pPrior==0.
18119**
18120** nBytes is always a value obtained from a prior call to
18121** memsys5Round().  Hence nBytes is always a non-negative power
18122** of two.  If nBytes==0 that means that an oversize allocation
18123** (an allocation larger than 0x40000000) was requested and this
18124** routine should return 0 without freeing pPrior.
18125*/
18126static void *memsys5Realloc(void *pPrior, int nBytes){
18127  int nOld;
18128  void *p;
18129  assert( pPrior!=0 );
18130  assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
18131  assert( nBytes>=0 );
18132  if( nBytes==0 ){
18133    return 0;
18134  }
18135  nOld = memsys5Size(pPrior);
18136  if( nBytes<=nOld ){
18137    return pPrior;
18138  }
18139  memsys5Enter();
18140  p = memsys5MallocUnsafe(nBytes);
18141  if( p ){
18142    memcpy(p, pPrior, nOld);
18143    memsys5FreeUnsafe(pPrior);
18144  }
18145  memsys5Leave();
18146  return p;
18147}
18148
18149/*
18150** Round up a request size to the next valid allocation size.  If
18151** the allocation is too large to be handled by this allocation system,
18152** return 0.
18153**
18154** All allocations must be a power of two and must be expressed by a
18155** 32-bit signed integer.  Hence the largest allocation is 0x40000000
18156** or 1073741824 bytes.
18157*/
18158static int memsys5Roundup(int n){
18159  int iFullSz;
18160  if( n > 0x40000000 ) return 0;
18161  for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
18162  return iFullSz;
18163}
18164
18165/*
18166** Return the ceiling of the logarithm base 2 of iValue.
18167**
18168** Examples:   memsys5Log(1) -> 0
18169**             memsys5Log(2) -> 1
18170**             memsys5Log(4) -> 2
18171**             memsys5Log(5) -> 3
18172**             memsys5Log(8) -> 3
18173**             memsys5Log(9) -> 4
18174*/
18175static int memsys5Log(int iValue){
18176  int iLog;
18177  for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
18178  return iLog;
18179}
18180
18181/*
18182** Initialize the memory allocator.
18183**
18184** This routine is not threadsafe.  The caller must be holding a mutex
18185** to prevent multiple threads from entering at the same time.
18186*/
18187static int memsys5Init(void *NotUsed){
18188  int ii;            /* Loop counter */
18189  int nByte;         /* Number of bytes of memory available to this allocator */
18190  u8 *zByte;         /* Memory usable by this allocator */
18191  int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
18192  int iOffset;       /* An offset into mem5.aCtrl[] */
18193
18194  UNUSED_PARAMETER(NotUsed);
18195
18196  /* For the purposes of this routine, disable the mutex */
18197  mem5.mutex = 0;
18198
18199  /* The size of a Mem5Link object must be a power of two.  Verify that
18200  ** this is case.
18201  */
18202  assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
18203
18204  nByte = sqlite3GlobalConfig.nHeap;
18205  zByte = (u8*)sqlite3GlobalConfig.pHeap;
18206  assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
18207
18208  /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
18209  nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
18210  mem5.szAtom = (1<<nMinLog);
18211  while( (int)sizeof(Mem5Link)>mem5.szAtom ){
18212    mem5.szAtom = mem5.szAtom << 1;
18213  }
18214
18215  mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
18216  mem5.zPool = zByte;
18217  mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
18218
18219  for(ii=0; ii<=LOGMAX; ii++){
18220    mem5.aiFreelist[ii] = -1;
18221  }
18222
18223  iOffset = 0;
18224  for(ii=LOGMAX; ii>=0; ii--){
18225    int nAlloc = (1<<ii);
18226    if( (iOffset+nAlloc)<=mem5.nBlock ){
18227      mem5.aCtrl[iOffset] = ii | CTRL_FREE;
18228      memsys5Link(iOffset, ii);
18229      iOffset += nAlloc;
18230    }
18231    assert((iOffset+nAlloc)>mem5.nBlock);
18232  }
18233
18234  /* If a mutex is required for normal operation, allocate one */
18235  if( sqlite3GlobalConfig.bMemstat==0 ){
18236    mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
18237  }
18238
18239  return SQLITE_OK;
18240}
18241
18242/*
18243** Deinitialize this module.
18244*/
18245static void memsys5Shutdown(void *NotUsed){
18246  UNUSED_PARAMETER(NotUsed);
18247  mem5.mutex = 0;
18248  return;
18249}
18250
18251#ifdef SQLITE_TEST
18252/*
18253** Open the file indicated and write a log of all unfreed memory
18254** allocations into that log.
18255*/
18256SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
18257  FILE *out;
18258  int i, j, n;
18259  int nMinLog;
18260
18261  if( zFilename==0 || zFilename[0]==0 ){
18262    out = stdout;
18263  }else{
18264    out = fopen(zFilename, "w");
18265    if( out==0 ){
18266      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
18267                      zFilename);
18268      return;
18269    }
18270  }
18271  memsys5Enter();
18272  nMinLog = memsys5Log(mem5.szAtom);
18273  for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
18274    for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
18275    fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
18276  }
18277  fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
18278  fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
18279  fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
18280  fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
18281  fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
18282  fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
18283  fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
18284  fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
18285  memsys5Leave();
18286  if( out==stdout ){
18287    fflush(stdout);
18288  }else{
18289    fclose(out);
18290  }
18291}
18292#endif
18293
18294/*
18295** This routine is the only routine in this file with external
18296** linkage. It returns a pointer to a static sqlite3_mem_methods
18297** struct populated with the memsys5 methods.
18298*/
18299SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
18300  static const sqlite3_mem_methods memsys5Methods = {
18301     memsys5Malloc,
18302     memsys5Free,
18303     memsys5Realloc,
18304     memsys5Size,
18305     memsys5Roundup,
18306     memsys5Init,
18307     memsys5Shutdown,
18308     0
18309  };
18310  return &memsys5Methods;
18311}
18312
18313#endif /* SQLITE_ENABLE_MEMSYS5 */
18314
18315/************** End of mem5.c ************************************************/
18316/************** Begin file mutex.c *******************************************/
18317/*
18318** 2007 August 14
18319**
18320** The author disclaims copyright to this source code.  In place of
18321** a legal notice, here is a blessing:
18322**
18323**    May you do good and not evil.
18324**    May you find forgiveness for yourself and forgive others.
18325**    May you share freely, never taking more than you give.
18326**
18327*************************************************************************
18328** This file contains the C functions that implement mutexes.
18329**
18330** This file contains code that is common across all mutex implementations.
18331*/
18332
18333#if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
18334/*
18335** For debugging purposes, record when the mutex subsystem is initialized
18336** and uninitialized so that we can assert() if there is an attempt to
18337** allocate a mutex while the system is uninitialized.
18338*/
18339static SQLITE_WSD int mutexIsInit = 0;
18340#endif /* SQLITE_DEBUG */
18341
18342
18343#ifndef SQLITE_MUTEX_OMIT
18344/*
18345** Initialize the mutex system.
18346*/
18347SQLITE_PRIVATE int sqlite3MutexInit(void){
18348  int rc = SQLITE_OK;
18349  if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
18350    /* If the xMutexAlloc method has not been set, then the user did not
18351    ** install a mutex implementation via sqlite3_config() prior to
18352    ** sqlite3_initialize() being called. This block copies pointers to
18353    ** the default implementation into the sqlite3GlobalConfig structure.
18354    */
18355    sqlite3_mutex_methods const *pFrom;
18356    sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
18357
18358    if( sqlite3GlobalConfig.bCoreMutex ){
18359      pFrom = sqlite3DefaultMutex();
18360    }else{
18361      pFrom = sqlite3NoopMutex();
18362    }
18363    memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
18364    memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
18365           sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
18366    pTo->xMutexAlloc = pFrom->xMutexAlloc;
18367  }
18368  rc = sqlite3GlobalConfig.mutex.xMutexInit();
18369
18370#ifdef SQLITE_DEBUG
18371  GLOBAL(int, mutexIsInit) = 1;
18372#endif
18373
18374  return rc;
18375}
18376
18377/*
18378** Shutdown the mutex system. This call frees resources allocated by
18379** sqlite3MutexInit().
18380*/
18381SQLITE_PRIVATE int sqlite3MutexEnd(void){
18382  int rc = SQLITE_OK;
18383  if( sqlite3GlobalConfig.mutex.xMutexEnd ){
18384    rc = sqlite3GlobalConfig.mutex.xMutexEnd();
18385  }
18386
18387#ifdef SQLITE_DEBUG
18388  GLOBAL(int, mutexIsInit) = 0;
18389#endif
18390
18391  return rc;
18392}
18393
18394/*
18395** Retrieve a pointer to a static mutex or allocate a new dynamic one.
18396*/
18397SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
18398#ifndef SQLITE_OMIT_AUTOINIT
18399  if( sqlite3_initialize() ) return 0;
18400#endif
18401  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
18402}
18403
18404SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
18405  if( !sqlite3GlobalConfig.bCoreMutex ){
18406    return 0;
18407  }
18408  assert( GLOBAL(int, mutexIsInit) );
18409  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
18410}
18411
18412/*
18413** Free a dynamic mutex.
18414*/
18415SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
18416  if( p ){
18417    sqlite3GlobalConfig.mutex.xMutexFree(p);
18418  }
18419}
18420
18421/*
18422** Obtain the mutex p. If some other thread already has the mutex, block
18423** until it can be obtained.
18424*/
18425SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
18426  if( p ){
18427    sqlite3GlobalConfig.mutex.xMutexEnter(p);
18428  }
18429}
18430
18431/*
18432** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
18433** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
18434*/
18435SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
18436  int rc = SQLITE_OK;
18437  if( p ){
18438    return sqlite3GlobalConfig.mutex.xMutexTry(p);
18439  }
18440  return rc;
18441}
18442
18443/*
18444** The sqlite3_mutex_leave() routine exits a mutex that was previously
18445** entered by the same thread.  The behavior is undefined if the mutex
18446** is not currently entered. If a NULL pointer is passed as an argument
18447** this function is a no-op.
18448*/
18449SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
18450  if( p ){
18451    sqlite3GlobalConfig.mutex.xMutexLeave(p);
18452  }
18453}
18454
18455#ifndef NDEBUG
18456/*
18457** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18458** intended for use inside assert() statements.
18459*/
18460SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
18461  return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
18462}
18463SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
18464  return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
18465}
18466#endif
18467
18468#endif /* !defined(SQLITE_MUTEX_OMIT) */
18469
18470/************** End of mutex.c ***********************************************/
18471/************** Begin file mutex_noop.c **************************************/
18472/*
18473** 2008 October 07
18474**
18475** The author disclaims copyright to this source code.  In place of
18476** a legal notice, here is a blessing:
18477**
18478**    May you do good and not evil.
18479**    May you find forgiveness for yourself and forgive others.
18480**    May you share freely, never taking more than you give.
18481**
18482*************************************************************************
18483** This file contains the C functions that implement mutexes.
18484**
18485** This implementation in this file does not provide any mutual
18486** exclusion and is thus suitable for use only in applications
18487** that use SQLite in a single thread.  The routines defined
18488** here are place-holders.  Applications can substitute working
18489** mutex routines at start-time using the
18490**
18491**     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
18492**
18493** interface.
18494**
18495** If compiled with SQLITE_DEBUG, then additional logic is inserted
18496** that does error checking on mutexes to make sure they are being
18497** called correctly.
18498*/
18499
18500#ifndef SQLITE_MUTEX_OMIT
18501
18502#ifndef SQLITE_DEBUG
18503/*
18504** Stub routines for all mutex methods.
18505**
18506** This routines provide no mutual exclusion or error checking.
18507*/
18508static int noopMutexInit(void){ return SQLITE_OK; }
18509static int noopMutexEnd(void){ return SQLITE_OK; }
18510static sqlite3_mutex *noopMutexAlloc(int id){
18511  UNUSED_PARAMETER(id);
18512  return (sqlite3_mutex*)8;
18513}
18514static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
18515static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
18516static int noopMutexTry(sqlite3_mutex *p){
18517  UNUSED_PARAMETER(p);
18518  return SQLITE_OK;
18519}
18520static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
18521
18522SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
18523  static const sqlite3_mutex_methods sMutex = {
18524    noopMutexInit,
18525    noopMutexEnd,
18526    noopMutexAlloc,
18527    noopMutexFree,
18528    noopMutexEnter,
18529    noopMutexTry,
18530    noopMutexLeave,
18531
18532    0,
18533    0,
18534  };
18535
18536  return &sMutex;
18537}
18538#endif /* !SQLITE_DEBUG */
18539
18540#ifdef SQLITE_DEBUG
18541/*
18542** In this implementation, error checking is provided for testing
18543** and debugging purposes.  The mutexes still do not provide any
18544** mutual exclusion.
18545*/
18546
18547/*
18548** The mutex object
18549*/
18550typedef struct sqlite3_debug_mutex {
18551  int id;     /* The mutex type */
18552  int cnt;    /* Number of entries without a matching leave */
18553} sqlite3_debug_mutex;
18554
18555/*
18556** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18557** intended for use inside assert() statements.
18558*/
18559static int debugMutexHeld(sqlite3_mutex *pX){
18560  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18561  return p==0 || p->cnt>0;
18562}
18563static int debugMutexNotheld(sqlite3_mutex *pX){
18564  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18565  return p==0 || p->cnt==0;
18566}
18567
18568/*
18569** Initialize and deinitialize the mutex subsystem.
18570*/
18571static int debugMutexInit(void){ return SQLITE_OK; }
18572static int debugMutexEnd(void){ return SQLITE_OK; }
18573
18574/*
18575** The sqlite3_mutex_alloc() routine allocates a new
18576** mutex and returns a pointer to it.  If it returns NULL
18577** that means that a mutex could not be allocated.
18578*/
18579static sqlite3_mutex *debugMutexAlloc(int id){
18580  static sqlite3_debug_mutex aStatic[6];
18581  sqlite3_debug_mutex *pNew = 0;
18582  switch( id ){
18583    case SQLITE_MUTEX_FAST:
18584    case SQLITE_MUTEX_RECURSIVE: {
18585      pNew = sqlite3Malloc(sizeof(*pNew));
18586      if( pNew ){
18587        pNew->id = id;
18588        pNew->cnt = 0;
18589      }
18590      break;
18591    }
18592    default: {
18593      assert( id-2 >= 0 );
18594      assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
18595      pNew = &aStatic[id-2];
18596      pNew->id = id;
18597      break;
18598    }
18599  }
18600  return (sqlite3_mutex*)pNew;
18601}
18602
18603/*
18604** This routine deallocates a previously allocated mutex.
18605*/
18606static void debugMutexFree(sqlite3_mutex *pX){
18607  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18608  assert( p->cnt==0 );
18609  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18610  sqlite3_free(p);
18611}
18612
18613/*
18614** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18615** to enter a mutex.  If another thread is already within the mutex,
18616** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18617** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
18618** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
18619** be entered multiple times by the same thread.  In such cases the,
18620** mutex must be exited an equal number of times before another thread
18621** can enter.  If the same thread tries to enter any other kind of mutex
18622** more than once, the behavior is undefined.
18623*/
18624static void debugMutexEnter(sqlite3_mutex *pX){
18625  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18626  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
18627  p->cnt++;
18628}
18629static int debugMutexTry(sqlite3_mutex *pX){
18630  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18631  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
18632  p->cnt++;
18633  return SQLITE_OK;
18634}
18635
18636/*
18637** The sqlite3_mutex_leave() routine exits a mutex that was
18638** previously entered by the same thread.  The behavior
18639** is undefined if the mutex is not currently entered or
18640** is not currently allocated.  SQLite will never do either.
18641*/
18642static void debugMutexLeave(sqlite3_mutex *pX){
18643  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18644  assert( debugMutexHeld(pX) );
18645  p->cnt--;
18646  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
18647}
18648
18649SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
18650  static const sqlite3_mutex_methods sMutex = {
18651    debugMutexInit,
18652    debugMutexEnd,
18653    debugMutexAlloc,
18654    debugMutexFree,
18655    debugMutexEnter,
18656    debugMutexTry,
18657    debugMutexLeave,
18658
18659    debugMutexHeld,
18660    debugMutexNotheld
18661  };
18662
18663  return &sMutex;
18664}
18665#endif /* SQLITE_DEBUG */
18666
18667/*
18668** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
18669** is used regardless of the run-time threadsafety setting.
18670*/
18671#ifdef SQLITE_MUTEX_NOOP
18672SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18673  return sqlite3NoopMutex();
18674}
18675#endif /* defined(SQLITE_MUTEX_NOOP) */
18676#endif /* !defined(SQLITE_MUTEX_OMIT) */
18677
18678/************** End of mutex_noop.c ******************************************/
18679/************** Begin file mutex_unix.c **************************************/
18680/*
18681** 2007 August 28
18682**
18683** The author disclaims copyright to this source code.  In place of
18684** a legal notice, here is a blessing:
18685**
18686**    May you do good and not evil.
18687**    May you find forgiveness for yourself and forgive others.
18688**    May you share freely, never taking more than you give.
18689**
18690*************************************************************************
18691** This file contains the C functions that implement mutexes for pthreads
18692*/
18693
18694/*
18695** The code in this file is only used if we are compiling threadsafe
18696** under unix with pthreads.
18697**
18698** Note that this implementation requires a version of pthreads that
18699** supports recursive mutexes.
18700*/
18701#ifdef SQLITE_MUTEX_PTHREADS
18702
18703#include <pthread.h>
18704
18705/*
18706** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
18707** are necessary under two condidtions:  (1) Debug builds and (2) using
18708** home-grown mutexes.  Encapsulate these conditions into a single #define.
18709*/
18710#if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
18711# define SQLITE_MUTEX_NREF 1
18712#else
18713# define SQLITE_MUTEX_NREF 0
18714#endif
18715
18716/*
18717** Each recursive mutex is an instance of the following structure.
18718*/
18719struct sqlite3_mutex {
18720  pthread_mutex_t mutex;     /* Mutex controlling the lock */
18721#if SQLITE_MUTEX_NREF
18722  int id;                    /* Mutex type */
18723  volatile int nRef;         /* Number of entrances */
18724  volatile pthread_t owner;  /* Thread that is within this mutex */
18725  int trace;                 /* True to trace changes */
18726#endif
18727};
18728#if SQLITE_MUTEX_NREF
18729#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
18730#else
18731#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
18732#endif
18733
18734/*
18735** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18736** intended for use only inside assert() statements.  On some platforms,
18737** there might be race conditions that can cause these routines to
18738** deliver incorrect results.  In particular, if pthread_equal() is
18739** not an atomic operation, then these routines might delivery
18740** incorrect results.  On most platforms, pthread_equal() is a
18741** comparison of two integers and is therefore atomic.  But we are
18742** told that HPUX is not such a platform.  If so, then these routines
18743** will not always work correctly on HPUX.
18744**
18745** On those platforms where pthread_equal() is not atomic, SQLite
18746** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
18747** make sure no assert() statements are evaluated and hence these
18748** routines are never called.
18749*/
18750#if !defined(NDEBUG) || defined(SQLITE_DEBUG)
18751static int pthreadMutexHeld(sqlite3_mutex *p){
18752  return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
18753}
18754static int pthreadMutexNotheld(sqlite3_mutex *p){
18755  return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
18756}
18757#endif
18758
18759/*
18760** Initialize and deinitialize the mutex subsystem.
18761*/
18762static int pthreadMutexInit(void){ return SQLITE_OK; }
18763static int pthreadMutexEnd(void){ return SQLITE_OK; }
18764
18765/*
18766** The sqlite3_mutex_alloc() routine allocates a new
18767** mutex and returns a pointer to it.  If it returns NULL
18768** that means that a mutex could not be allocated.  SQLite
18769** will unwind its stack and return an error.  The argument
18770** to sqlite3_mutex_alloc() is one of these integer constants:
18771**
18772** <ul>
18773** <li>  SQLITE_MUTEX_FAST
18774** <li>  SQLITE_MUTEX_RECURSIVE
18775** <li>  SQLITE_MUTEX_STATIC_MASTER
18776** <li>  SQLITE_MUTEX_STATIC_MEM
18777** <li>  SQLITE_MUTEX_STATIC_MEM2
18778** <li>  SQLITE_MUTEX_STATIC_PRNG
18779** <li>  SQLITE_MUTEX_STATIC_LRU
18780** <li>  SQLITE_MUTEX_STATIC_PMEM
18781** </ul>
18782**
18783** The first two constants cause sqlite3_mutex_alloc() to create
18784** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
18785** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
18786** The mutex implementation does not need to make a distinction
18787** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
18788** not want to.  But SQLite will only request a recursive mutex in
18789** cases where it really needs one.  If a faster non-recursive mutex
18790** implementation is available on the host platform, the mutex subsystem
18791** might return such a mutex in response to SQLITE_MUTEX_FAST.
18792**
18793** The other allowed parameters to sqlite3_mutex_alloc() each return
18794** a pointer to a static preexisting mutex.  Six static mutexes are
18795** used by the current version of SQLite.  Future versions of SQLite
18796** may add additional static mutexes.  Static mutexes are for internal
18797** use by SQLite only.  Applications that use SQLite mutexes should
18798** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
18799** SQLITE_MUTEX_RECURSIVE.
18800**
18801** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
18802** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
18803** returns a different mutex on every call.  But for the static
18804** mutex types, the same mutex is returned on every call that has
18805** the same type number.
18806*/
18807static sqlite3_mutex *pthreadMutexAlloc(int iType){
18808  static sqlite3_mutex staticMutexes[] = {
18809    SQLITE3_MUTEX_INITIALIZER,
18810    SQLITE3_MUTEX_INITIALIZER,
18811    SQLITE3_MUTEX_INITIALIZER,
18812    SQLITE3_MUTEX_INITIALIZER,
18813    SQLITE3_MUTEX_INITIALIZER,
18814    SQLITE3_MUTEX_INITIALIZER
18815  };
18816  sqlite3_mutex *p;
18817  switch( iType ){
18818    case SQLITE_MUTEX_RECURSIVE: {
18819      p = sqlite3MallocZero( sizeof(*p) );
18820      if( p ){
18821#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18822        /* If recursive mutexes are not available, we will have to
18823        ** build our own.  See below. */
18824        pthread_mutex_init(&p->mutex, 0);
18825#else
18826        /* Use a recursive mutex if it is available */
18827        pthread_mutexattr_t recursiveAttr;
18828        pthread_mutexattr_init(&recursiveAttr);
18829        pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
18830        pthread_mutex_init(&p->mutex, &recursiveAttr);
18831        pthread_mutexattr_destroy(&recursiveAttr);
18832#endif
18833#if SQLITE_MUTEX_NREF
18834        p->id = iType;
18835#endif
18836      }
18837      break;
18838    }
18839    case SQLITE_MUTEX_FAST: {
18840      p = sqlite3MallocZero( sizeof(*p) );
18841      if( p ){
18842#if SQLITE_MUTEX_NREF
18843        p->id = iType;
18844#endif
18845        pthread_mutex_init(&p->mutex, 0);
18846      }
18847      break;
18848    }
18849    default: {
18850      assert( iType-2 >= 0 );
18851      assert( iType-2 < ArraySize(staticMutexes) );
18852      p = &staticMutexes[iType-2];
18853#if SQLITE_MUTEX_NREF
18854      p->id = iType;
18855#endif
18856      break;
18857    }
18858  }
18859  return p;
18860}
18861
18862
18863/*
18864** This routine deallocates a previously
18865** allocated mutex.  SQLite is careful to deallocate every
18866** mutex that it allocates.
18867*/
18868static void pthreadMutexFree(sqlite3_mutex *p){
18869  assert( p->nRef==0 );
18870  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18871  pthread_mutex_destroy(&p->mutex);
18872  sqlite3_free(p);
18873}
18874
18875/*
18876** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18877** to enter a mutex.  If another thread is already within the mutex,
18878** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18879** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
18880** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
18881** be entered multiple times by the same thread.  In such cases the,
18882** mutex must be exited an equal number of times before another thread
18883** can enter.  If the same thread tries to enter any other kind of mutex
18884** more than once, the behavior is undefined.
18885*/
18886static void pthreadMutexEnter(sqlite3_mutex *p){
18887  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
18888
18889#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18890  /* If recursive mutexes are not available, then we have to grow
18891  ** our own.  This implementation assumes that pthread_equal()
18892  ** is atomic - that it cannot be deceived into thinking self
18893  ** and p->owner are equal if p->owner changes between two values
18894  ** that are not equal to self while the comparison is taking place.
18895  ** This implementation also assumes a coherent cache - that
18896  ** separate processes cannot read different values from the same
18897  ** address at the same time.  If either of these two conditions
18898  ** are not met, then the mutexes will fail and problems will result.
18899  */
18900  {
18901    pthread_t self = pthread_self();
18902    if( p->nRef>0 && pthread_equal(p->owner, self) ){
18903      p->nRef++;
18904    }else{
18905      pthread_mutex_lock(&p->mutex);
18906      assert( p->nRef==0 );
18907      p->owner = self;
18908      p->nRef = 1;
18909    }
18910  }
18911#else
18912  /* Use the built-in recursive mutexes if they are available.
18913  */
18914  pthread_mutex_lock(&p->mutex);
18915#if SQLITE_MUTEX_NREF
18916  assert( p->nRef>0 || p->owner==0 );
18917  p->owner = pthread_self();
18918  p->nRef++;
18919#endif
18920#endif
18921
18922#ifdef SQLITE_DEBUG
18923  if( p->trace ){
18924    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18925  }
18926#endif
18927}
18928static int pthreadMutexTry(sqlite3_mutex *p){
18929  int rc;
18930  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
18931
18932#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18933  /* If recursive mutexes are not available, then we have to grow
18934  ** our own.  This implementation assumes that pthread_equal()
18935  ** is atomic - that it cannot be deceived into thinking self
18936  ** and p->owner are equal if p->owner changes between two values
18937  ** that are not equal to self while the comparison is taking place.
18938  ** This implementation also assumes a coherent cache - that
18939  ** separate processes cannot read different values from the same
18940  ** address at the same time.  If either of these two conditions
18941  ** are not met, then the mutexes will fail and problems will result.
18942  */
18943  {
18944    pthread_t self = pthread_self();
18945    if( p->nRef>0 && pthread_equal(p->owner, self) ){
18946      p->nRef++;
18947      rc = SQLITE_OK;
18948    }else if( pthread_mutex_trylock(&p->mutex)==0 ){
18949      assert( p->nRef==0 );
18950      p->owner = self;
18951      p->nRef = 1;
18952      rc = SQLITE_OK;
18953    }else{
18954      rc = SQLITE_BUSY;
18955    }
18956  }
18957#else
18958  /* Use the built-in recursive mutexes if they are available.
18959  */
18960  if( pthread_mutex_trylock(&p->mutex)==0 ){
18961#if SQLITE_MUTEX_NREF
18962    p->owner = pthread_self();
18963    p->nRef++;
18964#endif
18965    rc = SQLITE_OK;
18966  }else{
18967    rc = SQLITE_BUSY;
18968  }
18969#endif
18970
18971#ifdef SQLITE_DEBUG
18972  if( rc==SQLITE_OK && p->trace ){
18973    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18974  }
18975#endif
18976  return rc;
18977}
18978
18979/*
18980** The sqlite3_mutex_leave() routine exits a mutex that was
18981** previously entered by the same thread.  The behavior
18982** is undefined if the mutex is not currently entered or
18983** is not currently allocated.  SQLite will never do either.
18984*/
18985static void pthreadMutexLeave(sqlite3_mutex *p){
18986  assert( pthreadMutexHeld(p) );
18987#if SQLITE_MUTEX_NREF
18988  p->nRef--;
18989  if( p->nRef==0 ) p->owner = 0;
18990#endif
18991  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
18992
18993#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18994  if( p->nRef==0 ){
18995    pthread_mutex_unlock(&p->mutex);
18996  }
18997#else
18998  pthread_mutex_unlock(&p->mutex);
18999#endif
19000
19001#ifdef SQLITE_DEBUG
19002  if( p->trace ){
19003    printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
19004  }
19005#endif
19006}
19007
19008SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
19009  static const sqlite3_mutex_methods sMutex = {
19010    pthreadMutexInit,
19011    pthreadMutexEnd,
19012    pthreadMutexAlloc,
19013    pthreadMutexFree,
19014    pthreadMutexEnter,
19015    pthreadMutexTry,
19016    pthreadMutexLeave,
19017#ifdef SQLITE_DEBUG
19018    pthreadMutexHeld,
19019    pthreadMutexNotheld
19020#else
19021    0,
19022    0
19023#endif
19024  };
19025
19026  return &sMutex;
19027}
19028
19029#endif /* SQLITE_MUTEX_PTHREADS */
19030
19031/************** End of mutex_unix.c ******************************************/
19032/************** Begin file mutex_w32.c ***************************************/
19033/*
19034** 2007 August 14
19035**
19036** The author disclaims copyright to this source code.  In place of
19037** a legal notice, here is a blessing:
19038**
19039**    May you do good and not evil.
19040**    May you find forgiveness for yourself and forgive others.
19041**    May you share freely, never taking more than you give.
19042**
19043*************************************************************************
19044** This file contains the C functions that implement mutexes for win32
19045*/
19046
19047#if SQLITE_OS_WIN
19048/*
19049** Include the header file for the Windows VFS.
19050*/
19051/************** Include os_win.h in the middle of mutex_w32.c ****************/
19052/************** Begin file os_win.h ******************************************/
19053/*
19054** 2013 November 25
19055**
19056** The author disclaims copyright to this source code.  In place of
19057** a legal notice, here is a blessing:
19058**
19059**    May you do good and not evil.
19060**    May you find forgiveness for yourself and forgive others.
19061**    May you share freely, never taking more than you give.
19062**
19063******************************************************************************
19064**
19065** This file contains code that is specific to Windows.
19066*/
19067#ifndef _OS_WIN_H_
19068#define _OS_WIN_H_
19069
19070/*
19071** Include the primary Windows SDK header file.
19072*/
19073#include "windows.h"
19074
19075#ifdef __CYGWIN__
19076# include <sys/cygwin.h>
19077# include <errno.h> /* amalgamator: dontcache */
19078#endif
19079
19080/*
19081** Determine if we are dealing with Windows NT.
19082**
19083** We ought to be able to determine if we are compiling for Windows 9x or
19084** Windows NT using the _WIN32_WINNT macro as follows:
19085**
19086** #if defined(_WIN32_WINNT)
19087** # define SQLITE_OS_WINNT 1
19088** #else
19089** # define SQLITE_OS_WINNT 0
19090** #endif
19091**
19092** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
19093** it ought to, so the above test does not work.  We'll just assume that
19094** everything is Windows NT unless the programmer explicitly says otherwise
19095** by setting SQLITE_OS_WINNT to 0.
19096*/
19097#if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
19098# define SQLITE_OS_WINNT 1
19099#endif
19100
19101/*
19102** Determine if we are dealing with Windows CE - which has a much reduced
19103** API.
19104*/
19105#if defined(_WIN32_WCE)
19106# define SQLITE_OS_WINCE 1
19107#else
19108# define SQLITE_OS_WINCE 0
19109#endif
19110
19111/*
19112** Determine if we are dealing with WinRT, which provides only a subset of
19113** the full Win32 API.
19114*/
19115#if !defined(SQLITE_OS_WINRT)
19116# define SQLITE_OS_WINRT 0
19117#endif
19118
19119#endif /* _OS_WIN_H_ */
19120
19121/************** End of os_win.h **********************************************/
19122/************** Continuing where we left off in mutex_w32.c ******************/
19123#endif
19124
19125/*
19126** The code in this file is only used if we are compiling multithreaded
19127** on a win32 system.
19128*/
19129#ifdef SQLITE_MUTEX_W32
19130
19131/*
19132** Each recursive mutex is an instance of the following structure.
19133*/
19134struct sqlite3_mutex {
19135  CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
19136  int id;                    /* Mutex type */
19137#ifdef SQLITE_DEBUG
19138  volatile int nRef;         /* Number of enterances */
19139  volatile DWORD owner;      /* Thread holding this mutex */
19140  int trace;                 /* True to trace changes */
19141#endif
19142};
19143#define SQLITE_W32_MUTEX_INITIALIZER { 0 }
19144#ifdef SQLITE_DEBUG
19145#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
19146#else
19147#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
19148#endif
19149
19150/*
19151** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
19152** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
19153**
19154** Here is an interesting observation:  Win95, Win98, and WinME lack
19155** the LockFileEx() API.  But we can still statically link against that
19156** API as long as we don't call it win running Win95/98/ME.  A call to
19157** this routine is used to determine if the host is Win95/98/ME or
19158** WinNT/2K/XP so that we will know whether or not we can safely call
19159** the LockFileEx() API.
19160**
19161** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
19162** which is only available if your application was compiled with
19163** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
19164** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef
19165** this out as well.
19166*/
19167#if 0
19168#if SQLITE_OS_WINCE || SQLITE_OS_WINRT
19169# define mutexIsNT()  (1)
19170#else
19171  static int mutexIsNT(void){
19172    static int osType = 0;
19173    if( osType==0 ){
19174      OSVERSIONINFO sInfo;
19175      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
19176      GetVersionEx(&sInfo);
19177      osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
19178    }
19179    return osType==2;
19180  }
19181#endif /* SQLITE_OS_WINCE || SQLITE_OS_WINRT */
19182#endif
19183
19184#ifdef SQLITE_DEBUG
19185/*
19186** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
19187** intended for use only inside assert() statements.
19188*/
19189static int winMutexHeld(sqlite3_mutex *p){
19190  return p->nRef!=0 && p->owner==GetCurrentThreadId();
19191}
19192static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
19193  return p->nRef==0 || p->owner!=tid;
19194}
19195static int winMutexNotheld(sqlite3_mutex *p){
19196  DWORD tid = GetCurrentThreadId();
19197  return winMutexNotheld2(p, tid);
19198}
19199#endif
19200
19201
19202/*
19203** Initialize and deinitialize the mutex subsystem.
19204*/
19205static sqlite3_mutex winMutex_staticMutexes[6] = {
19206  SQLITE3_MUTEX_INITIALIZER,
19207  SQLITE3_MUTEX_INITIALIZER,
19208  SQLITE3_MUTEX_INITIALIZER,
19209  SQLITE3_MUTEX_INITIALIZER,
19210  SQLITE3_MUTEX_INITIALIZER,
19211  SQLITE3_MUTEX_INITIALIZER
19212};
19213static int winMutex_isInit = 0;
19214/* As winMutexInit() and winMutexEnd() are called as part
19215** of the sqlite3_initialize and sqlite3_shutdown()
19216** processing, the "interlocked" magic is probably not
19217** strictly necessary.
19218*/
19219static LONG winMutex_lock = 0;
19220
19221SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
19222
19223static int winMutexInit(void){
19224  /* The first to increment to 1 does actual initialization */
19225  if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
19226    int i;
19227    for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
19228#if SQLITE_OS_WINRT
19229      InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
19230#else
19231      InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
19232#endif
19233    }
19234    winMutex_isInit = 1;
19235  }else{
19236    /* Someone else is in the process of initing the static mutexes */
19237    while( !winMutex_isInit ){
19238      sqlite3_win32_sleep(1);
19239    }
19240  }
19241  return SQLITE_OK;
19242}
19243
19244static int winMutexEnd(void){
19245  /* The first to decrement to 0 does actual shutdown
19246  ** (which should be the last to shutdown.) */
19247  if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
19248    if( winMutex_isInit==1 ){
19249      int i;
19250      for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
19251        DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
19252      }
19253      winMutex_isInit = 0;
19254    }
19255  }
19256  return SQLITE_OK;
19257}
19258
19259/*
19260** The sqlite3_mutex_alloc() routine allocates a new
19261** mutex and returns a pointer to it.  If it returns NULL
19262** that means that a mutex could not be allocated.  SQLite
19263** will unwind its stack and return an error.  The argument
19264** to sqlite3_mutex_alloc() is one of these integer constants:
19265**
19266** <ul>
19267** <li>  SQLITE_MUTEX_FAST
19268** <li>  SQLITE_MUTEX_RECURSIVE
19269** <li>  SQLITE_MUTEX_STATIC_MASTER
19270** <li>  SQLITE_MUTEX_STATIC_MEM
19271** <li>  SQLITE_MUTEX_STATIC_MEM2
19272** <li>  SQLITE_MUTEX_STATIC_PRNG
19273** <li>  SQLITE_MUTEX_STATIC_LRU
19274** <li>  SQLITE_MUTEX_STATIC_PMEM
19275** </ul>
19276**
19277** The first two constants cause sqlite3_mutex_alloc() to create
19278** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
19279** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
19280** The mutex implementation does not need to make a distinction
19281** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
19282** not want to.  But SQLite will only request a recursive mutex in
19283** cases where it really needs one.  If a faster non-recursive mutex
19284** implementation is available on the host platform, the mutex subsystem
19285** might return such a mutex in response to SQLITE_MUTEX_FAST.
19286**
19287** The other allowed parameters to sqlite3_mutex_alloc() each return
19288** a pointer to a static preexisting mutex.  Six static mutexes are
19289** used by the current version of SQLite.  Future versions of SQLite
19290** may add additional static mutexes.  Static mutexes are for internal
19291** use by SQLite only.  Applications that use SQLite mutexes should
19292** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
19293** SQLITE_MUTEX_RECURSIVE.
19294**
19295** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
19296** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
19297** returns a different mutex on every call.  But for the static
19298** mutex types, the same mutex is returned on every call that has
19299** the same type number.
19300*/
19301static sqlite3_mutex *winMutexAlloc(int iType){
19302  sqlite3_mutex *p;
19303
19304  switch( iType ){
19305    case SQLITE_MUTEX_FAST:
19306    case SQLITE_MUTEX_RECURSIVE: {
19307      p = sqlite3MallocZero( sizeof(*p) );
19308      if( p ){
19309#ifdef SQLITE_DEBUG
19310        p->id = iType;
19311#endif
19312#if SQLITE_OS_WINRT
19313        InitializeCriticalSectionEx(&p->mutex, 0, 0);
19314#else
19315        InitializeCriticalSection(&p->mutex);
19316#endif
19317      }
19318      break;
19319    }
19320    default: {
19321      assert( winMutex_isInit==1 );
19322      assert( iType-2 >= 0 );
19323      assert( iType-2 < ArraySize(winMutex_staticMutexes) );
19324      p = &winMutex_staticMutexes[iType-2];
19325#ifdef SQLITE_DEBUG
19326      p->id = iType;
19327#endif
19328      break;
19329    }
19330  }
19331  return p;
19332}
19333
19334
19335/*
19336** This routine deallocates a previously
19337** allocated mutex.  SQLite is careful to deallocate every
19338** mutex that it allocates.
19339*/
19340static void winMutexFree(sqlite3_mutex *p){
19341  assert( p );
19342  assert( p->nRef==0 && p->owner==0 );
19343  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
19344  DeleteCriticalSection(&p->mutex);
19345  sqlite3_free(p);
19346}
19347
19348/*
19349** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
19350** to enter a mutex.  If another thread is already within the mutex,
19351** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
19352** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
19353** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
19354** be entered multiple times by the same thread.  In such cases the,
19355** mutex must be exited an equal number of times before another thread
19356** can enter.  If the same thread tries to enter any other kind of mutex
19357** more than once, the behavior is undefined.
19358*/
19359static void winMutexEnter(sqlite3_mutex *p){
19360#ifdef SQLITE_DEBUG
19361  DWORD tid = GetCurrentThreadId();
19362  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
19363#endif
19364  EnterCriticalSection(&p->mutex);
19365#ifdef SQLITE_DEBUG
19366  assert( p->nRef>0 || p->owner==0 );
19367  p->owner = tid;
19368  p->nRef++;
19369  if( p->trace ){
19370    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
19371  }
19372#endif
19373}
19374static int winMutexTry(sqlite3_mutex *p){
19375#ifndef NDEBUG
19376  DWORD tid = GetCurrentThreadId();
19377#endif
19378  int rc = SQLITE_BUSY;
19379  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
19380  /*
19381  ** The sqlite3_mutex_try() routine is very rarely used, and when it
19382  ** is used it is merely an optimization.  So it is OK for it to always
19383  ** fail.
19384  **
19385  ** The TryEnterCriticalSection() interface is only available on WinNT.
19386  ** And some windows compilers complain if you try to use it without
19387  ** first doing some #defines that prevent SQLite from building on Win98.
19388  ** For that reason, we will omit this optimization for now.  See
19389  ** ticket #2685.
19390  */
19391#if 0
19392  if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
19393    p->owner = tid;
19394    p->nRef++;
19395    rc = SQLITE_OK;
19396  }
19397#else
19398  UNUSED_PARAMETER(p);
19399#endif
19400#ifdef SQLITE_DEBUG
19401  if( rc==SQLITE_OK && p->trace ){
19402    printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
19403  }
19404#endif
19405  return rc;
19406}
19407
19408/*
19409** The sqlite3_mutex_leave() routine exits a mutex that was
19410** previously entered by the same thread.  The behavior
19411** is undefined if the mutex is not currently entered or
19412** is not currently allocated.  SQLite will never do either.
19413*/
19414static void winMutexLeave(sqlite3_mutex *p){
19415#ifndef NDEBUG
19416  DWORD tid = GetCurrentThreadId();
19417  assert( p->nRef>0 );
19418  assert( p->owner==tid );
19419  p->nRef--;
19420  if( p->nRef==0 ) p->owner = 0;
19421  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
19422#endif
19423  LeaveCriticalSection(&p->mutex);
19424#ifdef SQLITE_DEBUG
19425  if( p->trace ){
19426    printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
19427  }
19428#endif
19429}
19430
19431SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
19432  static const sqlite3_mutex_methods sMutex = {
19433    winMutexInit,
19434    winMutexEnd,
19435    winMutexAlloc,
19436    winMutexFree,
19437    winMutexEnter,
19438    winMutexTry,
19439    winMutexLeave,
19440#ifdef SQLITE_DEBUG
19441    winMutexHeld,
19442    winMutexNotheld
19443#else
19444    0,
19445    0
19446#endif
19447  };
19448
19449  return &sMutex;
19450}
19451#endif /* SQLITE_MUTEX_W32 */
19452
19453/************** End of mutex_w32.c *******************************************/
19454/************** Begin file malloc.c ******************************************/
19455/*
19456** 2001 September 15
19457**
19458** The author disclaims copyright to this source code.  In place of
19459** a legal notice, here is a blessing:
19460**
19461**    May you do good and not evil.
19462**    May you find forgiveness for yourself and forgive others.
19463**    May you share freely, never taking more than you give.
19464**
19465*************************************************************************
19466**
19467** Memory allocation functions used throughout sqlite.
19468*/
19469/* #include <stdarg.h> */
19470
19471/*
19472** Attempt to release up to n bytes of non-essential memory currently
19473** held by SQLite. An example of non-essential memory is memory used to
19474** cache database pages that are not currently in use.
19475*/
19476SQLITE_API int sqlite3_release_memory(int n){
19477#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
19478  return sqlite3PcacheReleaseMemory(n);
19479#else
19480  /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
19481  ** is a no-op returning zero if SQLite is not compiled with
19482  ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
19483  UNUSED_PARAMETER(n);
19484  return 0;
19485#endif
19486}
19487
19488/*
19489** An instance of the following object records the location of
19490** each unused scratch buffer.
19491*/
19492typedef struct ScratchFreeslot {
19493  struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
19494} ScratchFreeslot;
19495
19496/*
19497** State information local to the memory allocation subsystem.
19498*/
19499static SQLITE_WSD struct Mem0Global {
19500  sqlite3_mutex *mutex;         /* Mutex to serialize access */
19501
19502  /*
19503  ** The alarm callback and its arguments.  The mem0.mutex lock will
19504  ** be held while the callback is running.  Recursive calls into
19505  ** the memory subsystem are allowed, but no new callbacks will be
19506  ** issued.
19507  */
19508  sqlite3_int64 alarmThreshold;
19509  void (*alarmCallback)(void*, sqlite3_int64,int);
19510  void *alarmArg;
19511
19512  /*
19513  ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
19514  ** (so that a range test can be used to determine if an allocation
19515  ** being freed came from pScratch) and a pointer to the list of
19516  ** unused scratch allocations.
19517  */
19518  void *pScratchEnd;
19519  ScratchFreeslot *pScratchFree;
19520  u32 nScratchFree;
19521
19522  /*
19523  ** True if heap is nearly "full" where "full" is defined by the
19524  ** sqlite3_soft_heap_limit() setting.
19525  */
19526  int nearlyFull;
19527} mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
19528
19529#define mem0 GLOBAL(struct Mem0Global, mem0)
19530
19531/*
19532** This routine runs when the memory allocator sees that the
19533** total memory allocation is about to exceed the soft heap
19534** limit.
19535*/
19536static void softHeapLimitEnforcer(
19537  void *NotUsed,
19538  sqlite3_int64 NotUsed2,
19539  int allocSize
19540){
19541  UNUSED_PARAMETER2(NotUsed, NotUsed2);
19542  sqlite3_release_memory(allocSize);
19543}
19544
19545/*
19546** Change the alarm callback
19547*/
19548static int sqlite3MemoryAlarm(
19549  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
19550  void *pArg,
19551  sqlite3_int64 iThreshold
19552){
19553  int nUsed;
19554  sqlite3_mutex_enter(mem0.mutex);
19555  mem0.alarmCallback = xCallback;
19556  mem0.alarmArg = pArg;
19557  mem0.alarmThreshold = iThreshold;
19558  nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
19559  mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
19560  sqlite3_mutex_leave(mem0.mutex);
19561  return SQLITE_OK;
19562}
19563
19564#ifndef SQLITE_OMIT_DEPRECATED
19565/*
19566** Deprecated external interface.  Internal/core SQLite code
19567** should call sqlite3MemoryAlarm.
19568*/
19569SQLITE_API int sqlite3_memory_alarm(
19570  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
19571  void *pArg,
19572  sqlite3_int64 iThreshold
19573){
19574  return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
19575}
19576#endif
19577
19578/*
19579** Set the soft heap-size limit for the library. Passing a zero or
19580** negative value indicates no limit.
19581*/
19582SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
19583  sqlite3_int64 priorLimit;
19584  sqlite3_int64 excess;
19585#ifndef SQLITE_OMIT_AUTOINIT
19586  int rc = sqlite3_initialize();
19587  if( rc ) return -1;
19588#endif
19589  sqlite3_mutex_enter(mem0.mutex);
19590  priorLimit = mem0.alarmThreshold;
19591  sqlite3_mutex_leave(mem0.mutex);
19592  if( n<0 ) return priorLimit;
19593  if( n>0 ){
19594    sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
19595  }else{
19596    sqlite3MemoryAlarm(0, 0, 0);
19597  }
19598  excess = sqlite3_memory_used() - n;
19599  if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
19600  return priorLimit;
19601}
19602SQLITE_API void sqlite3_soft_heap_limit(int n){
19603  if( n<0 ) n = 0;
19604  sqlite3_soft_heap_limit64(n);
19605}
19606
19607/*
19608** Initialize the memory allocation subsystem.
19609*/
19610SQLITE_PRIVATE int sqlite3MallocInit(void){
19611  if( sqlite3GlobalConfig.m.xMalloc==0 ){
19612    sqlite3MemSetDefault();
19613  }
19614  memset(&mem0, 0, sizeof(mem0));
19615  if( sqlite3GlobalConfig.bCoreMutex ){
19616    mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
19617  }
19618  if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
19619      && sqlite3GlobalConfig.nScratch>0 ){
19620    int i, n, sz;
19621    ScratchFreeslot *pSlot;
19622    sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
19623    sqlite3GlobalConfig.szScratch = sz;
19624    pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
19625    n = sqlite3GlobalConfig.nScratch;
19626    mem0.pScratchFree = pSlot;
19627    mem0.nScratchFree = n;
19628    for(i=0; i<n-1; i++){
19629      pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
19630      pSlot = pSlot->pNext;
19631    }
19632    pSlot->pNext = 0;
19633    mem0.pScratchEnd = (void*)&pSlot[1];
19634  }else{
19635    mem0.pScratchEnd = 0;
19636    sqlite3GlobalConfig.pScratch = 0;
19637    sqlite3GlobalConfig.szScratch = 0;
19638    sqlite3GlobalConfig.nScratch = 0;
19639  }
19640  if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
19641      || sqlite3GlobalConfig.nPage<1 ){
19642    sqlite3GlobalConfig.pPage = 0;
19643    sqlite3GlobalConfig.szPage = 0;
19644    sqlite3GlobalConfig.nPage = 0;
19645  }
19646  return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
19647}
19648
19649/*
19650** Return true if the heap is currently under memory pressure - in other
19651** words if the amount of heap used is close to the limit set by
19652** sqlite3_soft_heap_limit().
19653*/
19654SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
19655  return mem0.nearlyFull;
19656}
19657
19658/*
19659** Deinitialize the memory allocation subsystem.
19660*/
19661SQLITE_PRIVATE void sqlite3MallocEnd(void){
19662  if( sqlite3GlobalConfig.m.xShutdown ){
19663    sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
19664  }
19665  memset(&mem0, 0, sizeof(mem0));
19666}
19667
19668/*
19669** Return the amount of memory currently checked out.
19670*/
19671SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
19672  int n, mx;
19673  sqlite3_int64 res;
19674  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
19675  res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
19676  return res;
19677}
19678
19679/*
19680** Return the maximum amount of memory that has ever been
19681** checked out since either the beginning of this process
19682** or since the most recent reset.
19683*/
19684SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
19685  int n, mx;
19686  sqlite3_int64 res;
19687  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
19688  res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
19689  return res;
19690}
19691
19692/*
19693** Trigger the alarm
19694*/
19695static void sqlite3MallocAlarm(int nByte){
19696  void (*xCallback)(void*,sqlite3_int64,int);
19697  sqlite3_int64 nowUsed;
19698  void *pArg;
19699  if( mem0.alarmCallback==0 ) return;
19700  xCallback = mem0.alarmCallback;
19701  nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
19702  pArg = mem0.alarmArg;
19703  mem0.alarmCallback = 0;
19704  sqlite3_mutex_leave(mem0.mutex);
19705  xCallback(pArg, nowUsed, nByte);
19706  sqlite3_mutex_enter(mem0.mutex);
19707  mem0.alarmCallback = xCallback;
19708  mem0.alarmArg = pArg;
19709}
19710
19711/*
19712** Do a memory allocation with statistics and alarms.  Assume the
19713** lock is already held.
19714*/
19715static int mallocWithAlarm(int n, void **pp){
19716  int nFull;
19717  void *p;
19718  assert( sqlite3_mutex_held(mem0.mutex) );
19719  nFull = sqlite3GlobalConfig.m.xRoundup(n);
19720  sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
19721  if( mem0.alarmCallback!=0 ){
19722    int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
19723    if( nUsed >= mem0.alarmThreshold - nFull ){
19724      mem0.nearlyFull = 1;
19725      sqlite3MallocAlarm(nFull);
19726    }else{
19727      mem0.nearlyFull = 0;
19728    }
19729  }
19730  p = sqlite3GlobalConfig.m.xMalloc(nFull);
19731#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
19732  if( p==0 && mem0.alarmCallback ){
19733    sqlite3MallocAlarm(nFull);
19734    p = sqlite3GlobalConfig.m.xMalloc(nFull);
19735  }
19736#endif
19737  if( p ){
19738    nFull = sqlite3MallocSize(p);
19739    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
19740    sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
19741  }
19742  *pp = p;
19743  return nFull;
19744}
19745
19746/*
19747** Allocate memory.  This routine is like sqlite3_malloc() except that it
19748** assumes the memory subsystem has already been initialized.
19749*/
19750SQLITE_PRIVATE void *sqlite3Malloc(int n){
19751  void *p;
19752  if( n<=0               /* IMP: R-65312-04917 */
19753   || n>=0x7fffff00
19754  ){
19755    /* A memory allocation of a number of bytes which is near the maximum
19756    ** signed integer value might cause an integer overflow inside of the
19757    ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
19758    ** 255 bytes of overhead.  SQLite itself will never use anything near
19759    ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
19760    p = 0;
19761  }else if( sqlite3GlobalConfig.bMemstat ){
19762    sqlite3_mutex_enter(mem0.mutex);
19763    mallocWithAlarm(n, &p);
19764    sqlite3_mutex_leave(mem0.mutex);
19765  }else{
19766    p = sqlite3GlobalConfig.m.xMalloc(n);
19767  }
19768  assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
19769  return p;
19770}
19771
19772/*
19773** This version of the memory allocation is for use by the application.
19774** First make sure the memory subsystem is initialized, then do the
19775** allocation.
19776*/
19777SQLITE_API void *sqlite3_malloc(int n){
19778#ifndef SQLITE_OMIT_AUTOINIT
19779  if( sqlite3_initialize() ) return 0;
19780#endif
19781  return sqlite3Malloc(n);
19782}
19783
19784/*
19785** Each thread may only have a single outstanding allocation from
19786** xScratchMalloc().  We verify this constraint in the single-threaded
19787** case by setting scratchAllocOut to 1 when an allocation
19788** is outstanding clearing it when the allocation is freed.
19789*/
19790#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
19791static int scratchAllocOut = 0;
19792#endif
19793
19794
19795/*
19796** Allocate memory that is to be used and released right away.
19797** This routine is similar to alloca() in that it is not intended
19798** for situations where the memory might be held long-term.  This
19799** routine is intended to get memory to old large transient data
19800** structures that would not normally fit on the stack of an
19801** embedded processor.
19802*/
19803SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
19804  void *p;
19805  assert( n>0 );
19806
19807  sqlite3_mutex_enter(mem0.mutex);
19808  if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
19809    p = mem0.pScratchFree;
19810    mem0.pScratchFree = mem0.pScratchFree->pNext;
19811    mem0.nScratchFree--;
19812    sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
19813    sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
19814    sqlite3_mutex_leave(mem0.mutex);
19815  }else{
19816    if( sqlite3GlobalConfig.bMemstat ){
19817      sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
19818      n = mallocWithAlarm(n, &p);
19819      if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
19820      sqlite3_mutex_leave(mem0.mutex);
19821    }else{
19822      sqlite3_mutex_leave(mem0.mutex);
19823      p = sqlite3GlobalConfig.m.xMalloc(n);
19824    }
19825    sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
19826  }
19827  assert( sqlite3_mutex_notheld(mem0.mutex) );
19828
19829
19830#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
19831  /* Verify that no more than two scratch allocations per thread
19832  ** are outstanding at one time.  (This is only checked in the
19833  ** single-threaded case since checking in the multi-threaded case
19834  ** would be much more complicated.) */
19835  assert( scratchAllocOut<=1 );
19836  if( p ) scratchAllocOut++;
19837#endif
19838
19839  return p;
19840}
19841SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
19842  if( p ){
19843
19844#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
19845    /* Verify that no more than two scratch allocation per thread
19846    ** is outstanding at one time.  (This is only checked in the
19847    ** single-threaded case since checking in the multi-threaded case
19848    ** would be much more complicated.) */
19849    assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
19850    scratchAllocOut--;
19851#endif
19852
19853    if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
19854      /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
19855      ScratchFreeslot *pSlot;
19856      pSlot = (ScratchFreeslot*)p;
19857      sqlite3_mutex_enter(mem0.mutex);
19858      pSlot->pNext = mem0.pScratchFree;
19859      mem0.pScratchFree = pSlot;
19860      mem0.nScratchFree++;
19861      assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
19862      sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
19863      sqlite3_mutex_leave(mem0.mutex);
19864    }else{
19865      /* Release memory back to the heap */
19866      assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
19867      assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
19868      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19869      if( sqlite3GlobalConfig.bMemstat ){
19870        int iSize = sqlite3MallocSize(p);
19871        sqlite3_mutex_enter(mem0.mutex);
19872        sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
19873        sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
19874        sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
19875        sqlite3GlobalConfig.m.xFree(p);
19876        sqlite3_mutex_leave(mem0.mutex);
19877      }else{
19878        sqlite3GlobalConfig.m.xFree(p);
19879      }
19880    }
19881  }
19882}
19883
19884/*
19885** TRUE if p is a lookaside memory allocation from db
19886*/
19887#ifndef SQLITE_OMIT_LOOKASIDE
19888static int isLookaside(sqlite3 *db, void *p){
19889  return p>=db->lookaside.pStart && p<db->lookaside.pEnd;
19890}
19891#else
19892#define isLookaside(A,B) 0
19893#endif
19894
19895/*
19896** Return the size of a memory allocation previously obtained from
19897** sqlite3Malloc() or sqlite3_malloc().
19898*/
19899SQLITE_PRIVATE int sqlite3MallocSize(void *p){
19900  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
19901  assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
19902  return sqlite3GlobalConfig.m.xSize(p);
19903}
19904SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
19905  assert( db!=0 );
19906  assert( sqlite3_mutex_held(db->mutex) );
19907  if( isLookaside(db, p) ){
19908    return db->lookaside.sz;
19909  }else{
19910    assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19911    assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19912    assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
19913    return sqlite3GlobalConfig.m.xSize(p);
19914  }
19915}
19916
19917/*
19918** Free memory previously obtained from sqlite3Malloc().
19919*/
19920SQLITE_API void sqlite3_free(void *p){
19921  if( p==0 ) return;  /* IMP: R-49053-54554 */
19922  assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
19923  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
19924  if( sqlite3GlobalConfig.bMemstat ){
19925    sqlite3_mutex_enter(mem0.mutex);
19926    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
19927    sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
19928    sqlite3GlobalConfig.m.xFree(p);
19929    sqlite3_mutex_leave(mem0.mutex);
19930  }else{
19931    sqlite3GlobalConfig.m.xFree(p);
19932  }
19933}
19934
19935/*
19936** Free memory that might be associated with a particular database
19937** connection.
19938*/
19939SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
19940  assert( db==0 || sqlite3_mutex_held(db->mutex) );
19941  if( p==0 ) return;
19942  if( db ){
19943    if( db->pnBytesFreed ){
19944      *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
19945      return;
19946    }
19947    if( isLookaside(db, p) ){
19948      LookasideSlot *pBuf = (LookasideSlot*)p;
19949#if SQLITE_DEBUG
19950      /* Trash all content in the buffer being freed */
19951      memset(p, 0xaa, db->lookaside.sz);
19952#endif
19953      pBuf->pNext = db->lookaside.pFree;
19954      db->lookaside.pFree = pBuf;
19955      db->lookaside.nOut--;
19956      return;
19957    }
19958  }
19959  assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19960  assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19961  assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
19962  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19963  sqlite3_free(p);
19964}
19965
19966/*
19967** Change the size of an existing memory allocation
19968*/
19969SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
19970  int nOld, nNew, nDiff;
19971  void *pNew;
19972  if( pOld==0 ){
19973    return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
19974  }
19975  if( nBytes<=0 ){
19976    sqlite3_free(pOld); /* IMP: R-31593-10574 */
19977    return 0;
19978  }
19979  if( nBytes>=0x7fffff00 ){
19980    /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
19981    return 0;
19982  }
19983  nOld = sqlite3MallocSize(pOld);
19984  /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
19985  ** argument to xRealloc is always a value returned by a prior call to
19986  ** xRoundup. */
19987  nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
19988  if( nOld==nNew ){
19989    pNew = pOld;
19990  }else if( sqlite3GlobalConfig.bMemstat ){
19991    sqlite3_mutex_enter(mem0.mutex);
19992    sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
19993    nDiff = nNew - nOld;
19994    if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
19995          mem0.alarmThreshold-nDiff ){
19996      sqlite3MallocAlarm(nDiff);
19997    }
19998    assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
19999    assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
20000    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
20001    if( pNew==0 && mem0.alarmCallback ){
20002      sqlite3MallocAlarm(nBytes);
20003      pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
20004    }
20005    if( pNew ){
20006      nNew = sqlite3MallocSize(pNew);
20007      sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
20008    }
20009    sqlite3_mutex_leave(mem0.mutex);
20010  }else{
20011    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
20012  }
20013  assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
20014  return pNew;
20015}
20016
20017/*
20018** The public interface to sqlite3Realloc.  Make sure that the memory
20019** subsystem is initialized prior to invoking sqliteRealloc.
20020*/
20021SQLITE_API void *sqlite3_realloc(void *pOld, int n){
20022#ifndef SQLITE_OMIT_AUTOINIT
20023  if( sqlite3_initialize() ) return 0;
20024#endif
20025  return sqlite3Realloc(pOld, n);
20026}
20027
20028
20029/*
20030** Allocate and zero memory.
20031*/
20032SQLITE_PRIVATE void *sqlite3MallocZero(int n){
20033  void *p = sqlite3Malloc(n);
20034  if( p ){
20035    memset(p, 0, n);
20036  }
20037  return p;
20038}
20039
20040/*
20041** Allocate and zero memory.  If the allocation fails, make
20042** the mallocFailed flag in the connection pointer.
20043*/
20044SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
20045  void *p = sqlite3DbMallocRaw(db, n);
20046  if( p ){
20047    memset(p, 0, n);
20048  }
20049  return p;
20050}
20051
20052/*
20053** Allocate and zero memory.  If the allocation fails, make
20054** the mallocFailed flag in the connection pointer.
20055**
20056** If db!=0 and db->mallocFailed is true (indicating a prior malloc
20057** failure on the same database connection) then always return 0.
20058** Hence for a particular database connection, once malloc starts
20059** failing, it fails consistently until mallocFailed is reset.
20060** This is an important assumption.  There are many places in the
20061** code that do things like this:
20062**
20063**         int *a = (int*)sqlite3DbMallocRaw(db, 100);
20064**         int *b = (int*)sqlite3DbMallocRaw(db, 200);
20065**         if( b ) a[10] = 9;
20066**
20067** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
20068** that all prior mallocs (ex: "a") worked too.
20069*/
20070SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
20071  void *p;
20072  assert( db==0 || sqlite3_mutex_held(db->mutex) );
20073  assert( db==0 || db->pnBytesFreed==0 );
20074#ifndef SQLITE_OMIT_LOOKASIDE
20075  if( db ){
20076    LookasideSlot *pBuf;
20077    if( db->mallocFailed ){
20078      return 0;
20079    }
20080    if( db->lookaside.bEnabled ){
20081      if( n>db->lookaside.sz ){
20082        db->lookaside.anStat[1]++;
20083      }else if( (pBuf = db->lookaside.pFree)==0 ){
20084        db->lookaside.anStat[2]++;
20085      }else{
20086        db->lookaside.pFree = pBuf->pNext;
20087        db->lookaside.nOut++;
20088        db->lookaside.anStat[0]++;
20089        if( db->lookaside.nOut>db->lookaside.mxOut ){
20090          db->lookaside.mxOut = db->lookaside.nOut;
20091        }
20092        return (void*)pBuf;
20093      }
20094    }
20095  }
20096#else
20097  if( db && db->mallocFailed ){
20098    return 0;
20099  }
20100#endif
20101  p = sqlite3Malloc(n);
20102  if( !p && db ){
20103    db->mallocFailed = 1;
20104  }
20105  sqlite3MemdebugSetType(p, MEMTYPE_DB |
20106         ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
20107  return p;
20108}
20109
20110/*
20111** Resize the block of memory pointed to by p to n bytes. If the
20112** resize fails, set the mallocFailed flag in the connection object.
20113*/
20114SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
20115  void *pNew = 0;
20116  assert( db!=0 );
20117  assert( sqlite3_mutex_held(db->mutex) );
20118  if( db->mallocFailed==0 ){
20119    if( p==0 ){
20120      return sqlite3DbMallocRaw(db, n);
20121    }
20122    if( isLookaside(db, p) ){
20123      if( n<=db->lookaside.sz ){
20124        return p;
20125      }
20126      pNew = sqlite3DbMallocRaw(db, n);
20127      if( pNew ){
20128        memcpy(pNew, p, db->lookaside.sz);
20129        sqlite3DbFree(db, p);
20130      }
20131    }else{
20132      assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
20133      assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
20134      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
20135      pNew = sqlite3_realloc(p, n);
20136      if( !pNew ){
20137        sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
20138        db->mallocFailed = 1;
20139      }
20140      sqlite3MemdebugSetType(pNew, MEMTYPE_DB |
20141            (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
20142    }
20143  }
20144  return pNew;
20145}
20146
20147/*
20148** Attempt to reallocate p.  If the reallocation fails, then free p
20149** and set the mallocFailed flag in the database connection.
20150*/
20151SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
20152  void *pNew;
20153  pNew = sqlite3DbRealloc(db, p, n);
20154  if( !pNew ){
20155    sqlite3DbFree(db, p);
20156  }
20157  return pNew;
20158}
20159
20160/*
20161** Make a copy of a string in memory obtained from sqliteMalloc(). These
20162** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
20163** is because when memory debugging is turned on, these two functions are
20164** called via macros that record the current file and line number in the
20165** ThreadData structure.
20166*/
20167SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
20168  char *zNew;
20169  size_t n;
20170  if( z==0 ){
20171    return 0;
20172  }
20173  n = sqlite3Strlen30(z) + 1;
20174  assert( (n&0x7fffffff)==n );
20175  zNew = sqlite3DbMallocRaw(db, (int)n);
20176  if( zNew ){
20177    memcpy(zNew, z, n);
20178  }
20179  return zNew;
20180}
20181SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
20182  char *zNew;
20183  if( z==0 ){
20184    return 0;
20185  }
20186  assert( (n&0x7fffffff)==n );
20187  zNew = sqlite3DbMallocRaw(db, n+1);
20188  if( zNew ){
20189    memcpy(zNew, z, n);
20190    zNew[n] = 0;
20191  }
20192  return zNew;
20193}
20194
20195/*
20196** Create a string from the zFromat argument and the va_list that follows.
20197** Store the string in memory obtained from sqliteMalloc() and make *pz
20198** point to that string.
20199*/
20200SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
20201  va_list ap;
20202  char *z;
20203
20204  va_start(ap, zFormat);
20205  z = sqlite3VMPrintf(db, zFormat, ap);
20206  va_end(ap);
20207  sqlite3DbFree(db, *pz);
20208  *pz = z;
20209}
20210
20211
20212/*
20213** This function must be called before exiting any API function (i.e.
20214** returning control to the user) that has called sqlite3_malloc or
20215** sqlite3_realloc.
20216**
20217** The returned value is normally a copy of the second argument to this
20218** function. However, if a malloc() failure has occurred since the previous
20219** invocation SQLITE_NOMEM is returned instead.
20220**
20221** If the first argument, db, is not NULL and a malloc() error has occurred,
20222** then the connection error-code (the value returned by sqlite3_errcode())
20223** is set to SQLITE_NOMEM.
20224*/
20225SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
20226  /* If the db handle is not NULL, then we must hold the connection handle
20227  ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
20228  ** is unsafe, as is the call to sqlite3Error().
20229  */
20230  assert( !db || sqlite3_mutex_held(db->mutex) );
20231  if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
20232    sqlite3Error(db, SQLITE_NOMEM, 0);
20233    db->mallocFailed = 0;
20234    rc = SQLITE_NOMEM;
20235  }
20236  return rc & (db ? db->errMask : 0xff);
20237}
20238
20239/************** End of malloc.c **********************************************/
20240/************** Begin file printf.c ******************************************/
20241/*
20242** The "printf" code that follows dates from the 1980's.  It is in
20243** the public domain.  The original comments are included here for
20244** completeness.  They are very out-of-date but might be useful as
20245** an historical reference.  Most of the "enhancements" have been backed
20246** out so that the functionality is now the same as standard printf().
20247**
20248**************************************************************************
20249**
20250** This file contains code for a set of "printf"-like routines.  These
20251** routines format strings much like the printf() from the standard C
20252** library, though the implementation here has enhancements to support
20253** SQLlite.
20254*/
20255
20256/*
20257** Conversion types fall into various categories as defined by the
20258** following enumeration.
20259*/
20260#define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
20261#define etFLOAT       2 /* Floating point.  %f */
20262#define etEXP         3 /* Exponentional notation. %e and %E */
20263#define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
20264#define etSIZE        5 /* Return number of characters processed so far. %n */
20265#define etSTRING      6 /* Strings. %s */
20266#define etDYNSTRING   7 /* Dynamically allocated strings. %z */
20267#define etPERCENT     8 /* Percent symbol. %% */
20268#define etCHARX       9 /* Characters. %c */
20269/* The rest are extensions, not normally found in printf() */
20270#define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
20271#define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
20272                          NULL pointers replaced by SQL NULL.  %Q */
20273#define etTOKEN      12 /* a pointer to a Token structure */
20274#define etSRCLIST    13 /* a pointer to a SrcList */
20275#define etPOINTER    14 /* The %p conversion */
20276#define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
20277#define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
20278
20279#define etINVALID     0 /* Any unrecognized conversion type */
20280
20281
20282/*
20283** An "etByte" is an 8-bit unsigned value.
20284*/
20285typedef unsigned char etByte;
20286
20287/*
20288** Each builtin conversion character (ex: the 'd' in "%d") is described
20289** by an instance of the following structure
20290*/
20291typedef struct et_info {   /* Information about each format field */
20292  char fmttype;            /* The format field code letter */
20293  etByte base;             /* The base for radix conversion */
20294  etByte flags;            /* One or more of FLAG_ constants below */
20295  etByte type;             /* Conversion paradigm */
20296  etByte charset;          /* Offset into aDigits[] of the digits string */
20297  etByte prefix;           /* Offset into aPrefix[] of the prefix string */
20298} et_info;
20299
20300/*
20301** Allowed values for et_info.flags
20302*/
20303#define FLAG_SIGNED  1     /* True if the value to convert is signed */
20304#define FLAG_INTERN  2     /* True if for internal use only */
20305#define FLAG_STRING  4     /* Allow infinity precision */
20306
20307
20308/*
20309** The following table is searched linearly, so it is good to put the
20310** most frequently used conversion types first.
20311*/
20312static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
20313static const char aPrefix[] = "-x0\000X0";
20314static const et_info fmtinfo[] = {
20315  {  'd', 10, 1, etRADIX,      0,  0 },
20316  {  's',  0, 4, etSTRING,     0,  0 },
20317  {  'g',  0, 1, etGENERIC,    30, 0 },
20318  {  'z',  0, 4, etDYNSTRING,  0,  0 },
20319  {  'q',  0, 4, etSQLESCAPE,  0,  0 },
20320  {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
20321  {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
20322  {  'c',  0, 0, etCHARX,      0,  0 },
20323  {  'o',  8, 0, etRADIX,      0,  2 },
20324  {  'u', 10, 0, etRADIX,      0,  0 },
20325  {  'x', 16, 0, etRADIX,      16, 1 },
20326  {  'X', 16, 0, etRADIX,      0,  4 },
20327#ifndef SQLITE_OMIT_FLOATING_POINT
20328  {  'f',  0, 1, etFLOAT,      0,  0 },
20329  {  'e',  0, 1, etEXP,        30, 0 },
20330  {  'E',  0, 1, etEXP,        14, 0 },
20331  {  'G',  0, 1, etGENERIC,    14, 0 },
20332#endif
20333  {  'i', 10, 1, etRADIX,      0,  0 },
20334  {  'n',  0, 0, etSIZE,       0,  0 },
20335  {  '%',  0, 0, etPERCENT,    0,  0 },
20336  {  'p', 16, 0, etPOINTER,    0,  1 },
20337
20338/* All the rest have the FLAG_INTERN bit set and are thus for internal
20339** use only */
20340  {  'T',  0, 2, etTOKEN,      0,  0 },
20341  {  'S',  0, 2, etSRCLIST,    0,  0 },
20342  {  'r', 10, 3, etORDINAL,    0,  0 },
20343};
20344
20345/*
20346** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
20347** conversions will work.
20348*/
20349#ifndef SQLITE_OMIT_FLOATING_POINT
20350/*
20351** "*val" is a double such that 0.1 <= *val < 10.0
20352** Return the ascii code for the leading digit of *val, then
20353** multiply "*val" by 10.0 to renormalize.
20354**
20355** Example:
20356**     input:     *val = 3.14159
20357**     output:    *val = 1.4159    function return = '3'
20358**
20359** The counter *cnt is incremented each time.  After counter exceeds
20360** 16 (the number of significant digits in a 64-bit float) '0' is
20361** always returned.
20362*/
20363static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
20364  int digit;
20365  LONGDOUBLE_TYPE d;
20366  if( (*cnt)<=0 ) return '0';
20367  (*cnt)--;
20368  digit = (int)*val;
20369  d = digit;
20370  digit += '0';
20371  *val = (*val - d)*10.0;
20372  return (char)digit;
20373}
20374#endif /* SQLITE_OMIT_FLOATING_POINT */
20375
20376/*
20377** Set the StrAccum object to an error mode.
20378*/
20379static void setStrAccumError(StrAccum *p, u8 eError){
20380  p->accError = eError;
20381  p->nAlloc = 0;
20382}
20383
20384/*
20385** Extra argument values from a PrintfArguments object
20386*/
20387static sqlite3_int64 getIntArg(PrintfArguments *p){
20388  if( p->nArg<=p->nUsed ) return 0;
20389  return sqlite3_value_int64(p->apArg[p->nUsed++]);
20390}
20391static double getDoubleArg(PrintfArguments *p){
20392  if( p->nArg<=p->nUsed ) return 0.0;
20393  return sqlite3_value_double(p->apArg[p->nUsed++]);
20394}
20395static char *getTextArg(PrintfArguments *p){
20396  if( p->nArg<=p->nUsed ) return 0;
20397  return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
20398}
20399
20400
20401/*
20402** On machines with a small stack size, you can redefine the
20403** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
20404*/
20405#ifndef SQLITE_PRINT_BUF_SIZE
20406# define SQLITE_PRINT_BUF_SIZE 70
20407#endif
20408#define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
20409
20410/*
20411** Render a string given by "fmt" into the StrAccum object.
20412*/
20413SQLITE_PRIVATE void sqlite3VXPrintf(
20414  StrAccum *pAccum,          /* Accumulate results here */
20415  u32 bFlags,                /* SQLITE_PRINTF_* flags */
20416  const char *fmt,           /* Format string */
20417  va_list ap                 /* arguments */
20418){
20419  int c;                     /* Next character in the format string */
20420  char *bufpt;               /* Pointer to the conversion buffer */
20421  int precision;             /* Precision of the current field */
20422  int length;                /* Length of the field */
20423  int idx;                   /* A general purpose loop counter */
20424  int width;                 /* Width of the current field */
20425  etByte flag_leftjustify;   /* True if "-" flag is present */
20426  etByte flag_plussign;      /* True if "+" flag is present */
20427  etByte flag_blanksign;     /* True if " " flag is present */
20428  etByte flag_alternateform; /* True if "#" flag is present */
20429  etByte flag_altform2;      /* True if "!" flag is present */
20430  etByte flag_zeropad;       /* True if field width constant starts with zero */
20431  etByte flag_long;          /* True if "l" flag is present */
20432  etByte flag_longlong;      /* True if the "ll" flag is present */
20433  etByte done;               /* Loop termination flag */
20434  etByte xtype = 0;          /* Conversion paradigm */
20435  u8 bArgList;               /* True for SQLITE_PRINTF_SQLFUNC */
20436  u8 useIntern;              /* Ok to use internal conversions (ex: %T) */
20437  char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
20438  sqlite_uint64 longvalue;   /* Value for integer types */
20439  LONGDOUBLE_TYPE realvalue; /* Value for real types */
20440  const et_info *infop;      /* Pointer to the appropriate info structure */
20441  char *zOut;                /* Rendering buffer */
20442  int nOut;                  /* Size of the rendering buffer */
20443  char *zExtra;              /* Malloced memory used by some conversion */
20444#ifndef SQLITE_OMIT_FLOATING_POINT
20445  int  exp, e2;              /* exponent of real numbers */
20446  int nsd;                   /* Number of significant digits returned */
20447  double rounder;            /* Used for rounding floating point values */
20448  etByte flag_dp;            /* True if decimal point should be shown */
20449  etByte flag_rtz;           /* True if trailing zeros should be removed */
20450#endif
20451  PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
20452  char buf[etBUFSIZE];       /* Conversion buffer */
20453
20454  bufpt = 0;
20455  if( bFlags ){
20456    if( (bArgList = (bFlags & SQLITE_PRINTF_SQLFUNC))!=0 ){
20457      pArgList = va_arg(ap, PrintfArguments*);
20458    }
20459    useIntern = bFlags & SQLITE_PRINTF_INTERNAL;
20460  }else{
20461    bArgList = useIntern = 0;
20462  }
20463  for(; (c=(*fmt))!=0; ++fmt){
20464    if( c!='%' ){
20465      bufpt = (char *)fmt;
20466      while( (c=(*++fmt))!='%' && c!=0 ){};
20467      sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
20468      if( c==0 ) break;
20469    }
20470    if( (c=(*++fmt))==0 ){
20471      sqlite3StrAccumAppend(pAccum, "%", 1);
20472      break;
20473    }
20474    /* Find out what flags are present */
20475    flag_leftjustify = flag_plussign = flag_blanksign =
20476     flag_alternateform = flag_altform2 = flag_zeropad = 0;
20477    done = 0;
20478    do{
20479      switch( c ){
20480        case '-':   flag_leftjustify = 1;     break;
20481        case '+':   flag_plussign = 1;        break;
20482        case ' ':   flag_blanksign = 1;       break;
20483        case '#':   flag_alternateform = 1;   break;
20484        case '!':   flag_altform2 = 1;        break;
20485        case '0':   flag_zeropad = 1;         break;
20486        default:    done = 1;                 break;
20487      }
20488    }while( !done && (c=(*++fmt))!=0 );
20489    /* Get the field width */
20490    width = 0;
20491    if( c=='*' ){
20492      if( bArgList ){
20493        width = (int)getIntArg(pArgList);
20494      }else{
20495        width = va_arg(ap,int);
20496      }
20497      if( width<0 ){
20498        flag_leftjustify = 1;
20499        width = -width;
20500      }
20501      c = *++fmt;
20502    }else{
20503      while( c>='0' && c<='9' ){
20504        width = width*10 + c - '0';
20505        c = *++fmt;
20506      }
20507    }
20508    /* Get the precision */
20509    if( c=='.' ){
20510      precision = 0;
20511      c = *++fmt;
20512      if( c=='*' ){
20513        if( bArgList ){
20514          precision = (int)getIntArg(pArgList);
20515        }else{
20516          precision = va_arg(ap,int);
20517        }
20518        if( precision<0 ) precision = -precision;
20519        c = *++fmt;
20520      }else{
20521        while( c>='0' && c<='9' ){
20522          precision = precision*10 + c - '0';
20523          c = *++fmt;
20524        }
20525      }
20526    }else{
20527      precision = -1;
20528    }
20529    /* Get the conversion type modifier */
20530    if( c=='l' ){
20531      flag_long = 1;
20532      c = *++fmt;
20533      if( c=='l' ){
20534        flag_longlong = 1;
20535        c = *++fmt;
20536      }else{
20537        flag_longlong = 0;
20538      }
20539    }else{
20540      flag_long = flag_longlong = 0;
20541    }
20542    /* Fetch the info entry for the field */
20543    infop = &fmtinfo[0];
20544    xtype = etINVALID;
20545    for(idx=0; idx<ArraySize(fmtinfo); idx++){
20546      if( c==fmtinfo[idx].fmttype ){
20547        infop = &fmtinfo[idx];
20548        if( useIntern || (infop->flags & FLAG_INTERN)==0 ){
20549          xtype = infop->type;
20550        }else{
20551          return;
20552        }
20553        break;
20554      }
20555    }
20556    zExtra = 0;
20557
20558    /*
20559    ** At this point, variables are initialized as follows:
20560    **
20561    **   flag_alternateform          TRUE if a '#' is present.
20562    **   flag_altform2               TRUE if a '!' is present.
20563    **   flag_plussign               TRUE if a '+' is present.
20564    **   flag_leftjustify            TRUE if a '-' is present or if the
20565    **                               field width was negative.
20566    **   flag_zeropad                TRUE if the width began with 0.
20567    **   flag_long                   TRUE if the letter 'l' (ell) prefixed
20568    **                               the conversion character.
20569    **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
20570    **                               the conversion character.
20571    **   flag_blanksign              TRUE if a ' ' is present.
20572    **   width                       The specified field width.  This is
20573    **                               always non-negative.  Zero is the default.
20574    **   precision                   The specified precision.  The default
20575    **                               is -1.
20576    **   xtype                       The class of the conversion.
20577    **   infop                       Pointer to the appropriate info struct.
20578    */
20579    switch( xtype ){
20580      case etPOINTER:
20581        flag_longlong = sizeof(char*)==sizeof(i64);
20582        flag_long = sizeof(char*)==sizeof(long int);
20583        /* Fall through into the next case */
20584      case etORDINAL:
20585      case etRADIX:
20586        if( infop->flags & FLAG_SIGNED ){
20587          i64 v;
20588          if( bArgList ){
20589            v = getIntArg(pArgList);
20590          }else if( flag_longlong ){
20591            v = va_arg(ap,i64);
20592          }else if( flag_long ){
20593            v = va_arg(ap,long int);
20594          }else{
20595            v = va_arg(ap,int);
20596          }
20597          if( v<0 ){
20598            if( v==SMALLEST_INT64 ){
20599              longvalue = ((u64)1)<<63;
20600            }else{
20601              longvalue = -v;
20602            }
20603            prefix = '-';
20604          }else{
20605            longvalue = v;
20606            if( flag_plussign )        prefix = '+';
20607            else if( flag_blanksign )  prefix = ' ';
20608            else                       prefix = 0;
20609          }
20610        }else{
20611          if( bArgList ){
20612            longvalue = (u64)getIntArg(pArgList);
20613          }else if( flag_longlong ){
20614            longvalue = va_arg(ap,u64);
20615          }else if( flag_long ){
20616            longvalue = va_arg(ap,unsigned long int);
20617          }else{
20618            longvalue = va_arg(ap,unsigned int);
20619          }
20620          prefix = 0;
20621        }
20622        if( longvalue==0 ) flag_alternateform = 0;
20623        if( flag_zeropad && precision<width-(prefix!=0) ){
20624          precision = width-(prefix!=0);
20625        }
20626        if( precision<etBUFSIZE-10 ){
20627          nOut = etBUFSIZE;
20628          zOut = buf;
20629        }else{
20630          nOut = precision + 10;
20631          zOut = zExtra = sqlite3Malloc( nOut );
20632          if( zOut==0 ){
20633            setStrAccumError(pAccum, STRACCUM_NOMEM);
20634            return;
20635          }
20636        }
20637        bufpt = &zOut[nOut-1];
20638        if( xtype==etORDINAL ){
20639          static const char zOrd[] = "thstndrd";
20640          int x = (int)(longvalue % 10);
20641          if( x>=4 || (longvalue/10)%10==1 ){
20642            x = 0;
20643          }
20644          *(--bufpt) = zOrd[x*2+1];
20645          *(--bufpt) = zOrd[x*2];
20646        }
20647        {
20648          const char *cset = &aDigits[infop->charset];
20649          u8 base = infop->base;
20650          do{                                           /* Convert to ascii */
20651            *(--bufpt) = cset[longvalue%base];
20652            longvalue = longvalue/base;
20653          }while( longvalue>0 );
20654        }
20655        length = (int)(&zOut[nOut-1]-bufpt);
20656        for(idx=precision-length; idx>0; idx--){
20657          *(--bufpt) = '0';                             /* Zero pad */
20658        }
20659        if( prefix ) *(--bufpt) = prefix;               /* Add sign */
20660        if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
20661          const char *pre;
20662          char x;
20663          pre = &aPrefix[infop->prefix];
20664          for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
20665        }
20666        length = (int)(&zOut[nOut-1]-bufpt);
20667        break;
20668      case etFLOAT:
20669      case etEXP:
20670      case etGENERIC:
20671        if( bArgList ){
20672          realvalue = getDoubleArg(pArgList);
20673        }else{
20674          realvalue = va_arg(ap,double);
20675        }
20676#ifdef SQLITE_OMIT_FLOATING_POINT
20677        length = 0;
20678#else
20679        if( precision<0 ) precision = 6;         /* Set default precision */
20680        if( realvalue<0.0 ){
20681          realvalue = -realvalue;
20682          prefix = '-';
20683        }else{
20684          if( flag_plussign )          prefix = '+';
20685          else if( flag_blanksign )    prefix = ' ';
20686          else                         prefix = 0;
20687        }
20688        if( xtype==etGENERIC && precision>0 ) precision--;
20689        for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
20690        if( xtype==etFLOAT ) realvalue += rounder;
20691        /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
20692        exp = 0;
20693        if( sqlite3IsNaN((double)realvalue) ){
20694          bufpt = "NaN";
20695          length = 3;
20696          break;
20697        }
20698        if( realvalue>0.0 ){
20699          LONGDOUBLE_TYPE scale = 1.0;
20700          while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
20701          while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
20702          while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
20703          while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
20704          realvalue /= scale;
20705          while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
20706          while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
20707          if( exp>350 ){
20708            if( prefix=='-' ){
20709              bufpt = "-Inf";
20710            }else if( prefix=='+' ){
20711              bufpt = "+Inf";
20712            }else{
20713              bufpt = "Inf";
20714            }
20715            length = sqlite3Strlen30(bufpt);
20716            break;
20717          }
20718        }
20719        bufpt = buf;
20720        /*
20721        ** If the field type is etGENERIC, then convert to either etEXP
20722        ** or etFLOAT, as appropriate.
20723        */
20724        if( xtype!=etFLOAT ){
20725          realvalue += rounder;
20726          if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
20727        }
20728        if( xtype==etGENERIC ){
20729          flag_rtz = !flag_alternateform;
20730          if( exp<-4 || exp>precision ){
20731            xtype = etEXP;
20732          }else{
20733            precision = precision - exp;
20734            xtype = etFLOAT;
20735          }
20736        }else{
20737          flag_rtz = flag_altform2;
20738        }
20739        if( xtype==etEXP ){
20740          e2 = 0;
20741        }else{
20742          e2 = exp;
20743        }
20744        if( MAX(e2,0)+precision+width > etBUFSIZE - 15 ){
20745          bufpt = zExtra = sqlite3Malloc( MAX(e2,0)+precision+width+15 );
20746          if( bufpt==0 ){
20747            setStrAccumError(pAccum, STRACCUM_NOMEM);
20748            return;
20749          }
20750        }
20751        zOut = bufpt;
20752        nsd = 16 + flag_altform2*10;
20753        flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
20754        /* The sign in front of the number */
20755        if( prefix ){
20756          *(bufpt++) = prefix;
20757        }
20758        /* Digits prior to the decimal point */
20759        if( e2<0 ){
20760          *(bufpt++) = '0';
20761        }else{
20762          for(; e2>=0; e2--){
20763            *(bufpt++) = et_getdigit(&realvalue,&nsd);
20764          }
20765        }
20766        /* The decimal point */
20767        if( flag_dp ){
20768          *(bufpt++) = '.';
20769        }
20770        /* "0" digits after the decimal point but before the first
20771        ** significant digit of the number */
20772        for(e2++; e2<0; precision--, e2++){
20773          assert( precision>0 );
20774          *(bufpt++) = '0';
20775        }
20776        /* Significant digits after the decimal point */
20777        while( (precision--)>0 ){
20778          *(bufpt++) = et_getdigit(&realvalue,&nsd);
20779        }
20780        /* Remove trailing zeros and the "." if no digits follow the "." */
20781        if( flag_rtz && flag_dp ){
20782          while( bufpt[-1]=='0' ) *(--bufpt) = 0;
20783          assert( bufpt>zOut );
20784          if( bufpt[-1]=='.' ){
20785            if( flag_altform2 ){
20786              *(bufpt++) = '0';
20787            }else{
20788              *(--bufpt) = 0;
20789            }
20790          }
20791        }
20792        /* Add the "eNNN" suffix */
20793        if( xtype==etEXP ){
20794          *(bufpt++) = aDigits[infop->charset];
20795          if( exp<0 ){
20796            *(bufpt++) = '-'; exp = -exp;
20797          }else{
20798            *(bufpt++) = '+';
20799          }
20800          if( exp>=100 ){
20801            *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
20802            exp %= 100;
20803          }
20804          *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
20805          *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
20806        }
20807        *bufpt = 0;
20808
20809        /* The converted number is in buf[] and zero terminated. Output it.
20810        ** Note that the number is in the usual order, not reversed as with
20811        ** integer conversions. */
20812        length = (int)(bufpt-zOut);
20813        bufpt = zOut;
20814
20815        /* Special case:  Add leading zeros if the flag_zeropad flag is
20816        ** set and we are not left justified */
20817        if( flag_zeropad && !flag_leftjustify && length < width){
20818          int i;
20819          int nPad = width - length;
20820          for(i=width; i>=nPad; i--){
20821            bufpt[i] = bufpt[i-nPad];
20822          }
20823          i = prefix!=0;
20824          while( nPad-- ) bufpt[i++] = '0';
20825          length = width;
20826        }
20827#endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
20828        break;
20829      case etSIZE:
20830        if( !bArgList ){
20831          *(va_arg(ap,int*)) = pAccum->nChar;
20832        }
20833        length = width = 0;
20834        break;
20835      case etPERCENT:
20836        buf[0] = '%';
20837        bufpt = buf;
20838        length = 1;
20839        break;
20840      case etCHARX:
20841        if( bArgList ){
20842          bufpt = getTextArg(pArgList);
20843          c = bufpt ? bufpt[0] : 0;
20844        }else{
20845          c = va_arg(ap,int);
20846        }
20847        buf[0] = (char)c;
20848        if( precision>=0 ){
20849          for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
20850          length = precision;
20851        }else{
20852          length =1;
20853        }
20854        bufpt = buf;
20855        break;
20856      case etSTRING:
20857      case etDYNSTRING:
20858        if( bArgList ){
20859          bufpt = getTextArg(pArgList);
20860        }else{
20861          bufpt = va_arg(ap,char*);
20862        }
20863        if( bufpt==0 ){
20864          bufpt = "";
20865        }else if( xtype==etDYNSTRING && !bArgList ){
20866          zExtra = bufpt;
20867        }
20868        if( precision>=0 ){
20869          for(length=0; length<precision && bufpt[length]; length++){}
20870        }else{
20871          length = sqlite3Strlen30(bufpt);
20872        }
20873        break;
20874      case etSQLESCAPE:
20875      case etSQLESCAPE2:
20876      case etSQLESCAPE3: {
20877        int i, j, k, n, isnull;
20878        int needQuote;
20879        char ch;
20880        char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
20881        char *escarg;
20882
20883        if( bArgList ){
20884          escarg = getTextArg(pArgList);
20885        }else{
20886          escarg = va_arg(ap,char*);
20887        }
20888        isnull = escarg==0;
20889        if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
20890        k = precision;
20891        for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
20892          if( ch==q )  n++;
20893        }
20894        needQuote = !isnull && xtype==etSQLESCAPE2;
20895        n += i + 1 + needQuote*2;
20896        if( n>etBUFSIZE ){
20897          bufpt = zExtra = sqlite3Malloc( n );
20898          if( bufpt==0 ){
20899            setStrAccumError(pAccum, STRACCUM_NOMEM);
20900            return;
20901          }
20902        }else{
20903          bufpt = buf;
20904        }
20905        j = 0;
20906        if( needQuote ) bufpt[j++] = q;
20907        k = i;
20908        for(i=0; i<k; i++){
20909          bufpt[j++] = ch = escarg[i];
20910          if( ch==q ) bufpt[j++] = ch;
20911        }
20912        if( needQuote ) bufpt[j++] = q;
20913        bufpt[j] = 0;
20914        length = j;
20915        /* The precision in %q and %Q means how many input characters to
20916        ** consume, not the length of the output...
20917        ** if( precision>=0 && precision<length ) length = precision; */
20918        break;
20919      }
20920      case etTOKEN: {
20921        Token *pToken = va_arg(ap, Token*);
20922        assert( bArgList==0 );
20923        if( pToken && pToken->n ){
20924          sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
20925        }
20926        length = width = 0;
20927        break;
20928      }
20929      case etSRCLIST: {
20930        SrcList *pSrc = va_arg(ap, SrcList*);
20931        int k = va_arg(ap, int);
20932        struct SrcList_item *pItem = &pSrc->a[k];
20933        assert( bArgList==0 );
20934        assert( k>=0 && k<pSrc->nSrc );
20935        if( pItem->zDatabase ){
20936          sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
20937          sqlite3StrAccumAppend(pAccum, ".", 1);
20938        }
20939        sqlite3StrAccumAppendAll(pAccum, pItem->zName);
20940        length = width = 0;
20941        break;
20942      }
20943      default: {
20944        assert( xtype==etINVALID );
20945        return;
20946      }
20947    }/* End switch over the format type */
20948    /*
20949    ** The text of the conversion is pointed to by "bufpt" and is
20950    ** "length" characters long.  The field width is "width".  Do
20951    ** the output.
20952    */
20953    width -= length;
20954    if( width>0 && !flag_leftjustify ) sqlite3AppendSpace(pAccum, width);
20955    sqlite3StrAccumAppend(pAccum, bufpt, length);
20956    if( width>0 && flag_leftjustify ) sqlite3AppendSpace(pAccum, width);
20957
20958    if( zExtra ) sqlite3_free(zExtra);
20959  }/* End for loop over the format string */
20960} /* End of function */
20961
20962/*
20963** Enlarge the memory allocation on a StrAccum object so that it is
20964** able to accept at least N more bytes of text.
20965**
20966** Return the number of bytes of text that StrAccum is able to accept
20967** after the attempted enlargement.  The value returned might be zero.
20968*/
20969static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
20970  char *zNew;
20971  assert( p->nChar+N >= p->nAlloc ); /* Only called if really needed */
20972  if( p->accError ){
20973    testcase(p->accError==STRACCUM_TOOBIG);
20974    testcase(p->accError==STRACCUM_NOMEM);
20975    return 0;
20976  }
20977  if( !p->useMalloc ){
20978    N = p->nAlloc - p->nChar - 1;
20979    setStrAccumError(p, STRACCUM_TOOBIG);
20980    return N;
20981  }else{
20982    char *zOld = (p->zText==p->zBase ? 0 : p->zText);
20983    i64 szNew = p->nChar;
20984    szNew += N + 1;
20985    if( szNew > p->mxAlloc ){
20986      sqlite3StrAccumReset(p);
20987      setStrAccumError(p, STRACCUM_TOOBIG);
20988      return 0;
20989    }else{
20990      p->nAlloc = (int)szNew;
20991    }
20992    if( p->useMalloc==1 ){
20993      zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
20994    }else{
20995      zNew = sqlite3_realloc(zOld, p->nAlloc);
20996    }
20997    if( zNew ){
20998      assert( p->zText!=0 || p->nChar==0 );
20999      if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
21000      p->zText = zNew;
21001    }else{
21002      sqlite3StrAccumReset(p);
21003      setStrAccumError(p, STRACCUM_NOMEM);
21004      return 0;
21005    }
21006  }
21007  return N;
21008}
21009
21010/*
21011** Append N space characters to the given string buffer.
21012*/
21013SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum *p, int N){
21014  if( p->nChar+N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ) return;
21015  while( (N--)>0 ) p->zText[p->nChar++] = ' ';
21016}
21017
21018/*
21019** The StrAccum "p" is not large enough to accept N new bytes of z[].
21020** So enlarge if first, then do the append.
21021**
21022** This is a helper routine to sqlite3StrAccumAppend() that does special-case
21023** work (enlarging the buffer) using tail recursion, so that the
21024** sqlite3StrAccumAppend() routine can use fast calling semantics.
21025*/
21026static void enlargeAndAppend(StrAccum *p, const char *z, int N){
21027  N = sqlite3StrAccumEnlarge(p, N);
21028  if( N>0 ){
21029    memcpy(&p->zText[p->nChar], z, N);
21030    p->nChar += N;
21031  }
21032}
21033
21034/*
21035** Append N bytes of text from z to the StrAccum object.  Increase the
21036** size of the memory allocation for StrAccum if necessary.
21037*/
21038SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
21039  assert( z!=0 );
21040  assert( p->zText!=0 || p->nChar==0 || p->accError );
21041  assert( N>=0 );
21042  assert( p->accError==0 || p->nAlloc==0 );
21043  if( p->nChar+N >= p->nAlloc ){
21044    enlargeAndAppend(p,z,N);
21045    return;
21046  }
21047  assert( p->zText );
21048  memcpy(&p->zText[p->nChar], z, N);
21049  p->nChar += N;
21050}
21051
21052/*
21053** Append the complete text of zero-terminated string z[] to the p string.
21054*/
21055SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
21056  sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
21057}
21058
21059
21060/*
21061** Finish off a string by making sure it is zero-terminated.
21062** Return a pointer to the resulting string.  Return a NULL
21063** pointer if any kind of error was encountered.
21064*/
21065SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
21066  if( p->zText ){
21067    p->zText[p->nChar] = 0;
21068    if( p->useMalloc && p->zText==p->zBase ){
21069      if( p->useMalloc==1 ){
21070        p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
21071      }else{
21072        p->zText = sqlite3_malloc(p->nChar+1);
21073      }
21074      if( p->zText ){
21075        memcpy(p->zText, p->zBase, p->nChar+1);
21076      }else{
21077        setStrAccumError(p, STRACCUM_NOMEM);
21078      }
21079    }
21080  }
21081  return p->zText;
21082}
21083
21084/*
21085** Reset an StrAccum string.  Reclaim all malloced memory.
21086*/
21087SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
21088  if( p->zText!=p->zBase ){
21089    if( p->useMalloc==1 ){
21090      sqlite3DbFree(p->db, p->zText);
21091    }else{
21092      sqlite3_free(p->zText);
21093    }
21094  }
21095  p->zText = 0;
21096}
21097
21098/*
21099** Initialize a string accumulator
21100*/
21101SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
21102  p->zText = p->zBase = zBase;
21103  p->db = 0;
21104  p->nChar = 0;
21105  p->nAlloc = n;
21106  p->mxAlloc = mx;
21107  p->useMalloc = 1;
21108  p->accError = 0;
21109}
21110
21111/*
21112** Print into memory obtained from sqliteMalloc().  Use the internal
21113** %-conversion extensions.
21114*/
21115SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
21116  char *z;
21117  char zBase[SQLITE_PRINT_BUF_SIZE];
21118  StrAccum acc;
21119  assert( db!=0 );
21120  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
21121                      db->aLimit[SQLITE_LIMIT_LENGTH]);
21122  acc.db = db;
21123  sqlite3VXPrintf(&acc, SQLITE_PRINTF_INTERNAL, zFormat, ap);
21124  z = sqlite3StrAccumFinish(&acc);
21125  if( acc.accError==STRACCUM_NOMEM ){
21126    db->mallocFailed = 1;
21127  }
21128  return z;
21129}
21130
21131/*
21132** Print into memory obtained from sqliteMalloc().  Use the internal
21133** %-conversion extensions.
21134*/
21135SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
21136  va_list ap;
21137  char *z;
21138  va_start(ap, zFormat);
21139  z = sqlite3VMPrintf(db, zFormat, ap);
21140  va_end(ap);
21141  return z;
21142}
21143
21144/*
21145** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
21146** the string and before returnning.  This routine is intended to be used
21147** to modify an existing string.  For example:
21148**
21149**       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
21150**
21151*/
21152SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
21153  va_list ap;
21154  char *z;
21155  va_start(ap, zFormat);
21156  z = sqlite3VMPrintf(db, zFormat, ap);
21157  va_end(ap);
21158  sqlite3DbFree(db, zStr);
21159  return z;
21160}
21161
21162/*
21163** Print into memory obtained from sqlite3_malloc().  Omit the internal
21164** %-conversion extensions.
21165*/
21166SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
21167  char *z;
21168  char zBase[SQLITE_PRINT_BUF_SIZE];
21169  StrAccum acc;
21170#ifndef SQLITE_OMIT_AUTOINIT
21171  if( sqlite3_initialize() ) return 0;
21172#endif
21173  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
21174  acc.useMalloc = 2;
21175  sqlite3VXPrintf(&acc, 0, zFormat, ap);
21176  z = sqlite3StrAccumFinish(&acc);
21177  return z;
21178}
21179
21180/*
21181** Print into memory obtained from sqlite3_malloc()().  Omit the internal
21182** %-conversion extensions.
21183*/
21184SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
21185  va_list ap;
21186  char *z;
21187#ifndef SQLITE_OMIT_AUTOINIT
21188  if( sqlite3_initialize() ) return 0;
21189#endif
21190  va_start(ap, zFormat);
21191  z = sqlite3_vmprintf(zFormat, ap);
21192  va_end(ap);
21193  return z;
21194}
21195
21196/*
21197** sqlite3_snprintf() works like snprintf() except that it ignores the
21198** current locale settings.  This is important for SQLite because we
21199** are not able to use a "," as the decimal point in place of "." as
21200** specified by some locales.
21201**
21202** Oops:  The first two arguments of sqlite3_snprintf() are backwards
21203** from the snprintf() standard.  Unfortunately, it is too late to change
21204** this without breaking compatibility, so we just have to live with the
21205** mistake.
21206**
21207** sqlite3_vsnprintf() is the varargs version.
21208*/
21209SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
21210  StrAccum acc;
21211  if( n<=0 ) return zBuf;
21212  sqlite3StrAccumInit(&acc, zBuf, n, 0);
21213  acc.useMalloc = 0;
21214  sqlite3VXPrintf(&acc, 0, zFormat, ap);
21215  return sqlite3StrAccumFinish(&acc);
21216}
21217SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
21218  char *z;
21219  va_list ap;
21220  va_start(ap,zFormat);
21221  z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
21222  va_end(ap);
21223  return z;
21224}
21225
21226/*
21227** This is the routine that actually formats the sqlite3_log() message.
21228** We house it in a separate routine from sqlite3_log() to avoid using
21229** stack space on small-stack systems when logging is disabled.
21230**
21231** sqlite3_log() must render into a static buffer.  It cannot dynamically
21232** allocate memory because it might be called while the memory allocator
21233** mutex is held.
21234*/
21235static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
21236  StrAccum acc;                          /* String accumulator */
21237  char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
21238
21239  sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
21240  acc.useMalloc = 0;
21241  sqlite3VXPrintf(&acc, 0, zFormat, ap);
21242  sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
21243                           sqlite3StrAccumFinish(&acc));
21244}
21245
21246/*
21247** Format and write a message to the log if logging is enabled.
21248*/
21249SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
21250  va_list ap;                             /* Vararg list */
21251  if( sqlite3GlobalConfig.xLog ){
21252    va_start(ap, zFormat);
21253    renderLogMsg(iErrCode, zFormat, ap);
21254    va_end(ap);
21255  }
21256}
21257
21258#if defined(SQLITE_DEBUG)
21259/*
21260** A version of printf() that understands %lld.  Used for debugging.
21261** The printf() built into some versions of windows does not understand %lld
21262** and segfaults if you give it a long long int.
21263*/
21264SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
21265  va_list ap;
21266  StrAccum acc;
21267  char zBuf[500];
21268  sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
21269  acc.useMalloc = 0;
21270  va_start(ap,zFormat);
21271  sqlite3VXPrintf(&acc, 0, zFormat, ap);
21272  va_end(ap);
21273  sqlite3StrAccumFinish(&acc);
21274  fprintf(stdout,"%s", zBuf);
21275  fflush(stdout);
21276}
21277#endif
21278
21279/*
21280** variable-argument wrapper around sqlite3VXPrintf().
21281*/
21282SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, u32 bFlags, const char *zFormat, ...){
21283  va_list ap;
21284  va_start(ap,zFormat);
21285  sqlite3VXPrintf(p, bFlags, zFormat, ap);
21286  va_end(ap);
21287}
21288
21289/************** End of printf.c **********************************************/
21290/************** Begin file random.c ******************************************/
21291/*
21292** 2001 September 15
21293**
21294** The author disclaims copyright to this source code.  In place of
21295** a legal notice, here is a blessing:
21296**
21297**    May you do good and not evil.
21298**    May you find forgiveness for yourself and forgive others.
21299**    May you share freely, never taking more than you give.
21300**
21301*************************************************************************
21302** This file contains code to implement a pseudo-random number
21303** generator (PRNG) for SQLite.
21304**
21305** Random numbers are used by some of the database backends in order
21306** to generate random integer keys for tables or random filenames.
21307*/
21308
21309
21310/* All threads share a single random number generator.
21311** This structure is the current state of the generator.
21312*/
21313static SQLITE_WSD struct sqlite3PrngType {
21314  unsigned char isInit;          /* True if initialized */
21315  unsigned char i, j;            /* State variables */
21316  unsigned char s[256];          /* State variables */
21317} sqlite3Prng;
21318
21319/*
21320** Return N random bytes.
21321*/
21322SQLITE_API void sqlite3_randomness(int N, void *pBuf){
21323  unsigned char t;
21324  unsigned char *zBuf = pBuf;
21325
21326  /* The "wsdPrng" macro will resolve to the pseudo-random number generator
21327  ** state vector.  If writable static data is unsupported on the target,
21328  ** we have to locate the state vector at run-time.  In the more common
21329  ** case where writable static data is supported, wsdPrng can refer directly
21330  ** to the "sqlite3Prng" state vector declared above.
21331  */
21332#ifdef SQLITE_OMIT_WSD
21333  struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
21334# define wsdPrng p[0]
21335#else
21336# define wsdPrng sqlite3Prng
21337#endif
21338
21339#if SQLITE_THREADSAFE
21340  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
21341  sqlite3_mutex_enter(mutex);
21342#endif
21343
21344  if( N<=0 ){
21345    wsdPrng.isInit = 0;
21346    sqlite3_mutex_leave(mutex);
21347    return;
21348  }
21349
21350  /* Initialize the state of the random number generator once,
21351  ** the first time this routine is called.  The seed value does
21352  ** not need to contain a lot of randomness since we are not
21353  ** trying to do secure encryption or anything like that...
21354  **
21355  ** Nothing in this file or anywhere else in SQLite does any kind of
21356  ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
21357  ** number generator) not as an encryption device.
21358  */
21359  if( !wsdPrng.isInit ){
21360    int i;
21361    char k[256];
21362    wsdPrng.j = 0;
21363    wsdPrng.i = 0;
21364    sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
21365    for(i=0; i<256; i++){
21366      wsdPrng.s[i] = (u8)i;
21367    }
21368    for(i=0; i<256; i++){
21369      wsdPrng.j += wsdPrng.s[i] + k[i];
21370      t = wsdPrng.s[wsdPrng.j];
21371      wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
21372      wsdPrng.s[i] = t;
21373    }
21374    wsdPrng.isInit = 1;
21375  }
21376
21377  assert( N>0 );
21378  do{
21379    wsdPrng.i++;
21380    t = wsdPrng.s[wsdPrng.i];
21381    wsdPrng.j += t;
21382    wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
21383    wsdPrng.s[wsdPrng.j] = t;
21384    t += wsdPrng.s[wsdPrng.i];
21385    *(zBuf++) = wsdPrng.s[t];
21386  }while( --N );
21387  sqlite3_mutex_leave(mutex);
21388}
21389
21390#ifndef SQLITE_OMIT_BUILTIN_TEST
21391/*
21392** For testing purposes, we sometimes want to preserve the state of
21393** PRNG and restore the PRNG to its saved state at a later time, or
21394** to reset the PRNG to its initial state.  These routines accomplish
21395** those tasks.
21396**
21397** The sqlite3_test_control() interface calls these routines to
21398** control the PRNG.
21399*/
21400static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
21401SQLITE_PRIVATE void sqlite3PrngSaveState(void){
21402  memcpy(
21403    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
21404    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
21405    sizeof(sqlite3Prng)
21406  );
21407}
21408SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
21409  memcpy(
21410    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
21411    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
21412    sizeof(sqlite3Prng)
21413  );
21414}
21415#endif /* SQLITE_OMIT_BUILTIN_TEST */
21416
21417/************** End of random.c **********************************************/
21418/************** Begin file utf.c *********************************************/
21419/*
21420** 2004 April 13
21421**
21422** The author disclaims copyright to this source code.  In place of
21423** a legal notice, here is a blessing:
21424**
21425**    May you do good and not evil.
21426**    May you find forgiveness for yourself and forgive others.
21427**    May you share freely, never taking more than you give.
21428**
21429*************************************************************************
21430** This file contains routines used to translate between UTF-8,
21431** UTF-16, UTF-16BE, and UTF-16LE.
21432**
21433** Notes on UTF-8:
21434**
21435**   Byte-0    Byte-1    Byte-2    Byte-3    Value
21436**  0xxxxxxx                                 00000000 00000000 0xxxxxxx
21437**  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
21438**  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
21439**  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
21440**
21441**
21442** Notes on UTF-16:  (with wwww+1==uuuuu)
21443**
21444**      Word-0               Word-1          Value
21445**  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
21446**  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
21447**
21448**
21449** BOM or Byte Order Mark:
21450**     0xff 0xfe   little-endian utf-16 follows
21451**     0xfe 0xff   big-endian utf-16 follows
21452**
21453*/
21454/* #include <assert.h> */
21455
21456#ifndef SQLITE_AMALGAMATION
21457/*
21458** The following constant value is used by the SQLITE_BIGENDIAN and
21459** SQLITE_LITTLEENDIAN macros.
21460*/
21461SQLITE_PRIVATE const int sqlite3one = 1;
21462#endif /* SQLITE_AMALGAMATION */
21463
21464/*
21465** This lookup table is used to help decode the first byte of
21466** a multi-byte UTF8 character.
21467*/
21468static const unsigned char sqlite3Utf8Trans1[] = {
21469  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
21470  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
21471  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
21472  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
21473  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
21474  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
21475  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
21476  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
21477};
21478
21479
21480#define WRITE_UTF8(zOut, c) {                          \
21481  if( c<0x00080 ){                                     \
21482    *zOut++ = (u8)(c&0xFF);                            \
21483  }                                                    \
21484  else if( c<0x00800 ){                                \
21485    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
21486    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
21487  }                                                    \
21488  else if( c<0x10000 ){                                \
21489    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
21490    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
21491    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
21492  }else{                                               \
21493    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
21494    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
21495    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
21496    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
21497  }                                                    \
21498}
21499
21500#define WRITE_UTF16LE(zOut, c) {                                    \
21501  if( c<=0xFFFF ){                                                  \
21502    *zOut++ = (u8)(c&0x00FF);                                       \
21503    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
21504  }else{                                                            \
21505    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
21506    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
21507    *zOut++ = (u8)(c&0x00FF);                                       \
21508    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
21509  }                                                                 \
21510}
21511
21512#define WRITE_UTF16BE(zOut, c) {                                    \
21513  if( c<=0xFFFF ){                                                  \
21514    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
21515    *zOut++ = (u8)(c&0x00FF);                                       \
21516  }else{                                                            \
21517    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
21518    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
21519    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
21520    *zOut++ = (u8)(c&0x00FF);                                       \
21521  }                                                                 \
21522}
21523
21524#define READ_UTF16LE(zIn, TERM, c){                                   \
21525  c = (*zIn++);                                                       \
21526  c += ((*zIn++)<<8);                                                 \
21527  if( c>=0xD800 && c<0xE000 && TERM ){                                \
21528    int c2 = (*zIn++);                                                \
21529    c2 += ((*zIn++)<<8);                                              \
21530    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
21531  }                                                                   \
21532}
21533
21534#define READ_UTF16BE(zIn, TERM, c){                                   \
21535  c = ((*zIn++)<<8);                                                  \
21536  c += (*zIn++);                                                      \
21537  if( c>=0xD800 && c<0xE000 && TERM ){                                \
21538    int c2 = ((*zIn++)<<8);                                           \
21539    c2 += (*zIn++);                                                   \
21540    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
21541  }                                                                   \
21542}
21543
21544/*
21545** Translate a single UTF-8 character.  Return the unicode value.
21546**
21547** During translation, assume that the byte that zTerm points
21548** is a 0x00.
21549**
21550** Write a pointer to the next unread byte back into *pzNext.
21551**
21552** Notes On Invalid UTF-8:
21553**
21554**  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
21555**     be encoded as a multi-byte character.  Any multi-byte character that
21556**     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
21557**
21558**  *  This routine never allows a UTF16 surrogate value to be encoded.
21559**     If a multi-byte character attempts to encode a value between
21560**     0xd800 and 0xe000 then it is rendered as 0xfffd.
21561**
21562**  *  Bytes in the range of 0x80 through 0xbf which occur as the first
21563**     byte of a character are interpreted as single-byte characters
21564**     and rendered as themselves even though they are technically
21565**     invalid characters.
21566**
21567**  *  This routine accepts an infinite number of different UTF8 encodings
21568**     for unicode values 0x80 and greater.  It do not change over-length
21569**     encodings to 0xfffd as some systems recommend.
21570*/
21571#define READ_UTF8(zIn, zTerm, c)                           \
21572  c = *(zIn++);                                            \
21573  if( c>=0xc0 ){                                           \
21574    c = sqlite3Utf8Trans1[c-0xc0];                         \
21575    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
21576      c = (c<<6) + (0x3f & *(zIn++));                      \
21577    }                                                      \
21578    if( c<0x80                                             \
21579        || (c&0xFFFFF800)==0xD800                          \
21580        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
21581  }
21582SQLITE_PRIVATE u32 sqlite3Utf8Read(
21583  const unsigned char **pz    /* Pointer to string from which to read char */
21584){
21585  unsigned int c;
21586
21587  /* Same as READ_UTF8() above but without the zTerm parameter.
21588  ** For this routine, we assume the UTF8 string is always zero-terminated.
21589  */
21590  c = *((*pz)++);
21591  if( c>=0xc0 ){
21592    c = sqlite3Utf8Trans1[c-0xc0];
21593    while( (*(*pz) & 0xc0)==0x80 ){
21594      c = (c<<6) + (0x3f & *((*pz)++));
21595    }
21596    if( c<0x80
21597        || (c&0xFFFFF800)==0xD800
21598        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
21599  }
21600  return c;
21601}
21602
21603
21604
21605
21606/*
21607** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
21608** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
21609*/
21610/* #define TRANSLATE_TRACE 1 */
21611
21612#ifndef SQLITE_OMIT_UTF16
21613/*
21614** This routine transforms the internal text encoding used by pMem to
21615** desiredEnc. It is an error if the string is already of the desired
21616** encoding, or if *pMem does not contain a string value.
21617*/
21618SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
21619  int len;                    /* Maximum length of output string in bytes */
21620  unsigned char *zOut;                  /* Output buffer */
21621  unsigned char *zIn;                   /* Input iterator */
21622  unsigned char *zTerm;                 /* End of input */
21623  unsigned char *z;                     /* Output iterator */
21624  unsigned int c;
21625
21626  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
21627  assert( pMem->flags&MEM_Str );
21628  assert( pMem->enc!=desiredEnc );
21629  assert( pMem->enc!=0 );
21630  assert( pMem->n>=0 );
21631
21632#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
21633  {
21634    char zBuf[100];
21635    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
21636    fprintf(stderr, "INPUT:  %s\n", zBuf);
21637  }
21638#endif
21639
21640  /* If the translation is between UTF-16 little and big endian, then
21641  ** all that is required is to swap the byte order. This case is handled
21642  ** differently from the others.
21643  */
21644  if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
21645    u8 temp;
21646    int rc;
21647    rc = sqlite3VdbeMemMakeWriteable(pMem);
21648    if( rc!=SQLITE_OK ){
21649      assert( rc==SQLITE_NOMEM );
21650      return SQLITE_NOMEM;
21651    }
21652    zIn = (u8*)pMem->z;
21653    zTerm = &zIn[pMem->n&~1];
21654    while( zIn<zTerm ){
21655      temp = *zIn;
21656      *zIn = *(zIn+1);
21657      zIn++;
21658      *zIn++ = temp;
21659    }
21660    pMem->enc = desiredEnc;
21661    goto translate_out;
21662  }
21663
21664  /* Set len to the maximum number of bytes required in the output buffer. */
21665  if( desiredEnc==SQLITE_UTF8 ){
21666    /* When converting from UTF-16, the maximum growth results from
21667    ** translating a 2-byte character to a 4-byte UTF-8 character.
21668    ** A single byte is required for the output string
21669    ** nul-terminator.
21670    */
21671    pMem->n &= ~1;
21672    len = pMem->n * 2 + 1;
21673  }else{
21674    /* When converting from UTF-8 to UTF-16 the maximum growth is caused
21675    ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
21676    ** character. Two bytes are required in the output buffer for the
21677    ** nul-terminator.
21678    */
21679    len = pMem->n * 2 + 2;
21680  }
21681
21682  /* Set zIn to point at the start of the input buffer and zTerm to point 1
21683  ** byte past the end.
21684  **
21685  ** Variable zOut is set to point at the output buffer, space obtained
21686  ** from sqlite3_malloc().
21687  */
21688  zIn = (u8*)pMem->z;
21689  zTerm = &zIn[pMem->n];
21690  zOut = sqlite3DbMallocRaw(pMem->db, len);
21691  if( !zOut ){
21692    return SQLITE_NOMEM;
21693  }
21694  z = zOut;
21695
21696  if( pMem->enc==SQLITE_UTF8 ){
21697    if( desiredEnc==SQLITE_UTF16LE ){
21698      /* UTF-8 -> UTF-16 Little-endian */
21699      while( zIn<zTerm ){
21700        READ_UTF8(zIn, zTerm, c);
21701        WRITE_UTF16LE(z, c);
21702      }
21703    }else{
21704      assert( desiredEnc==SQLITE_UTF16BE );
21705      /* UTF-8 -> UTF-16 Big-endian */
21706      while( zIn<zTerm ){
21707        READ_UTF8(zIn, zTerm, c);
21708        WRITE_UTF16BE(z, c);
21709      }
21710    }
21711    pMem->n = (int)(z - zOut);
21712    *z++ = 0;
21713  }else{
21714    assert( desiredEnc==SQLITE_UTF8 );
21715    if( pMem->enc==SQLITE_UTF16LE ){
21716      /* UTF-16 Little-endian -> UTF-8 */
21717      while( zIn<zTerm ){
21718        READ_UTF16LE(zIn, zIn<zTerm, c);
21719        WRITE_UTF8(z, c);
21720      }
21721    }else{
21722      /* UTF-16 Big-endian -> UTF-8 */
21723      while( zIn<zTerm ){
21724        READ_UTF16BE(zIn, zIn<zTerm, c);
21725        WRITE_UTF8(z, c);
21726      }
21727    }
21728    pMem->n = (int)(z - zOut);
21729  }
21730  *z = 0;
21731  assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
21732
21733  sqlite3VdbeMemRelease(pMem);
21734  pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
21735  pMem->enc = desiredEnc;
21736  pMem->flags |= (MEM_Term);
21737  pMem->z = (char*)zOut;
21738  pMem->zMalloc = pMem->z;
21739
21740translate_out:
21741#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
21742  {
21743    char zBuf[100];
21744    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
21745    fprintf(stderr, "OUTPUT: %s\n", zBuf);
21746  }
21747#endif
21748  return SQLITE_OK;
21749}
21750
21751/*
21752** This routine checks for a byte-order mark at the beginning of the
21753** UTF-16 string stored in *pMem. If one is present, it is removed and
21754** the encoding of the Mem adjusted. This routine does not do any
21755** byte-swapping, it just sets Mem.enc appropriately.
21756**
21757** The allocation (static, dynamic etc.) and encoding of the Mem may be
21758** changed by this function.
21759*/
21760SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
21761  int rc = SQLITE_OK;
21762  u8 bom = 0;
21763
21764  assert( pMem->n>=0 );
21765  if( pMem->n>1 ){
21766    u8 b1 = *(u8 *)pMem->z;
21767    u8 b2 = *(((u8 *)pMem->z) + 1);
21768    if( b1==0xFE && b2==0xFF ){
21769      bom = SQLITE_UTF16BE;
21770    }
21771    if( b1==0xFF && b2==0xFE ){
21772      bom = SQLITE_UTF16LE;
21773    }
21774  }
21775
21776  if( bom ){
21777    rc = sqlite3VdbeMemMakeWriteable(pMem);
21778    if( rc==SQLITE_OK ){
21779      pMem->n -= 2;
21780      memmove(pMem->z, &pMem->z[2], pMem->n);
21781      pMem->z[pMem->n] = '\0';
21782      pMem->z[pMem->n+1] = '\0';
21783      pMem->flags |= MEM_Term;
21784      pMem->enc = bom;
21785    }
21786  }
21787  return rc;
21788}
21789#endif /* SQLITE_OMIT_UTF16 */
21790
21791/*
21792** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
21793** return the number of unicode characters in pZ up to (but not including)
21794** the first 0x00 byte. If nByte is not less than zero, return the
21795** number of unicode characters in the first nByte of pZ (or up to
21796** the first 0x00, whichever comes first).
21797*/
21798SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
21799  int r = 0;
21800  const u8 *z = (const u8*)zIn;
21801  const u8 *zTerm;
21802  if( nByte>=0 ){
21803    zTerm = &z[nByte];
21804  }else{
21805    zTerm = (const u8*)(-1);
21806  }
21807  assert( z<=zTerm );
21808  while( *z!=0 && z<zTerm ){
21809    SQLITE_SKIP_UTF8(z);
21810    r++;
21811  }
21812  return r;
21813}
21814
21815/* This test function is not currently used by the automated test-suite.
21816** Hence it is only available in debug builds.
21817*/
21818#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
21819/*
21820** Translate UTF-8 to UTF-8.
21821**
21822** This has the effect of making sure that the string is well-formed
21823** UTF-8.  Miscoded characters are removed.
21824**
21825** The translation is done in-place and aborted if the output
21826** overruns the input.
21827*/
21828SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
21829  unsigned char *zOut = zIn;
21830  unsigned char *zStart = zIn;
21831  u32 c;
21832
21833  while( zIn[0] && zOut<=zIn ){
21834    c = sqlite3Utf8Read((const u8**)&zIn);
21835    if( c!=0xfffd ){
21836      WRITE_UTF8(zOut, c);
21837    }
21838  }
21839  *zOut = 0;
21840  return (int)(zOut - zStart);
21841}
21842#endif
21843
21844#ifndef SQLITE_OMIT_UTF16
21845/*
21846** Convert a UTF-16 string in the native encoding into a UTF-8 string.
21847** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
21848** be freed by the calling function.
21849**
21850** NULL is returned if there is an allocation error.
21851*/
21852SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
21853  Mem m;
21854  memset(&m, 0, sizeof(m));
21855  m.db = db;
21856  sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
21857  sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
21858  if( db->mallocFailed ){
21859    sqlite3VdbeMemRelease(&m);
21860    m.z = 0;
21861  }
21862  assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
21863  assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
21864  assert( m.z || db->mallocFailed );
21865  return m.z;
21866}
21867
21868/*
21869** zIn is a UTF-16 encoded unicode string at least nChar characters long.
21870** Return the number of bytes in the first nChar unicode characters
21871** in pZ.  nChar must be non-negative.
21872*/
21873SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
21874  int c;
21875  unsigned char const *z = zIn;
21876  int n = 0;
21877
21878  if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
21879    while( n<nChar ){
21880      READ_UTF16BE(z, 1, c);
21881      n++;
21882    }
21883  }else{
21884    while( n<nChar ){
21885      READ_UTF16LE(z, 1, c);
21886      n++;
21887    }
21888  }
21889  return (int)(z-(unsigned char const *)zIn);
21890}
21891
21892#if defined(SQLITE_TEST)
21893/*
21894** This routine is called from the TCL test function "translate_selftest".
21895** It checks that the primitives for serializing and deserializing
21896** characters in each encoding are inverses of each other.
21897*/
21898SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
21899  unsigned int i, t;
21900  unsigned char zBuf[20];
21901  unsigned char *z;
21902  int n;
21903  unsigned int c;
21904
21905  for(i=0; i<0x00110000; i++){
21906    z = zBuf;
21907    WRITE_UTF8(z, i);
21908    n = (int)(z-zBuf);
21909    assert( n>0 && n<=4 );
21910    z[0] = 0;
21911    z = zBuf;
21912    c = sqlite3Utf8Read((const u8**)&z);
21913    t = i;
21914    if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
21915    if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
21916    assert( c==t );
21917    assert( (z-zBuf)==n );
21918  }
21919  for(i=0; i<0x00110000; i++){
21920    if( i>=0xD800 && i<0xE000 ) continue;
21921    z = zBuf;
21922    WRITE_UTF16LE(z, i);
21923    n = (int)(z-zBuf);
21924    assert( n>0 && n<=4 );
21925    z[0] = 0;
21926    z = zBuf;
21927    READ_UTF16LE(z, 1, c);
21928    assert( c==i );
21929    assert( (z-zBuf)==n );
21930  }
21931  for(i=0; i<0x00110000; i++){
21932    if( i>=0xD800 && i<0xE000 ) continue;
21933    z = zBuf;
21934    WRITE_UTF16BE(z, i);
21935    n = (int)(z-zBuf);
21936    assert( n>0 && n<=4 );
21937    z[0] = 0;
21938    z = zBuf;
21939    READ_UTF16BE(z, 1, c);
21940    assert( c==i );
21941    assert( (z-zBuf)==n );
21942  }
21943}
21944#endif /* SQLITE_TEST */
21945#endif /* SQLITE_OMIT_UTF16 */
21946
21947/************** End of utf.c *************************************************/
21948/************** Begin file util.c ********************************************/
21949/*
21950** 2001 September 15
21951**
21952** The author disclaims copyright to this source code.  In place of
21953** a legal notice, here is a blessing:
21954**
21955**    May you do good and not evil.
21956**    May you find forgiveness for yourself and forgive others.
21957**    May you share freely, never taking more than you give.
21958**
21959*************************************************************************
21960** Utility functions used throughout sqlite.
21961**
21962** This file contains functions for allocating memory, comparing
21963** strings, and stuff like that.
21964**
21965*/
21966/* #include <stdarg.h> */
21967#ifdef SQLITE_HAVE_ISNAN
21968# include <math.h>
21969#endif
21970
21971/*
21972** Routine needed to support the testcase() macro.
21973*/
21974#ifdef SQLITE_COVERAGE_TEST
21975SQLITE_PRIVATE void sqlite3Coverage(int x){
21976  static unsigned dummy = 0;
21977  dummy += (unsigned)x;
21978}
21979#endif
21980
21981/*
21982** Give a callback to the test harness that can be used to simulate faults
21983** in places where it is difficult or expensive to do so purely by means
21984** of inputs.
21985**
21986** The intent of the integer argument is to let the fault simulator know
21987** which of multiple sqlite3FaultSim() calls has been hit.
21988**
21989** Return whatever integer value the test callback returns, or return
21990** SQLITE_OK if no test callback is installed.
21991*/
21992#ifndef SQLITE_OMIT_BUILTIN_TEST
21993SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
21994  int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
21995  return xCallback ? xCallback(iTest) : SQLITE_OK;
21996}
21997#endif
21998
21999#ifndef SQLITE_OMIT_FLOATING_POINT
22000/*
22001** Return true if the floating point value is Not a Number (NaN).
22002**
22003** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
22004** Otherwise, we have our own implementation that works on most systems.
22005*/
22006SQLITE_PRIVATE int sqlite3IsNaN(double x){
22007  int rc;   /* The value return */
22008#if !defined(SQLITE_HAVE_ISNAN)
22009  /*
22010  ** Systems that support the isnan() library function should probably
22011  ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
22012  ** found that many systems do not have a working isnan() function so
22013  ** this implementation is provided as an alternative.
22014  **
22015  ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
22016  ** On the other hand, the use of -ffast-math comes with the following
22017  ** warning:
22018  **
22019  **      This option [-ffast-math] should never be turned on by any
22020  **      -O option since it can result in incorrect output for programs
22021  **      which depend on an exact implementation of IEEE or ISO
22022  **      rules/specifications for math functions.
22023  **
22024  ** Under MSVC, this NaN test may fail if compiled with a floating-
22025  ** point precision mode other than /fp:precise.  From the MSDN
22026  ** documentation:
22027  **
22028  **      The compiler [with /fp:precise] will properly handle comparisons
22029  **      involving NaN. For example, x != x evaluates to true if x is NaN
22030  **      ...
22031  */
22032#ifdef __FAST_MATH__
22033# error SQLite will not work correctly with the -ffast-math option of GCC.
22034#endif
22035  volatile double y = x;
22036  volatile double z = y;
22037  rc = (y!=z);
22038#else  /* if defined(SQLITE_HAVE_ISNAN) */
22039  rc = isnan(x);
22040#endif /* SQLITE_HAVE_ISNAN */
22041  testcase( rc );
22042  return rc;
22043}
22044#endif /* SQLITE_OMIT_FLOATING_POINT */
22045
22046/*
22047** Compute a string length that is limited to what can be stored in
22048** lower 30 bits of a 32-bit signed integer.
22049**
22050** The value returned will never be negative.  Nor will it ever be greater
22051** than the actual length of the string.  For very long strings (greater
22052** than 1GiB) the value returned might be less than the true string length.
22053*/
22054SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
22055  const char *z2 = z;
22056  if( z==0 ) return 0;
22057  while( *z2 ){ z2++; }
22058  return 0x3fffffff & (int)(z2 - z);
22059}
22060
22061/*
22062** Set the most recent error code and error string for the sqlite
22063** handle "db". The error code is set to "err_code".
22064**
22065** If it is not NULL, string zFormat specifies the format of the
22066** error string in the style of the printf functions: The following
22067** format characters are allowed:
22068**
22069**      %s      Insert a string
22070**      %z      A string that should be freed after use
22071**      %d      Insert an integer
22072**      %T      Insert a token
22073**      %S      Insert the first element of a SrcList
22074**
22075** zFormat and any string tokens that follow it are assumed to be
22076** encoded in UTF-8.
22077**
22078** To clear the most recent error for sqlite handle "db", sqlite3Error
22079** should be called with err_code set to SQLITE_OK and zFormat set
22080** to NULL.
22081*/
22082SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
22083  assert( db!=0 );
22084  db->errCode = err_code;
22085  if( zFormat && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
22086    char *z;
22087    va_list ap;
22088    va_start(ap, zFormat);
22089    z = sqlite3VMPrintf(db, zFormat, ap);
22090    va_end(ap);
22091    sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
22092  }else if( db->pErr ){
22093    sqlite3ValueSetNull(db->pErr);
22094  }
22095}
22096
22097/*
22098** Add an error message to pParse->zErrMsg and increment pParse->nErr.
22099** The following formatting characters are allowed:
22100**
22101**      %s      Insert a string
22102**      %z      A string that should be freed after use
22103**      %d      Insert an integer
22104**      %T      Insert a token
22105**      %S      Insert the first element of a SrcList
22106**
22107** This function should be used to report any error that occurs whilst
22108** compiling an SQL statement (i.e. within sqlite3_prepare()). The
22109** last thing the sqlite3_prepare() function does is copy the error
22110** stored by this function into the database handle using sqlite3Error().
22111** Function sqlite3Error() should be used during statement execution
22112** (sqlite3_step() etc.).
22113*/
22114SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
22115  char *zMsg;
22116  va_list ap;
22117  sqlite3 *db = pParse->db;
22118  va_start(ap, zFormat);
22119  zMsg = sqlite3VMPrintf(db, zFormat, ap);
22120  va_end(ap);
22121  if( db->suppressErr ){
22122    sqlite3DbFree(db, zMsg);
22123  }else{
22124    pParse->nErr++;
22125    sqlite3DbFree(db, pParse->zErrMsg);
22126    pParse->zErrMsg = zMsg;
22127    pParse->rc = SQLITE_ERROR;
22128  }
22129}
22130
22131/*
22132** Convert an SQL-style quoted string into a normal string by removing
22133** the quote characters.  The conversion is done in-place.  If the
22134** input does not begin with a quote character, then this routine
22135** is a no-op.
22136**
22137** The input string must be zero-terminated.  A new zero-terminator
22138** is added to the dequoted string.
22139**
22140** The return value is -1 if no dequoting occurs or the length of the
22141** dequoted string, exclusive of the zero terminator, if dequoting does
22142** occur.
22143**
22144** 2002-Feb-14: This routine is extended to remove MS-Access style
22145** brackets from around identifers.  For example:  "[a-b-c]" becomes
22146** "a-b-c".
22147*/
22148SQLITE_PRIVATE int sqlite3Dequote(char *z){
22149  char quote;
22150  int i, j;
22151  if( z==0 ) return -1;
22152  quote = z[0];
22153  switch( quote ){
22154    case '\'':  break;
22155    case '"':   break;
22156    case '`':   break;                /* For MySQL compatibility */
22157    case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
22158    default:    return -1;
22159  }
22160  for(i=1, j=0;; i++){
22161    assert( z[i] );
22162    if( z[i]==quote ){
22163      if( z[i+1]==quote ){
22164        z[j++] = quote;
22165        i++;
22166      }else{
22167        break;
22168      }
22169    }else{
22170      z[j++] = z[i];
22171    }
22172  }
22173  z[j] = 0;
22174  return j;
22175}
22176
22177/* Convenient short-hand */
22178#define UpperToLower sqlite3UpperToLower
22179
22180/*
22181** Some systems have stricmp().  Others have strcasecmp().  Because
22182** there is no consistency, we will define our own.
22183**
22184** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
22185** sqlite3_strnicmp() APIs allow applications and extensions to compare
22186** the contents of two buffers containing UTF-8 strings in a
22187** case-independent fashion, using the same definition of "case
22188** independence" that SQLite uses internally when comparing identifiers.
22189*/
22190SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
22191  register unsigned char *a, *b;
22192  a = (unsigned char *)zLeft;
22193  b = (unsigned char *)zRight;
22194  while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
22195  return UpperToLower[*a] - UpperToLower[*b];
22196}
22197SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
22198  register unsigned char *a, *b;
22199  a = (unsigned char *)zLeft;
22200  b = (unsigned char *)zRight;
22201  while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
22202  return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
22203}
22204
22205/*
22206** The string z[] is an text representation of a real number.
22207** Convert this string to a double and write it into *pResult.
22208**
22209** The string z[] is length bytes in length (bytes, not characters) and
22210** uses the encoding enc.  The string is not necessarily zero-terminated.
22211**
22212** Return TRUE if the result is a valid real number (or integer) and FALSE
22213** if the string is empty or contains extraneous text.  Valid numbers
22214** are in one of these formats:
22215**
22216**    [+-]digits[E[+-]digits]
22217**    [+-]digits.[digits][E[+-]digits]
22218**    [+-].digits[E[+-]digits]
22219**
22220** Leading and trailing whitespace is ignored for the purpose of determining
22221** validity.
22222**
22223** If some prefix of the input string is a valid number, this routine
22224** returns FALSE but it still converts the prefix and writes the result
22225** into *pResult.
22226*/
22227SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
22228#ifndef SQLITE_OMIT_FLOATING_POINT
22229  int incr;
22230  const char *zEnd = z + length;
22231  /* sign * significand * (10 ^ (esign * exponent)) */
22232  int sign = 1;    /* sign of significand */
22233  i64 s = 0;       /* significand */
22234  int d = 0;       /* adjust exponent for shifting decimal point */
22235  int esign = 1;   /* sign of exponent */
22236  int e = 0;       /* exponent */
22237  int eValid = 1;  /* True exponent is either not used or is well-formed */
22238  double result;
22239  int nDigits = 0;
22240  int nonNum = 0;
22241
22242  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
22243  *pResult = 0.0;   /* Default return value, in case of an error */
22244
22245  if( enc==SQLITE_UTF8 ){
22246    incr = 1;
22247  }else{
22248    int i;
22249    incr = 2;
22250    assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
22251    for(i=3-enc; i<length && z[i]==0; i+=2){}
22252    nonNum = i<length;
22253    zEnd = z+i+enc-3;
22254    z += (enc&1);
22255  }
22256
22257  /* skip leading spaces */
22258  while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
22259  if( z>=zEnd ) return 0;
22260
22261  /* get sign of significand */
22262  if( *z=='-' ){
22263    sign = -1;
22264    z+=incr;
22265  }else if( *z=='+' ){
22266    z+=incr;
22267  }
22268
22269  /* skip leading zeroes */
22270  while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
22271
22272  /* copy max significant digits to significand */
22273  while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
22274    s = s*10 + (*z - '0');
22275    z+=incr, nDigits++;
22276  }
22277
22278  /* skip non-significant significand digits
22279  ** (increase exponent by d to shift decimal left) */
22280  while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
22281  if( z>=zEnd ) goto do_atof_calc;
22282
22283  /* if decimal point is present */
22284  if( *z=='.' ){
22285    z+=incr;
22286    /* copy digits from after decimal to significand
22287    ** (decrease exponent by d to shift decimal right) */
22288    while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
22289      s = s*10 + (*z - '0');
22290      z+=incr, nDigits++, d--;
22291    }
22292    /* skip non-significant digits */
22293    while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
22294  }
22295  if( z>=zEnd ) goto do_atof_calc;
22296
22297  /* if exponent is present */
22298  if( *z=='e' || *z=='E' ){
22299    z+=incr;
22300    eValid = 0;
22301    if( z>=zEnd ) goto do_atof_calc;
22302    /* get sign of exponent */
22303    if( *z=='-' ){
22304      esign = -1;
22305      z+=incr;
22306    }else if( *z=='+' ){
22307      z+=incr;
22308    }
22309    /* copy digits to exponent */
22310    while( z<zEnd && sqlite3Isdigit(*z) ){
22311      e = e<10000 ? (e*10 + (*z - '0')) : 10000;
22312      z+=incr;
22313      eValid = 1;
22314    }
22315  }
22316
22317  /* skip trailing spaces */
22318  if( nDigits && eValid ){
22319    while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
22320  }
22321
22322do_atof_calc:
22323  /* adjust exponent by d, and update sign */
22324  e = (e*esign) + d;
22325  if( e<0 ) {
22326    esign = -1;
22327    e *= -1;
22328  } else {
22329    esign = 1;
22330  }
22331
22332  /* if 0 significand */
22333  if( !s ) {
22334    /* In the IEEE 754 standard, zero is signed.
22335    ** Add the sign if we've seen at least one digit */
22336    result = (sign<0 && nDigits) ? -(double)0 : (double)0;
22337  } else {
22338    /* attempt to reduce exponent */
22339    if( esign>0 ){
22340      while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
22341    }else{
22342      while( !(s%10) && e>0 ) e--,s/=10;
22343    }
22344
22345    /* adjust the sign of significand */
22346    s = sign<0 ? -s : s;
22347
22348    /* if exponent, scale significand as appropriate
22349    ** and store in result. */
22350    if( e ){
22351      LONGDOUBLE_TYPE scale = 1.0;
22352      /* attempt to handle extremely small/large numbers better */
22353      if( e>307 && e<342 ){
22354        while( e%308 ) { scale *= 1.0e+1; e -= 1; }
22355        if( esign<0 ){
22356          result = s / scale;
22357          result /= 1.0e+308;
22358        }else{
22359          result = s * scale;
22360          result *= 1.0e+308;
22361        }
22362      }else if( e>=342 ){
22363        if( esign<0 ){
22364          result = 0.0*s;
22365        }else{
22366          result = 1e308*1e308*s;  /* Infinity */
22367        }
22368      }else{
22369        /* 1.0e+22 is the largest power of 10 than can be
22370        ** represented exactly. */
22371        while( e%22 ) { scale *= 1.0e+1; e -= 1; }
22372        while( e>0 ) { scale *= 1.0e+22; e -= 22; }
22373        if( esign<0 ){
22374          result = s / scale;
22375        }else{
22376          result = s * scale;
22377        }
22378      }
22379    } else {
22380      result = (double)s;
22381    }
22382  }
22383
22384  /* store the result */
22385  *pResult = result;
22386
22387  /* return true if number and no extra non-whitespace chracters after */
22388  return z>=zEnd && nDigits>0 && eValid && nonNum==0;
22389#else
22390  return !sqlite3Atoi64(z, pResult, length, enc);
22391#endif /* SQLITE_OMIT_FLOATING_POINT */
22392}
22393
22394/*
22395** Compare the 19-character string zNum against the text representation
22396** value 2^63:  9223372036854775808.  Return negative, zero, or positive
22397** if zNum is less than, equal to, or greater than the string.
22398** Note that zNum must contain exactly 19 characters.
22399**
22400** Unlike memcmp() this routine is guaranteed to return the difference
22401** in the values of the last digit if the only difference is in the
22402** last digit.  So, for example,
22403**
22404**      compare2pow63("9223372036854775800", 1)
22405**
22406** will return -8.
22407*/
22408static int compare2pow63(const char *zNum, int incr){
22409  int c = 0;
22410  int i;
22411                    /* 012345678901234567 */
22412  const char *pow63 = "922337203685477580";
22413  for(i=0; c==0 && i<18; i++){
22414    c = (zNum[i*incr]-pow63[i])*10;
22415  }
22416  if( c==0 ){
22417    c = zNum[18*incr] - '8';
22418    testcase( c==(-1) );
22419    testcase( c==0 );
22420    testcase( c==(+1) );
22421  }
22422  return c;
22423}
22424
22425
22426/*
22427** Convert zNum to a 64-bit signed integer.
22428**
22429** If the zNum value is representable as a 64-bit twos-complement
22430** integer, then write that value into *pNum and return 0.
22431**
22432** If zNum is exactly 9223372036854775808, return 2.  This special
22433** case is broken out because while 9223372036854775808 cannot be a
22434** signed 64-bit integer, its negative -9223372036854775808 can be.
22435**
22436** If zNum is too big for a 64-bit integer and is not
22437** 9223372036854775808  or if zNum contains any non-numeric text,
22438** then return 1.
22439**
22440** length is the number of bytes in the string (bytes, not characters).
22441** The string is not necessarily zero-terminated.  The encoding is
22442** given by enc.
22443*/
22444SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
22445  int incr;
22446  u64 u = 0;
22447  int neg = 0; /* assume positive */
22448  int i;
22449  int c = 0;
22450  int nonNum = 0;
22451  const char *zStart;
22452  const char *zEnd = zNum + length;
22453  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
22454  if( enc==SQLITE_UTF8 ){
22455    incr = 1;
22456  }else{
22457    incr = 2;
22458    assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
22459    for(i=3-enc; i<length && zNum[i]==0; i+=2){}
22460    nonNum = i<length;
22461    zEnd = zNum+i+enc-3;
22462    zNum += (enc&1);
22463  }
22464  while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
22465  if( zNum<zEnd ){
22466    if( *zNum=='-' ){
22467      neg = 1;
22468      zNum+=incr;
22469    }else if( *zNum=='+' ){
22470      zNum+=incr;
22471    }
22472  }
22473  zStart = zNum;
22474  while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
22475  for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
22476    u = u*10 + c - '0';
22477  }
22478  if( u>LARGEST_INT64 ){
22479    *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
22480  }else if( neg ){
22481    *pNum = -(i64)u;
22482  }else{
22483    *pNum = (i64)u;
22484  }
22485  testcase( i==18 );
22486  testcase( i==19 );
22487  testcase( i==20 );
22488  if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr || nonNum ){
22489    /* zNum is empty or contains non-numeric text or is longer
22490    ** than 19 digits (thus guaranteeing that it is too large) */
22491    return 1;
22492  }else if( i<19*incr ){
22493    /* Less than 19 digits, so we know that it fits in 64 bits */
22494    assert( u<=LARGEST_INT64 );
22495    return 0;
22496  }else{
22497    /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
22498    c = compare2pow63(zNum, incr);
22499    if( c<0 ){
22500      /* zNum is less than 9223372036854775808 so it fits */
22501      assert( u<=LARGEST_INT64 );
22502      return 0;
22503    }else if( c>0 ){
22504      /* zNum is greater than 9223372036854775808 so it overflows */
22505      return 1;
22506    }else{
22507      /* zNum is exactly 9223372036854775808.  Fits if negative.  The
22508      ** special case 2 overflow if positive */
22509      assert( u-1==LARGEST_INT64 );
22510      return neg ? 0 : 2;
22511    }
22512  }
22513}
22514
22515/*
22516** If zNum represents an integer that will fit in 32-bits, then set
22517** *pValue to that integer and return true.  Otherwise return false.
22518**
22519** Any non-numeric characters that following zNum are ignored.
22520** This is different from sqlite3Atoi64() which requires the
22521** input number to be zero-terminated.
22522*/
22523SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
22524  sqlite_int64 v = 0;
22525  int i, c;
22526  int neg = 0;
22527  if( zNum[0]=='-' ){
22528    neg = 1;
22529    zNum++;
22530  }else if( zNum[0]=='+' ){
22531    zNum++;
22532  }
22533  while( zNum[0]=='0' ) zNum++;
22534  for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
22535    v = v*10 + c;
22536  }
22537
22538  /* The longest decimal representation of a 32 bit integer is 10 digits:
22539  **
22540  **             1234567890
22541  **     2^31 -> 2147483648
22542  */
22543  testcase( i==10 );
22544  if( i>10 ){
22545    return 0;
22546  }
22547  testcase( v-neg==2147483647 );
22548  if( v-neg>2147483647 ){
22549    return 0;
22550  }
22551  if( neg ){
22552    v = -v;
22553  }
22554  *pValue = (int)v;
22555  return 1;
22556}
22557
22558/*
22559** Return a 32-bit integer value extracted from a string.  If the
22560** string is not an integer, just return 0.
22561*/
22562SQLITE_PRIVATE int sqlite3Atoi(const char *z){
22563  int x = 0;
22564  if( z ) sqlite3GetInt32(z, &x);
22565  return x;
22566}
22567
22568/*
22569** The variable-length integer encoding is as follows:
22570**
22571** KEY:
22572**         A = 0xxxxxxx    7 bits of data and one flag bit
22573**         B = 1xxxxxxx    7 bits of data and one flag bit
22574**         C = xxxxxxxx    8 bits of data
22575**
22576**  7 bits - A
22577** 14 bits - BA
22578** 21 bits - BBA
22579** 28 bits - BBBA
22580** 35 bits - BBBBA
22581** 42 bits - BBBBBA
22582** 49 bits - BBBBBBA
22583** 56 bits - BBBBBBBA
22584** 64 bits - BBBBBBBBC
22585*/
22586
22587/*
22588** Write a 64-bit variable-length integer to memory starting at p[0].
22589** The length of data write will be between 1 and 9 bytes.  The number
22590** of bytes written is returned.
22591**
22592** A variable-length integer consists of the lower 7 bits of each byte
22593** for all bytes that have the 8th bit set and one byte with the 8th
22594** bit clear.  Except, if we get to the 9th byte, it stores the full
22595** 8 bits and is the last byte.
22596*/
22597SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
22598  int i, j, n;
22599  u8 buf[10];
22600  if( v & (((u64)0xff000000)<<32) ){
22601    p[8] = (u8)v;
22602    v >>= 8;
22603    for(i=7; i>=0; i--){
22604      p[i] = (u8)((v & 0x7f) | 0x80);
22605      v >>= 7;
22606    }
22607    return 9;
22608  }
22609  n = 0;
22610  do{
22611    buf[n++] = (u8)((v & 0x7f) | 0x80);
22612    v >>= 7;
22613  }while( v!=0 );
22614  buf[0] &= 0x7f;
22615  assert( n<=9 );
22616  for(i=0, j=n-1; j>=0; j--, i++){
22617    p[i] = buf[j];
22618  }
22619  return n;
22620}
22621
22622/*
22623** This routine is a faster version of sqlite3PutVarint() that only
22624** works for 32-bit positive integers and which is optimized for
22625** the common case of small integers.  A MACRO version, putVarint32,
22626** is provided which inlines the single-byte case.  All code should use
22627** the MACRO version as this function assumes the single-byte case has
22628** already been handled.
22629*/
22630SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
22631#ifndef putVarint32
22632  if( (v & ~0x7f)==0 ){
22633    p[0] = v;
22634    return 1;
22635  }
22636#endif
22637  if( (v & ~0x3fff)==0 ){
22638    p[0] = (u8)((v>>7) | 0x80);
22639    p[1] = (u8)(v & 0x7f);
22640    return 2;
22641  }
22642  return sqlite3PutVarint(p, v);
22643}
22644
22645/*
22646** Bitmasks used by sqlite3GetVarint().  These precomputed constants
22647** are defined here rather than simply putting the constant expressions
22648** inline in order to work around bugs in the RVT compiler.
22649**
22650** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
22651**
22652** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
22653*/
22654#define SLOT_2_0     0x001fc07f
22655#define SLOT_4_2_0   0xf01fc07f
22656
22657
22658/*
22659** Read a 64-bit variable-length integer from memory starting at p[0].
22660** Return the number of bytes read.  The value is stored in *v.
22661*/
22662SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
22663  u32 a,b,s;
22664
22665  a = *p;
22666  /* a: p0 (unmasked) */
22667  if (!(a&0x80))
22668  {
22669    *v = a;
22670    return 1;
22671  }
22672
22673  p++;
22674  b = *p;
22675  /* b: p1 (unmasked) */
22676  if (!(b&0x80))
22677  {
22678    a &= 0x7f;
22679    a = a<<7;
22680    a |= b;
22681    *v = a;
22682    return 2;
22683  }
22684
22685  /* Verify that constants are precomputed correctly */
22686  assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
22687  assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
22688
22689  p++;
22690  a = a<<14;
22691  a |= *p;
22692  /* a: p0<<14 | p2 (unmasked) */
22693  if (!(a&0x80))
22694  {
22695    a &= SLOT_2_0;
22696    b &= 0x7f;
22697    b = b<<7;
22698    a |= b;
22699    *v = a;
22700    return 3;
22701  }
22702
22703  /* CSE1 from below */
22704  a &= SLOT_2_0;
22705  p++;
22706  b = b<<14;
22707  b |= *p;
22708  /* b: p1<<14 | p3 (unmasked) */
22709  if (!(b&0x80))
22710  {
22711    b &= SLOT_2_0;
22712    /* moved CSE1 up */
22713    /* a &= (0x7f<<14)|(0x7f); */
22714    a = a<<7;
22715    a |= b;
22716    *v = a;
22717    return 4;
22718  }
22719
22720  /* a: p0<<14 | p2 (masked) */
22721  /* b: p1<<14 | p3 (unmasked) */
22722  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
22723  /* moved CSE1 up */
22724  /* a &= (0x7f<<14)|(0x7f); */
22725  b &= SLOT_2_0;
22726  s = a;
22727  /* s: p0<<14 | p2 (masked) */
22728
22729  p++;
22730  a = a<<14;
22731  a |= *p;
22732  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
22733  if (!(a&0x80))
22734  {
22735    /* we can skip these cause they were (effectively) done above in calc'ing s */
22736    /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
22737    /* b &= (0x7f<<14)|(0x7f); */
22738    b = b<<7;
22739    a |= b;
22740    s = s>>18;
22741    *v = ((u64)s)<<32 | a;
22742    return 5;
22743  }
22744
22745  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
22746  s = s<<7;
22747  s |= b;
22748  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
22749
22750  p++;
22751  b = b<<14;
22752  b |= *p;
22753  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
22754  if (!(b&0x80))
22755  {
22756    /* we can skip this cause it was (effectively) done above in calc'ing s */
22757    /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
22758    a &= SLOT_2_0;
22759    a = a<<7;
22760    a |= b;
22761    s = s>>18;
22762    *v = ((u64)s)<<32 | a;
22763    return 6;
22764  }
22765
22766  p++;
22767  a = a<<14;
22768  a |= *p;
22769  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
22770  if (!(a&0x80))
22771  {
22772    a &= SLOT_4_2_0;
22773    b &= SLOT_2_0;
22774    b = b<<7;
22775    a |= b;
22776    s = s>>11;
22777    *v = ((u64)s)<<32 | a;
22778    return 7;
22779  }
22780
22781  /* CSE2 from below */
22782  a &= SLOT_2_0;
22783  p++;
22784  b = b<<14;
22785  b |= *p;
22786  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
22787  if (!(b&0x80))
22788  {
22789    b &= SLOT_4_2_0;
22790    /* moved CSE2 up */
22791    /* a &= (0x7f<<14)|(0x7f); */
22792    a = a<<7;
22793    a |= b;
22794    s = s>>4;
22795    *v = ((u64)s)<<32 | a;
22796    return 8;
22797  }
22798
22799  p++;
22800  a = a<<15;
22801  a |= *p;
22802  /* a: p4<<29 | p6<<15 | p8 (unmasked) */
22803
22804  /* moved CSE2 up */
22805  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
22806  b &= SLOT_2_0;
22807  b = b<<8;
22808  a |= b;
22809
22810  s = s<<4;
22811  b = p[-4];
22812  b &= 0x7f;
22813  b = b>>3;
22814  s |= b;
22815
22816  *v = ((u64)s)<<32 | a;
22817
22818  return 9;
22819}
22820
22821/*
22822** Read a 32-bit variable-length integer from memory starting at p[0].
22823** Return the number of bytes read.  The value is stored in *v.
22824**
22825** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
22826** integer, then set *v to 0xffffffff.
22827**
22828** A MACRO version, getVarint32, is provided which inlines the
22829** single-byte case.  All code should use the MACRO version as
22830** this function assumes the single-byte case has already been handled.
22831*/
22832SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
22833  u32 a,b;
22834
22835  /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
22836  ** by the getVarin32() macro */
22837  a = *p;
22838  /* a: p0 (unmasked) */
22839#ifndef getVarint32
22840  if (!(a&0x80))
22841  {
22842    /* Values between 0 and 127 */
22843    *v = a;
22844    return 1;
22845  }
22846#endif
22847
22848  /* The 2-byte case */
22849  p++;
22850  b = *p;
22851  /* b: p1 (unmasked) */
22852  if (!(b&0x80))
22853  {
22854    /* Values between 128 and 16383 */
22855    a &= 0x7f;
22856    a = a<<7;
22857    *v = a | b;
22858    return 2;
22859  }
22860
22861  /* The 3-byte case */
22862  p++;
22863  a = a<<14;
22864  a |= *p;
22865  /* a: p0<<14 | p2 (unmasked) */
22866  if (!(a&0x80))
22867  {
22868    /* Values between 16384 and 2097151 */
22869    a &= (0x7f<<14)|(0x7f);
22870    b &= 0x7f;
22871    b = b<<7;
22872    *v = a | b;
22873    return 3;
22874  }
22875
22876  /* A 32-bit varint is used to store size information in btrees.
22877  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
22878  ** A 3-byte varint is sufficient, for example, to record the size
22879  ** of a 1048569-byte BLOB or string.
22880  **
22881  ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
22882  ** rare larger cases can be handled by the slower 64-bit varint
22883  ** routine.
22884  */
22885#if 1
22886  {
22887    u64 v64;
22888    u8 n;
22889
22890    p -= 2;
22891    n = sqlite3GetVarint(p, &v64);
22892    assert( n>3 && n<=9 );
22893    if( (v64 & SQLITE_MAX_U32)!=v64 ){
22894      *v = 0xffffffff;
22895    }else{
22896      *v = (u32)v64;
22897    }
22898    return n;
22899  }
22900
22901#else
22902  /* For following code (kept for historical record only) shows an
22903  ** unrolling for the 3- and 4-byte varint cases.  This code is
22904  ** slightly faster, but it is also larger and much harder to test.
22905  */
22906  p++;
22907  b = b<<14;
22908  b |= *p;
22909  /* b: p1<<14 | p3 (unmasked) */
22910  if (!(b&0x80))
22911  {
22912    /* Values between 2097152 and 268435455 */
22913    b &= (0x7f<<14)|(0x7f);
22914    a &= (0x7f<<14)|(0x7f);
22915    a = a<<7;
22916    *v = a | b;
22917    return 4;
22918  }
22919
22920  p++;
22921  a = a<<14;
22922  a |= *p;
22923  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
22924  if (!(a&0x80))
22925  {
22926    /* Values  between 268435456 and 34359738367 */
22927    a &= SLOT_4_2_0;
22928    b &= SLOT_4_2_0;
22929    b = b<<7;
22930    *v = a | b;
22931    return 5;
22932  }
22933
22934  /* We can only reach this point when reading a corrupt database
22935  ** file.  In that case we are not in any hurry.  Use the (relatively
22936  ** slow) general-purpose sqlite3GetVarint() routine to extract the
22937  ** value. */
22938  {
22939    u64 v64;
22940    u8 n;
22941
22942    p -= 4;
22943    n = sqlite3GetVarint(p, &v64);
22944    assert( n>5 && n<=9 );
22945    *v = (u32)v64;
22946    return n;
22947  }
22948#endif
22949}
22950
22951/*
22952** Return the number of bytes that will be needed to store the given
22953** 64-bit integer.
22954*/
22955SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
22956  int i = 0;
22957  do{
22958    i++;
22959    v >>= 7;
22960  }while( v!=0 && ALWAYS(i<9) );
22961  return i;
22962}
22963
22964
22965/*
22966** Read or write a four-byte big-endian integer value.
22967*/
22968SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
22969  testcase( p[0]&0x80 );
22970  return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
22971}
22972SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
22973  p[0] = (u8)(v>>24);
22974  p[1] = (u8)(v>>16);
22975  p[2] = (u8)(v>>8);
22976  p[3] = (u8)v;
22977}
22978
22979
22980
22981/*
22982** Translate a single byte of Hex into an integer.
22983** This routine only works if h really is a valid hexadecimal
22984** character:  0..9a..fA..F
22985*/
22986SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
22987  assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
22988#ifdef SQLITE_ASCII
22989  h += 9*(1&(h>>6));
22990#endif
22991#ifdef SQLITE_EBCDIC
22992  h += 9*(1&~(h>>4));
22993#endif
22994  return (u8)(h & 0xf);
22995}
22996
22997#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
22998/*
22999** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
23000** value.  Return a pointer to its binary value.  Space to hold the
23001** binary value has been obtained from malloc and must be freed by
23002** the calling routine.
23003*/
23004SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
23005  char *zBlob;
23006  int i;
23007
23008  zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
23009  n--;
23010  if( zBlob ){
23011    for(i=0; i<n; i+=2){
23012      zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
23013    }
23014    zBlob[i/2] = 0;
23015  }
23016  return zBlob;
23017}
23018#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
23019
23020/*
23021** Log an error that is an API call on a connection pointer that should
23022** not have been used.  The "type" of connection pointer is given as the
23023** argument.  The zType is a word like "NULL" or "closed" or "invalid".
23024*/
23025static void logBadConnection(const char *zType){
23026  sqlite3_log(SQLITE_MISUSE,
23027     "API call with %s database connection pointer",
23028     zType
23029  );
23030}
23031
23032/*
23033** Check to make sure we have a valid db pointer.  This test is not
23034** foolproof but it does provide some measure of protection against
23035** misuse of the interface such as passing in db pointers that are
23036** NULL or which have been previously closed.  If this routine returns
23037** 1 it means that the db pointer is valid and 0 if it should not be
23038** dereferenced for any reason.  The calling function should invoke
23039** SQLITE_MISUSE immediately.
23040**
23041** sqlite3SafetyCheckOk() requires that the db pointer be valid for
23042** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
23043** open properly and is not fit for general use but which can be
23044** used as an argument to sqlite3_errmsg() or sqlite3_close().
23045*/
23046SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
23047  u32 magic;
23048  if( db==0 ){
23049    logBadConnection("NULL");
23050    return 0;
23051  }
23052  magic = db->magic;
23053  if( magic!=SQLITE_MAGIC_OPEN ){
23054    if( sqlite3SafetyCheckSickOrOk(db) ){
23055      testcase( sqlite3GlobalConfig.xLog!=0 );
23056      logBadConnection("unopened");
23057    }
23058    return 0;
23059  }else{
23060    return 1;
23061  }
23062}
23063SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
23064  u32 magic;
23065  magic = db->magic;
23066  if( magic!=SQLITE_MAGIC_SICK &&
23067      magic!=SQLITE_MAGIC_OPEN &&
23068      magic!=SQLITE_MAGIC_BUSY ){
23069    testcase( sqlite3GlobalConfig.xLog!=0 );
23070    logBadConnection("invalid");
23071    return 0;
23072  }else{
23073    return 1;
23074  }
23075}
23076
23077/*
23078** Attempt to add, substract, or multiply the 64-bit signed value iB against
23079** the other 64-bit signed integer at *pA and store the result in *pA.
23080** Return 0 on success.  Or if the operation would have resulted in an
23081** overflow, leave *pA unchanged and return 1.
23082*/
23083SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
23084  i64 iA = *pA;
23085  testcase( iA==0 ); testcase( iA==1 );
23086  testcase( iB==-1 ); testcase( iB==0 );
23087  if( iB>=0 ){
23088    testcase( iA>0 && LARGEST_INT64 - iA == iB );
23089    testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
23090    if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
23091  }else{
23092    testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
23093    testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
23094    if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
23095  }
23096  *pA += iB;
23097  return 0;
23098}
23099SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
23100  testcase( iB==SMALLEST_INT64+1 );
23101  if( iB==SMALLEST_INT64 ){
23102    testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
23103    if( (*pA)>=0 ) return 1;
23104    *pA -= iB;
23105    return 0;
23106  }else{
23107    return sqlite3AddInt64(pA, -iB);
23108  }
23109}
23110#define TWOPOWER32 (((i64)1)<<32)
23111#define TWOPOWER31 (((i64)1)<<31)
23112SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
23113  i64 iA = *pA;
23114  i64 iA1, iA0, iB1, iB0, r;
23115
23116  iA1 = iA/TWOPOWER32;
23117  iA0 = iA % TWOPOWER32;
23118  iB1 = iB/TWOPOWER32;
23119  iB0 = iB % TWOPOWER32;
23120  if( iA1==0 ){
23121    if( iB1==0 ){
23122      *pA *= iB;
23123      return 0;
23124    }
23125    r = iA0*iB1;
23126  }else if( iB1==0 ){
23127    r = iA1*iB0;
23128  }else{
23129    /* If both iA1 and iB1 are non-zero, overflow will result */
23130    return 1;
23131  }
23132  testcase( r==(-TWOPOWER31)-1 );
23133  testcase( r==(-TWOPOWER31) );
23134  testcase( r==TWOPOWER31 );
23135  testcase( r==TWOPOWER31-1 );
23136  if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
23137  r *= TWOPOWER32;
23138  if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
23139  *pA = r;
23140  return 0;
23141}
23142
23143/*
23144** Compute the absolute value of a 32-bit signed integer, of possible.  Or
23145** if the integer has a value of -2147483648, return +2147483647
23146*/
23147SQLITE_PRIVATE int sqlite3AbsInt32(int x){
23148  if( x>=0 ) return x;
23149  if( x==(int)0x80000000 ) return 0x7fffffff;
23150  return -x;
23151}
23152
23153#ifdef SQLITE_ENABLE_8_3_NAMES
23154/*
23155** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
23156** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
23157** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
23158** three characters, then shorten the suffix on z[] to be the last three
23159** characters of the original suffix.
23160**
23161** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
23162** do the suffix shortening regardless of URI parameter.
23163**
23164** Examples:
23165**
23166**     test.db-journal    =>   test.nal
23167**     test.db-wal        =>   test.wal
23168**     test.db-shm        =>   test.shm
23169**     test.db-mj7f3319fa =>   test.9fa
23170*/
23171SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
23172#if SQLITE_ENABLE_8_3_NAMES<2
23173  if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
23174#endif
23175  {
23176    int i, sz;
23177    sz = sqlite3Strlen30(z);
23178    for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
23179    if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
23180  }
23181}
23182#endif
23183
23184/*
23185** Find (an approximate) sum of two LogEst values.  This computation is
23186** not a simple "+" operator because LogEst is stored as a logarithmic
23187** value.
23188**
23189*/
23190SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
23191  static const unsigned char x[] = {
23192     10, 10,                         /* 0,1 */
23193      9, 9,                          /* 2,3 */
23194      8, 8,                          /* 4,5 */
23195      7, 7, 7,                       /* 6,7,8 */
23196      6, 6, 6,                       /* 9,10,11 */
23197      5, 5, 5,                       /* 12-14 */
23198      4, 4, 4, 4,                    /* 15-18 */
23199      3, 3, 3, 3, 3, 3,              /* 19-24 */
23200      2, 2, 2, 2, 2, 2, 2,           /* 25-31 */
23201  };
23202  if( a>=b ){
23203    if( a>b+49 ) return a;
23204    if( a>b+31 ) return a+1;
23205    return a+x[a-b];
23206  }else{
23207    if( b>a+49 ) return b;
23208    if( b>a+31 ) return b+1;
23209    return b+x[b-a];
23210  }
23211}
23212
23213/*
23214** Convert an integer into a LogEst.  In other words, compute an
23215** approximation for 10*log2(x).
23216*/
23217SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
23218  static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
23219  LogEst y = 40;
23220  if( x<8 ){
23221    if( x<2 ) return 0;
23222    while( x<8 ){  y -= 10; x <<= 1; }
23223  }else{
23224    while( x>255 ){ y += 40; x >>= 4; }
23225    while( x>15 ){  y += 10; x >>= 1; }
23226  }
23227  return a[x&7] + y - 10;
23228}
23229
23230#ifndef SQLITE_OMIT_VIRTUALTABLE
23231/*
23232** Convert a double into a LogEst
23233** In other words, compute an approximation for 10*log2(x).
23234*/
23235SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
23236  u64 a;
23237  LogEst e;
23238  assert( sizeof(x)==8 && sizeof(a)==8 );
23239  if( x<=1 ) return 0;
23240  if( x<=2000000000 ) return sqlite3LogEst((u64)x);
23241  memcpy(&a, &x, 8);
23242  e = (a>>52) - 1022;
23243  return e*10;
23244}
23245#endif /* SQLITE_OMIT_VIRTUALTABLE */
23246
23247/*
23248** Convert a LogEst into an integer.
23249*/
23250SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
23251  u64 n;
23252  if( x<10 ) return 1;
23253  n = x%10;
23254  x /= 10;
23255  if( n>=5 ) n -= 2;
23256  else if( n>=1 ) n -= 1;
23257  if( x>=3 ){
23258    return x>60 ? (u64)LARGEST_INT64 : (n+8)<<(x-3);
23259  }
23260  return (n+8)>>(3-x);
23261}
23262
23263/************** End of util.c ************************************************/
23264/************** Begin file hash.c ********************************************/
23265/*
23266** 2001 September 22
23267**
23268** The author disclaims copyright to this source code.  In place of
23269** a legal notice, here is a blessing:
23270**
23271**    May you do good and not evil.
23272**    May you find forgiveness for yourself and forgive others.
23273**    May you share freely, never taking more than you give.
23274**
23275*************************************************************************
23276** This is the implementation of generic hash-tables
23277** used in SQLite.
23278*/
23279/* #include <assert.h> */
23280
23281/* Turn bulk memory into a hash table object by initializing the
23282** fields of the Hash structure.
23283**
23284** "pNew" is a pointer to the hash table that is to be initialized.
23285*/
23286SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
23287  assert( pNew!=0 );
23288  pNew->first = 0;
23289  pNew->count = 0;
23290  pNew->htsize = 0;
23291  pNew->ht = 0;
23292}
23293
23294/* Remove all entries from a hash table.  Reclaim all memory.
23295** Call this routine to delete a hash table or to reset a hash table
23296** to the empty state.
23297*/
23298SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
23299  HashElem *elem;         /* For looping over all elements of the table */
23300
23301  assert( pH!=0 );
23302  elem = pH->first;
23303  pH->first = 0;
23304  sqlite3_free(pH->ht);
23305  pH->ht = 0;
23306  pH->htsize = 0;
23307  while( elem ){
23308    HashElem *next_elem = elem->next;
23309    sqlite3_free(elem);
23310    elem = next_elem;
23311  }
23312  pH->count = 0;
23313}
23314
23315/*
23316** The hashing function.
23317*/
23318static unsigned int strHash(const char *z, int nKey){
23319  unsigned int h = 0;
23320  assert( nKey>=0 );
23321  while( nKey > 0  ){
23322    h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
23323    nKey--;
23324  }
23325  return h;
23326}
23327
23328
23329/* Link pNew element into the hash table pH.  If pEntry!=0 then also
23330** insert pNew into the pEntry hash bucket.
23331*/
23332static void insertElement(
23333  Hash *pH,              /* The complete hash table */
23334  struct _ht *pEntry,    /* The entry into which pNew is inserted */
23335  HashElem *pNew         /* The element to be inserted */
23336){
23337  HashElem *pHead;       /* First element already in pEntry */
23338  if( pEntry ){
23339    pHead = pEntry->count ? pEntry->chain : 0;
23340    pEntry->count++;
23341    pEntry->chain = pNew;
23342  }else{
23343    pHead = 0;
23344  }
23345  if( pHead ){
23346    pNew->next = pHead;
23347    pNew->prev = pHead->prev;
23348    if( pHead->prev ){ pHead->prev->next = pNew; }
23349    else             { pH->first = pNew; }
23350    pHead->prev = pNew;
23351  }else{
23352    pNew->next = pH->first;
23353    if( pH->first ){ pH->first->prev = pNew; }
23354    pNew->prev = 0;
23355    pH->first = pNew;
23356  }
23357}
23358
23359
23360/* Resize the hash table so that it cantains "new_size" buckets.
23361**
23362** The hash table might fail to resize if sqlite3_malloc() fails or
23363** if the new size is the same as the prior size.
23364** Return TRUE if the resize occurs and false if not.
23365*/
23366static int rehash(Hash *pH, unsigned int new_size){
23367  struct _ht *new_ht;            /* The new hash table */
23368  HashElem *elem, *next_elem;    /* For looping over existing elements */
23369
23370#if SQLITE_MALLOC_SOFT_LIMIT>0
23371  if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
23372    new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
23373  }
23374  if( new_size==pH->htsize ) return 0;
23375#endif
23376
23377  /* The inability to allocates space for a larger hash table is
23378  ** a performance hit but it is not a fatal error.  So mark the
23379  ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
23380  ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
23381  ** only zeroes the requested number of bytes whereas this module will
23382  ** use the actual amount of space allocated for the hash table (which
23383  ** may be larger than the requested amount).
23384  */
23385  sqlite3BeginBenignMalloc();
23386  new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
23387  sqlite3EndBenignMalloc();
23388
23389  if( new_ht==0 ) return 0;
23390  sqlite3_free(pH->ht);
23391  pH->ht = new_ht;
23392  pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
23393  memset(new_ht, 0, new_size*sizeof(struct _ht));
23394  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
23395    unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
23396    next_elem = elem->next;
23397    insertElement(pH, &new_ht[h], elem);
23398  }
23399  return 1;
23400}
23401
23402/* This function (for internal use only) locates an element in an
23403** hash table that matches the given key.  The hash for this key has
23404** already been computed and is passed as the 4th parameter.
23405*/
23406static HashElem *findElementGivenHash(
23407  const Hash *pH,     /* The pH to be searched */
23408  const char *pKey,   /* The key we are searching for */
23409  int nKey,           /* Bytes in key (not counting zero terminator) */
23410  unsigned int h      /* The hash for this key. */
23411){
23412  HashElem *elem;                /* Used to loop thru the element list */
23413  int count;                     /* Number of elements left to test */
23414
23415  if( pH->ht ){
23416    struct _ht *pEntry = &pH->ht[h];
23417    elem = pEntry->chain;
23418    count = pEntry->count;
23419  }else{
23420    elem = pH->first;
23421    count = pH->count;
23422  }
23423  while( count-- && ALWAYS(elem) ){
23424    if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
23425      return elem;
23426    }
23427    elem = elem->next;
23428  }
23429  return 0;
23430}
23431
23432/* Remove a single entry from the hash table given a pointer to that
23433** element and a hash on the element's key.
23434*/
23435static void removeElementGivenHash(
23436  Hash *pH,         /* The pH containing "elem" */
23437  HashElem* elem,   /* The element to be removed from the pH */
23438  unsigned int h    /* Hash value for the element */
23439){
23440  struct _ht *pEntry;
23441  if( elem->prev ){
23442    elem->prev->next = elem->next;
23443  }else{
23444    pH->first = elem->next;
23445  }
23446  if( elem->next ){
23447    elem->next->prev = elem->prev;
23448  }
23449  if( pH->ht ){
23450    pEntry = &pH->ht[h];
23451    if( pEntry->chain==elem ){
23452      pEntry->chain = elem->next;
23453    }
23454    pEntry->count--;
23455    assert( pEntry->count>=0 );
23456  }
23457  sqlite3_free( elem );
23458  pH->count--;
23459  if( pH->count==0 ){
23460    assert( pH->first==0 );
23461    assert( pH->count==0 );
23462    sqlite3HashClear(pH);
23463  }
23464}
23465
23466/* Attempt to locate an element of the hash table pH with a key
23467** that matches pKey,nKey.  Return the data for this element if it is
23468** found, or NULL if there is no match.
23469*/
23470SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
23471  HashElem *elem;    /* The element that matches key */
23472  unsigned int h;    /* A hash on key */
23473
23474  assert( pH!=0 );
23475  assert( pKey!=0 );
23476  assert( nKey>=0 );
23477  if( pH->ht ){
23478    h = strHash(pKey, nKey) % pH->htsize;
23479  }else{
23480    h = 0;
23481  }
23482  elem = findElementGivenHash(pH, pKey, nKey, h);
23483  return elem ? elem->data : 0;
23484}
23485
23486/* Insert an element into the hash table pH.  The key is pKey,nKey
23487** and the data is "data".
23488**
23489** If no element exists with a matching key, then a new
23490** element is created and NULL is returned.
23491**
23492** If another element already exists with the same key, then the
23493** new data replaces the old data and the old data is returned.
23494** The key is not copied in this instance.  If a malloc fails, then
23495** the new data is returned and the hash table is unchanged.
23496**
23497** If the "data" parameter to this function is NULL, then the
23498** element corresponding to "key" is removed from the hash table.
23499*/
23500SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
23501  unsigned int h;       /* the hash of the key modulo hash table size */
23502  HashElem *elem;       /* Used to loop thru the element list */
23503  HashElem *new_elem;   /* New element added to the pH */
23504
23505  assert( pH!=0 );
23506  assert( pKey!=0 );
23507  assert( nKey>=0 );
23508  if( pH->htsize ){
23509    h = strHash(pKey, nKey) % pH->htsize;
23510  }else{
23511    h = 0;
23512  }
23513  elem = findElementGivenHash(pH,pKey,nKey,h);
23514  if( elem ){
23515    void *old_data = elem->data;
23516    if( data==0 ){
23517      removeElementGivenHash(pH,elem,h);
23518    }else{
23519      elem->data = data;
23520      elem->pKey = pKey;
23521      assert(nKey==elem->nKey);
23522    }
23523    return old_data;
23524  }
23525  if( data==0 ) return 0;
23526  new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
23527  if( new_elem==0 ) return data;
23528  new_elem->pKey = pKey;
23529  new_elem->nKey = nKey;
23530  new_elem->data = data;
23531  pH->count++;
23532  if( pH->count>=10 && pH->count > 2*pH->htsize ){
23533    if( rehash(pH, pH->count*2) ){
23534      assert( pH->htsize>0 );
23535      h = strHash(pKey, nKey) % pH->htsize;
23536    }
23537  }
23538  if( pH->ht ){
23539    insertElement(pH, &pH->ht[h], new_elem);
23540  }else{
23541    insertElement(pH, 0, new_elem);
23542  }
23543  return 0;
23544}
23545
23546/************** End of hash.c ************************************************/
23547/************** Begin file opcodes.c *****************************************/
23548/* Automatically generated.  Do not edit */
23549/* See the mkopcodec.awk script for details. */
23550#if !defined(SQLITE_OMIT_EXPLAIN) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
23551#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
23552# define OpHelp(X) "\0" X
23553#else
23554# define OpHelp(X)
23555#endif
23556SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
23557 static const char *const azName[] = { "?",
23558     /*   1 */ "Function"         OpHelp("r[P3]=func(r[P2@P5])"),
23559     /*   2 */ "Savepoint"        OpHelp(""),
23560     /*   3 */ "AutoCommit"       OpHelp(""),
23561     /*   4 */ "Transaction"      OpHelp(""),
23562     /*   5 */ "SorterNext"       OpHelp(""),
23563     /*   6 */ "PrevIfOpen"       OpHelp(""),
23564     /*   7 */ "NextIfOpen"       OpHelp(""),
23565     /*   8 */ "Prev"             OpHelp(""),
23566     /*   9 */ "Next"             OpHelp(""),
23567     /*  10 */ "AggStep"          OpHelp("accum=r[P3] step(r[P2@P5])"),
23568     /*  11 */ "Checkpoint"       OpHelp(""),
23569     /*  12 */ "JournalMode"      OpHelp(""),
23570     /*  13 */ "Vacuum"           OpHelp(""),
23571     /*  14 */ "VFilter"          OpHelp("iplan=r[P3] zplan='P4'"),
23572     /*  15 */ "VUpdate"          OpHelp("data=r[P3@P2]"),
23573     /*  16 */ "Goto"             OpHelp(""),
23574     /*  17 */ "Gosub"            OpHelp(""),
23575     /*  18 */ "Return"           OpHelp(""),
23576     /*  19 */ "Not"              OpHelp("r[P2]= !r[P1]"),
23577     /*  20 */ "InitCoroutine"    OpHelp(""),
23578     /*  21 */ "EndCoroutine"     OpHelp(""),
23579     /*  22 */ "Yield"            OpHelp(""),
23580     /*  23 */ "HaltIfNull"       OpHelp("if r[P3]=null halt"),
23581     /*  24 */ "Halt"             OpHelp(""),
23582     /*  25 */ "Integer"          OpHelp("r[P2]=P1"),
23583     /*  26 */ "Int64"            OpHelp("r[P2]=P4"),
23584     /*  27 */ "String"           OpHelp("r[P2]='P4' (len=P1)"),
23585     /*  28 */ "Null"             OpHelp("r[P2..P3]=NULL"),
23586     /*  29 */ "SoftNull"         OpHelp("r[P1]=NULL"),
23587     /*  30 */ "Blob"             OpHelp("r[P2]=P4 (len=P1)"),
23588     /*  31 */ "Variable"         OpHelp("r[P2]=parameter(P1,P4)"),
23589     /*  32 */ "Move"             OpHelp("r[P2@P3]=r[P1@P3]"),
23590     /*  33 */ "Copy"             OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
23591     /*  34 */ "SCopy"            OpHelp("r[P2]=r[P1]"),
23592     /*  35 */ "ResultRow"        OpHelp("output=r[P1@P2]"),
23593     /*  36 */ "CollSeq"          OpHelp(""),
23594     /*  37 */ "AddImm"           OpHelp("r[P1]=r[P1]+P2"),
23595     /*  38 */ "MustBeInt"        OpHelp(""),
23596     /*  39 */ "RealAffinity"     OpHelp(""),
23597     /*  40 */ "Permutation"      OpHelp(""),
23598     /*  41 */ "Compare"          OpHelp("r[P1@P3] <-> r[P2@P3]"),
23599     /*  42 */ "Jump"             OpHelp(""),
23600     /*  43 */ "Once"             OpHelp(""),
23601     /*  44 */ "If"               OpHelp(""),
23602     /*  45 */ "IfNot"            OpHelp(""),
23603     /*  46 */ "Column"           OpHelp("r[P3]=PX"),
23604     /*  47 */ "Affinity"         OpHelp("affinity(r[P1@P2])"),
23605     /*  48 */ "MakeRecord"       OpHelp("r[P3]=mkrec(r[P1@P2])"),
23606     /*  49 */ "Count"            OpHelp("r[P2]=count()"),
23607     /*  50 */ "ReadCookie"       OpHelp(""),
23608     /*  51 */ "SetCookie"        OpHelp(""),
23609     /*  52 */ "OpenRead"         OpHelp("root=P2 iDb=P3"),
23610     /*  53 */ "OpenWrite"        OpHelp("root=P2 iDb=P3"),
23611     /*  54 */ "OpenAutoindex"    OpHelp("nColumn=P2"),
23612     /*  55 */ "OpenEphemeral"    OpHelp("nColumn=P2"),
23613     /*  56 */ "SorterOpen"       OpHelp(""),
23614     /*  57 */ "OpenPseudo"       OpHelp("P3 columns in r[P2]"),
23615     /*  58 */ "Close"            OpHelp(""),
23616     /*  59 */ "SeekLT"           OpHelp(""),
23617     /*  60 */ "SeekLE"           OpHelp(""),
23618     /*  61 */ "SeekGE"           OpHelp(""),
23619     /*  62 */ "SeekGT"           OpHelp(""),
23620     /*  63 */ "Seek"             OpHelp("intkey=r[P2]"),
23621     /*  64 */ "NoConflict"       OpHelp("key=r[P3@P4]"),
23622     /*  65 */ "NotFound"         OpHelp("key=r[P3@P4]"),
23623     /*  66 */ "Found"            OpHelp("key=r[P3@P4]"),
23624     /*  67 */ "NotExists"        OpHelp("intkey=r[P3]"),
23625     /*  68 */ "Sequence"         OpHelp("r[P2]=cursor[P1].ctr++"),
23626     /*  69 */ "NewRowid"         OpHelp("r[P2]=rowid"),
23627     /*  70 */ "Insert"           OpHelp("intkey=r[P3] data=r[P2]"),
23628     /*  71 */ "Or"               OpHelp("r[P3]=(r[P1] || r[P2])"),
23629     /*  72 */ "And"              OpHelp("r[P3]=(r[P1] && r[P2])"),
23630     /*  73 */ "InsertInt"        OpHelp("intkey=P3 data=r[P2]"),
23631     /*  74 */ "Delete"           OpHelp(""),
23632     /*  75 */ "ResetCount"       OpHelp(""),
23633     /*  76 */ "IsNull"           OpHelp("if r[P1]==NULL goto P2"),
23634     /*  77 */ "NotNull"          OpHelp("if r[P1]!=NULL goto P2"),
23635     /*  78 */ "Ne"               OpHelp("if r[P1]!=r[P3] goto P2"),
23636     /*  79 */ "Eq"               OpHelp("if r[P1]==r[P3] goto P2"),
23637     /*  80 */ "Gt"               OpHelp("if r[P1]>r[P3] goto P2"),
23638     /*  81 */ "Le"               OpHelp("if r[P1]<=r[P3] goto P2"),
23639     /*  82 */ "Lt"               OpHelp("if r[P1]<r[P3] goto P2"),
23640     /*  83 */ "Ge"               OpHelp("if r[P1]>=r[P3] goto P2"),
23641     /*  84 */ "SorterCompare"    OpHelp("if key(P1)!=rtrim(r[P3],P4) goto P2"),
23642     /*  85 */ "BitAnd"           OpHelp("r[P3]=r[P1]&r[P2]"),
23643     /*  86 */ "BitOr"            OpHelp("r[P3]=r[P1]|r[P2]"),
23644     /*  87 */ "ShiftLeft"        OpHelp("r[P3]=r[P2]<<r[P1]"),
23645     /*  88 */ "ShiftRight"       OpHelp("r[P3]=r[P2]>>r[P1]"),
23646     /*  89 */ "Add"              OpHelp("r[P3]=r[P1]+r[P2]"),
23647     /*  90 */ "Subtract"         OpHelp("r[P3]=r[P2]-r[P1]"),
23648     /*  91 */ "Multiply"         OpHelp("r[P3]=r[P1]*r[P2]"),
23649     /*  92 */ "Divide"           OpHelp("r[P3]=r[P2]/r[P1]"),
23650     /*  93 */ "Remainder"        OpHelp("r[P3]=r[P2]%r[P1]"),
23651     /*  94 */ "Concat"           OpHelp("r[P3]=r[P2]+r[P1]"),
23652     /*  95 */ "SorterData"       OpHelp("r[P2]=data"),
23653     /*  96 */ "BitNot"           OpHelp("r[P1]= ~r[P1]"),
23654     /*  97 */ "String8"          OpHelp("r[P2]='P4'"),
23655     /*  98 */ "RowKey"           OpHelp("r[P2]=key"),
23656     /*  99 */ "RowData"          OpHelp("r[P2]=data"),
23657     /* 100 */ "Rowid"            OpHelp("r[P2]=rowid"),
23658     /* 101 */ "NullRow"          OpHelp(""),
23659     /* 102 */ "Last"             OpHelp(""),
23660     /* 103 */ "SorterSort"       OpHelp(""),
23661     /* 104 */ "Sort"             OpHelp(""),
23662     /* 105 */ "Rewind"           OpHelp(""),
23663     /* 106 */ "SorterInsert"     OpHelp(""),
23664     /* 107 */ "IdxInsert"        OpHelp("key=r[P2]"),
23665     /* 108 */ "IdxDelete"        OpHelp("key=r[P2@P3]"),
23666     /* 109 */ "IdxRowid"         OpHelp("r[P2]=rowid"),
23667     /* 110 */ "IdxLE"            OpHelp("key=r[P3@P4]"),
23668     /* 111 */ "IdxGT"            OpHelp("key=r[P3@P4]"),
23669     /* 112 */ "IdxLT"            OpHelp("key=r[P3@P4]"),
23670     /* 113 */ "IdxGE"            OpHelp("key=r[P3@P4]"),
23671     /* 114 */ "Destroy"          OpHelp(""),
23672     /* 115 */ "Clear"            OpHelp(""),
23673     /* 116 */ "ResetSorter"      OpHelp(""),
23674     /* 117 */ "CreateIndex"      OpHelp("r[P2]=root iDb=P1"),
23675     /* 118 */ "CreateTable"      OpHelp("r[P2]=root iDb=P1"),
23676     /* 119 */ "ParseSchema"      OpHelp(""),
23677     /* 120 */ "LoadAnalysis"     OpHelp(""),
23678     /* 121 */ "DropTable"        OpHelp(""),
23679     /* 122 */ "DropIndex"        OpHelp(""),
23680     /* 123 */ "DropTrigger"      OpHelp(""),
23681     /* 124 */ "IntegrityCk"      OpHelp(""),
23682     /* 125 */ "RowSetAdd"        OpHelp("rowset(P1)=r[P2]"),
23683     /* 126 */ "RowSetRead"       OpHelp("r[P3]=rowset(P1)"),
23684     /* 127 */ "RowSetTest"       OpHelp("if r[P3] in rowset(P1) goto P2"),
23685     /* 128 */ "Program"          OpHelp(""),
23686     /* 129 */ "Param"            OpHelp(""),
23687     /* 130 */ "FkCounter"        OpHelp("fkctr[P1]+=P2"),
23688     /* 131 */ "FkIfZero"         OpHelp("if fkctr[P1]==0 goto P2"),
23689     /* 132 */ "MemMax"           OpHelp("r[P1]=max(r[P1],r[P2])"),
23690     /* 133 */ "Real"             OpHelp("r[P2]=P4"),
23691     /* 134 */ "IfPos"            OpHelp("if r[P1]>0 goto P2"),
23692     /* 135 */ "IfNeg"            OpHelp("if r[P1]<0 goto P2"),
23693     /* 136 */ "IfZero"           OpHelp("r[P1]+=P3, if r[P1]==0 goto P2"),
23694     /* 137 */ "AggFinal"         OpHelp("accum=r[P1] N=P2"),
23695     /* 138 */ "IncrVacuum"       OpHelp(""),
23696     /* 139 */ "Expire"           OpHelp(""),
23697     /* 140 */ "TableLock"        OpHelp("iDb=P1 root=P2 write=P3"),
23698     /* 141 */ "VBegin"           OpHelp(""),
23699     /* 142 */ "VCreate"          OpHelp(""),
23700     /* 143 */ "ToText"           OpHelp(""),
23701     /* 144 */ "ToBlob"           OpHelp(""),
23702     /* 145 */ "ToNumeric"        OpHelp(""),
23703     /* 146 */ "ToInt"            OpHelp(""),
23704     /* 147 */ "ToReal"           OpHelp(""),
23705     /* 148 */ "VDestroy"         OpHelp(""),
23706     /* 149 */ "VOpen"            OpHelp(""),
23707     /* 150 */ "VColumn"          OpHelp("r[P3]=vcolumn(P2)"),
23708     /* 151 */ "VNext"            OpHelp(""),
23709     /* 152 */ "VRename"          OpHelp(""),
23710     /* 153 */ "Pagecount"        OpHelp(""),
23711     /* 154 */ "MaxPgcnt"         OpHelp(""),
23712     /* 155 */ "Init"             OpHelp("Start at P2"),
23713     /* 156 */ "Noop"             OpHelp(""),
23714     /* 157 */ "Explain"          OpHelp(""),
23715  };
23716  return azName[i];
23717}
23718#endif
23719
23720/************** End of opcodes.c *********************************************/
23721/************** Begin file os_unix.c *****************************************/
23722/*
23723** 2004 May 22
23724**
23725** The author disclaims copyright to this source code.  In place of
23726** a legal notice, here is a blessing:
23727**
23728**    May you do good and not evil.
23729**    May you find forgiveness for yourself and forgive others.
23730**    May you share freely, never taking more than you give.
23731**
23732******************************************************************************
23733**
23734** This file contains the VFS implementation for unix-like operating systems
23735** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
23736**
23737** There are actually several different VFS implementations in this file.
23738** The differences are in the way that file locking is done.  The default
23739** implementation uses Posix Advisory Locks.  Alternative implementations
23740** use flock(), dot-files, various proprietary locking schemas, or simply
23741** skip locking all together.
23742**
23743** This source file is organized into divisions where the logic for various
23744** subfunctions is contained within the appropriate division.  PLEASE
23745** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
23746** in the correct division and should be clearly labeled.
23747**
23748** The layout of divisions is as follows:
23749**
23750**   *  General-purpose declarations and utility functions.
23751**   *  Unique file ID logic used by VxWorks.
23752**   *  Various locking primitive implementations (all except proxy locking):
23753**      + for Posix Advisory Locks
23754**      + for no-op locks
23755**      + for dot-file locks
23756**      + for flock() locking
23757**      + for named semaphore locks (VxWorks only)
23758**      + for AFP filesystem locks (MacOSX only)
23759**   *  sqlite3_file methods not associated with locking.
23760**   *  Definitions of sqlite3_io_methods objects for all locking
23761**      methods plus "finder" functions for each locking method.
23762**   *  sqlite3_vfs method implementations.
23763**   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
23764**   *  Definitions of sqlite3_vfs objects for all locking methods
23765**      plus implementations of sqlite3_os_init() and sqlite3_os_end().
23766*/
23767#if SQLITE_OS_UNIX              /* This file is used on unix only */
23768
23769/*
23770** There are various methods for file locking used for concurrency
23771** control:
23772**
23773**   1. POSIX locking (the default),
23774**   2. No locking,
23775**   3. Dot-file locking,
23776**   4. flock() locking,
23777**   5. AFP locking (OSX only),
23778**   6. Named POSIX semaphores (VXWorks only),
23779**   7. proxy locking. (OSX only)
23780**
23781** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
23782** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
23783** selection of the appropriate locking style based on the filesystem
23784** where the database is located.
23785*/
23786#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
23787#  if defined(__APPLE__)
23788#    define SQLITE_ENABLE_LOCKING_STYLE 1
23789#  else
23790#    define SQLITE_ENABLE_LOCKING_STYLE 0
23791#  endif
23792#endif
23793
23794/*
23795** Define the OS_VXWORKS pre-processor macro to 1 if building on
23796** vxworks, or 0 otherwise.
23797*/
23798#ifndef OS_VXWORKS
23799#  if defined(__RTP__) || defined(_WRS_KERNEL)
23800#    define OS_VXWORKS 1
23801#  else
23802#    define OS_VXWORKS 0
23803#  endif
23804#endif
23805
23806/*
23807** standard include files.
23808*/
23809#include <sys/types.h>
23810#include <sys/stat.h>
23811#include <fcntl.h>
23812#include <unistd.h>
23813/* #include <time.h> */
23814#include <sys/time.h>
23815#include <errno.h>
23816#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
23817#include <sys/mman.h>
23818#endif
23819
23820
23821#if SQLITE_ENABLE_LOCKING_STYLE
23822# include <sys/ioctl.h>
23823# if OS_VXWORKS
23824#  include <semaphore.h>
23825#  include <limits.h>
23826# else
23827#  include <sys/file.h>
23828#  include <sys/param.h>
23829# endif
23830#endif /* SQLITE_ENABLE_LOCKING_STYLE */
23831
23832#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
23833# include <sys/mount.h>
23834#endif
23835
23836#ifdef HAVE_UTIME
23837# include <utime.h>
23838#endif
23839
23840/*
23841** Allowed values of unixFile.fsFlags
23842*/
23843#define SQLITE_FSFLAGS_IS_MSDOS     0x1
23844
23845/*
23846** If we are to be thread-safe, include the pthreads header and define
23847** the SQLITE_UNIX_THREADS macro.
23848*/
23849#if SQLITE_THREADSAFE
23850/* # include <pthread.h> */
23851# define SQLITE_UNIX_THREADS 1
23852#endif
23853
23854/*
23855** Default permissions when creating a new file
23856*/
23857#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
23858# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
23859#endif
23860
23861/*
23862** Default permissions when creating auto proxy dir
23863*/
23864#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
23865# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
23866#endif
23867
23868/*
23869** Maximum supported path-length.
23870*/
23871#define MAX_PATHNAME 512
23872
23873/*
23874** Only set the lastErrno if the error code is a real error and not
23875** a normal expected return code of SQLITE_BUSY or SQLITE_OK
23876*/
23877#define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
23878
23879/* Forward references */
23880typedef struct unixShm unixShm;               /* Connection shared memory */
23881typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
23882typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
23883typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
23884
23885/*
23886** Sometimes, after a file handle is closed by SQLite, the file descriptor
23887** cannot be closed immediately. In these cases, instances of the following
23888** structure are used to store the file descriptor while waiting for an
23889** opportunity to either close or reuse it.
23890*/
23891struct UnixUnusedFd {
23892  int fd;                   /* File descriptor to close */
23893  int flags;                /* Flags this file descriptor was opened with */
23894  UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
23895};
23896
23897/*
23898** The unixFile structure is subclass of sqlite3_file specific to the unix
23899** VFS implementations.
23900*/
23901typedef struct unixFile unixFile;
23902struct unixFile {
23903  sqlite3_io_methods const *pMethod;  /* Always the first entry */
23904  sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */
23905  unixInodeInfo *pInode;              /* Info about locks on this inode */
23906  int h;                              /* The file descriptor */
23907  unsigned char eFileLock;            /* The type of lock held on this fd */
23908  unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */
23909  int lastErrno;                      /* The unix errno from last I/O error */
23910  void *lockingContext;               /* Locking style specific state */
23911  UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
23912  const char *zPath;                  /* Name of the file */
23913  unixShm *pShm;                      /* Shared memory segment information */
23914  int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
23915#if SQLITE_MAX_MMAP_SIZE>0
23916  int nFetchOut;                      /* Number of outstanding xFetch refs */
23917  sqlite3_int64 mmapSize;             /* Usable size of mapping at pMapRegion */
23918  sqlite3_int64 mmapSizeActual;       /* Actual size of mapping at pMapRegion */
23919  sqlite3_int64 mmapSizeMax;          /* Configured FCNTL_MMAP_SIZE value */
23920  void *pMapRegion;                   /* Memory mapped region */
23921#endif
23922#ifdef __QNXNTO__
23923  int sectorSize;                     /* Device sector size */
23924  int deviceCharacteristics;          /* Precomputed device characteristics */
23925#endif
23926#if SQLITE_ENABLE_LOCKING_STYLE
23927  int openFlags;                      /* The flags specified at open() */
23928#endif
23929#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
23930  unsigned fsFlags;                   /* cached details from statfs() */
23931#endif
23932#if OS_VXWORKS
23933  struct vxworksFileId *pId;          /* Unique file ID */
23934#endif
23935#ifdef SQLITE_DEBUG
23936  /* The next group of variables are used to track whether or not the
23937  ** transaction counter in bytes 24-27 of database files are updated
23938  ** whenever any part of the database changes.  An assertion fault will
23939  ** occur if a file is updated without also updating the transaction
23940  ** counter.  This test is made to avoid new problems similar to the
23941  ** one described by ticket #3584.
23942  */
23943  unsigned char transCntrChng;   /* True if the transaction counter changed */
23944  unsigned char dbUpdate;        /* True if any part of database file changed */
23945  unsigned char inNormalWrite;   /* True if in a normal write operation */
23946
23947#endif
23948
23949#ifdef SQLITE_TEST
23950  /* In test mode, increase the size of this structure a bit so that
23951  ** it is larger than the struct CrashFile defined in test6.c.
23952  */
23953  char aPadding[32];
23954#endif
23955};
23956
23957/* This variable holds the process id (pid) from when the xRandomness()
23958** method was called.  If xOpen() is called from a different process id,
23959** indicating that a fork() has occurred, the PRNG will be reset.
23960*/
23961static int randomnessPid = 0;
23962
23963/*
23964** Allowed values for the unixFile.ctrlFlags bitmask:
23965*/
23966#define UNIXFILE_EXCL        0x01     /* Connections from one process only */
23967#define UNIXFILE_RDONLY      0x02     /* Connection is read only */
23968#define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
23969#ifndef SQLITE_DISABLE_DIRSYNC
23970# define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
23971#else
23972# define UNIXFILE_DIRSYNC    0x00
23973#endif
23974#define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
23975#define UNIXFILE_DELETE      0x20     /* Delete on close */
23976#define UNIXFILE_URI         0x40     /* Filename might have query parameters */
23977#define UNIXFILE_NOLOCK      0x80     /* Do no file locking */
23978#define UNIXFILE_WARNED    0x0100     /* verifyDbFile() warnings have been issued */
23979
23980/*
23981** Include code that is common to all os_*.c files
23982*/
23983/************** Include os_common.h in the middle of os_unix.c ***************/
23984/************** Begin file os_common.h ***************************************/
23985/*
23986** 2004 May 22
23987**
23988** The author disclaims copyright to this source code.  In place of
23989** a legal notice, here is a blessing:
23990**
23991**    May you do good and not evil.
23992**    May you find forgiveness for yourself and forgive others.
23993**    May you share freely, never taking more than you give.
23994**
23995******************************************************************************
23996**
23997** This file contains macros and a little bit of code that is common to
23998** all of the platform-specific files (os_*.c) and is #included into those
23999** files.
24000**
24001** This file should be #included by the os_*.c files only.  It is not a
24002** general purpose header file.
24003*/
24004#ifndef _OS_COMMON_H_
24005#define _OS_COMMON_H_
24006
24007/*
24008** At least two bugs have slipped in because we changed the MEMORY_DEBUG
24009** macro to SQLITE_DEBUG and some older makefiles have not yet made the
24010** switch.  The following code should catch this problem at compile-time.
24011*/
24012#ifdef MEMORY_DEBUG
24013# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
24014#endif
24015
24016#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
24017# ifndef SQLITE_DEBUG_OS_TRACE
24018#   define SQLITE_DEBUG_OS_TRACE 0
24019# endif
24020  int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
24021# define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
24022#else
24023# define OSTRACE(X)
24024#endif
24025
24026/*
24027** Macros for performance tracing.  Normally turned off.  Only works
24028** on i486 hardware.
24029*/
24030#ifdef SQLITE_PERFORMANCE_TRACE
24031
24032/*
24033** hwtime.h contains inline assembler code for implementing
24034** high-performance timing routines.
24035*/
24036/************** Include hwtime.h in the middle of os_common.h ****************/
24037/************** Begin file hwtime.h ******************************************/
24038/*
24039** 2008 May 27
24040**
24041** The author disclaims copyright to this source code.  In place of
24042** a legal notice, here is a blessing:
24043**
24044**    May you do good and not evil.
24045**    May you find forgiveness for yourself and forgive others.
24046**    May you share freely, never taking more than you give.
24047**
24048******************************************************************************
24049**
24050** This file contains inline asm code for retrieving "high-performance"
24051** counters for x86 class CPUs.
24052*/
24053#ifndef _HWTIME_H_
24054#define _HWTIME_H_
24055
24056/*
24057** The following routine only works on pentium-class (or newer) processors.
24058** It uses the RDTSC opcode to read the cycle count value out of the
24059** processor and returns that value.  This can be used for high-res
24060** profiling.
24061*/
24062#if (defined(__GNUC__) || defined(_MSC_VER)) && \
24063      (defined(i386) || defined(__i386__) || defined(_M_IX86))
24064
24065  #if defined(__GNUC__)
24066
24067  __inline__ sqlite_uint64 sqlite3Hwtime(void){
24068     unsigned int lo, hi;
24069     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
24070     return (sqlite_uint64)hi << 32 | lo;
24071  }
24072
24073  #elif defined(_MSC_VER)
24074
24075  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
24076     __asm {
24077        rdtsc
24078        ret       ; return value at EDX:EAX
24079     }
24080  }
24081
24082  #endif
24083
24084#elif (defined(__GNUC__) && defined(__x86_64__))
24085
24086  __inline__ sqlite_uint64 sqlite3Hwtime(void){
24087      unsigned long val;
24088      __asm__ __volatile__ ("rdtsc" : "=A" (val));
24089      return val;
24090  }
24091
24092#elif (defined(__GNUC__) && defined(__ppc__))
24093
24094  __inline__ sqlite_uint64 sqlite3Hwtime(void){
24095      unsigned long long retval;
24096      unsigned long junk;
24097      __asm__ __volatile__ ("\n\
24098          1:      mftbu   %1\n\
24099                  mftb    %L0\n\
24100                  mftbu   %0\n\
24101                  cmpw    %0,%1\n\
24102                  bne     1b"
24103                  : "=r" (retval), "=r" (junk));
24104      return retval;
24105  }
24106
24107#else
24108
24109  #error Need implementation of sqlite3Hwtime() for your platform.
24110
24111  /*
24112  ** To compile without implementing sqlite3Hwtime() for your platform,
24113  ** you can remove the above #error and use the following
24114  ** stub function.  You will lose timing support for many
24115  ** of the debugging and testing utilities, but it should at
24116  ** least compile and run.
24117  */
24118SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
24119
24120#endif
24121
24122#endif /* !defined(_HWTIME_H_) */
24123
24124/************** End of hwtime.h **********************************************/
24125/************** Continuing where we left off in os_common.h ******************/
24126
24127static sqlite_uint64 g_start;
24128static sqlite_uint64 g_elapsed;
24129#define TIMER_START       g_start=sqlite3Hwtime()
24130#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
24131#define TIMER_ELAPSED     g_elapsed
24132#else
24133#define TIMER_START
24134#define TIMER_END
24135#define TIMER_ELAPSED     ((sqlite_uint64)0)
24136#endif
24137
24138/*
24139** If we compile with the SQLITE_TEST macro set, then the following block
24140** of code will give us the ability to simulate a disk I/O error.  This
24141** is used for testing the I/O recovery logic.
24142*/
24143#ifdef SQLITE_TEST
24144SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
24145SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
24146SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
24147SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
24148SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
24149SQLITE_API int sqlite3_diskfull_pending = 0;
24150SQLITE_API int sqlite3_diskfull = 0;
24151#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
24152#define SimulateIOError(CODE)  \
24153  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
24154       || sqlite3_io_error_pending-- == 1 )  \
24155              { local_ioerr(); CODE; }
24156static void local_ioerr(){
24157  IOTRACE(("IOERR\n"));
24158  sqlite3_io_error_hit++;
24159  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
24160}
24161#define SimulateDiskfullError(CODE) \
24162   if( sqlite3_diskfull_pending ){ \
24163     if( sqlite3_diskfull_pending == 1 ){ \
24164       local_ioerr(); \
24165       sqlite3_diskfull = 1; \
24166       sqlite3_io_error_hit = 1; \
24167       CODE; \
24168     }else{ \
24169       sqlite3_diskfull_pending--; \
24170     } \
24171   }
24172#else
24173#define SimulateIOErrorBenign(X)
24174#define SimulateIOError(A)
24175#define SimulateDiskfullError(A)
24176#endif
24177
24178/*
24179** When testing, keep a count of the number of open files.
24180*/
24181#ifdef SQLITE_TEST
24182SQLITE_API int sqlite3_open_file_count = 0;
24183#define OpenCounter(X)  sqlite3_open_file_count+=(X)
24184#else
24185#define OpenCounter(X)
24186#endif
24187
24188#endif /* !defined(_OS_COMMON_H_) */
24189
24190/************** End of os_common.h *******************************************/
24191/************** Continuing where we left off in os_unix.c ********************/
24192
24193/*
24194** Define various macros that are missing from some systems.
24195*/
24196#ifndef O_LARGEFILE
24197# define O_LARGEFILE 0
24198#endif
24199#ifdef SQLITE_DISABLE_LFS
24200# undef O_LARGEFILE
24201# define O_LARGEFILE 0
24202#endif
24203#ifndef O_NOFOLLOW
24204# define O_NOFOLLOW 0
24205#endif
24206#ifndef O_BINARY
24207# define O_BINARY 0
24208#endif
24209
24210/*
24211** The threadid macro resolves to the thread-id or to 0.  Used for
24212** testing and debugging only.
24213*/
24214#if SQLITE_THREADSAFE
24215#define threadid pthread_self()
24216#else
24217#define threadid 0
24218#endif
24219
24220/*
24221** HAVE_MREMAP defaults to true on Linux and false everywhere else.
24222*/
24223#if !defined(HAVE_MREMAP)
24224# if defined(__linux__) && defined(_GNU_SOURCE)
24225#  define HAVE_MREMAP 1
24226# else
24227#  define HAVE_MREMAP 0
24228# endif
24229#endif
24230
24231/*
24232** Different Unix systems declare open() in different ways.  Same use
24233** open(const char*,int,mode_t).  Others use open(const char*,int,...).
24234** The difference is important when using a pointer to the function.
24235**
24236** The safest way to deal with the problem is to always use this wrapper
24237** which always has the same well-defined interface.
24238*/
24239static int posixOpen(const char *zFile, int flags, int mode){
24240  return open(zFile, flags, mode);
24241}
24242
24243/*
24244** On some systems, calls to fchown() will trigger a message in a security
24245** log if they come from non-root processes.  So avoid calling fchown() if
24246** we are not running as root.
24247*/
24248static int posixFchown(int fd, uid_t uid, gid_t gid){
24249  return geteuid() ? 0 : fchown(fd,uid,gid);
24250}
24251
24252/* Forward reference */
24253static int openDirectory(const char*, int*);
24254static int unixGetpagesize(void);
24255
24256/*
24257** Many system calls are accessed through pointer-to-functions so that
24258** they may be overridden at runtime to facilitate fault injection during
24259** testing and sandboxing.  The following array holds the names and pointers
24260** to all overrideable system calls.
24261*/
24262static struct unix_syscall {
24263  const char *zName;            /* Name of the system call */
24264  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
24265  sqlite3_syscall_ptr pDefault; /* Default value */
24266} aSyscall[] = {
24267  { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
24268#define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
24269
24270  { "close",        (sqlite3_syscall_ptr)close,      0  },
24271#define osClose     ((int(*)(int))aSyscall[1].pCurrent)
24272
24273  { "access",       (sqlite3_syscall_ptr)access,     0  },
24274#define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
24275
24276  { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
24277#define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
24278
24279  { "stat",         (sqlite3_syscall_ptr)stat,       0  },
24280#define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
24281
24282/*
24283** The DJGPP compiler environment looks mostly like Unix, but it
24284** lacks the fcntl() system call.  So redefine fcntl() to be something
24285** that always succeeds.  This means that locking does not occur under
24286** DJGPP.  But it is DOS - what did you expect?
24287*/
24288#ifdef __DJGPP__
24289  { "fstat",        0,                 0  },
24290#define osFstat(a,b,c)    0
24291#else
24292  { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
24293#define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
24294#endif
24295
24296  { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
24297#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
24298
24299  { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
24300#define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
24301
24302  { "read",         (sqlite3_syscall_ptr)read,       0  },
24303#define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
24304
24305#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
24306  { "pread",        (sqlite3_syscall_ptr)pread,      0  },
24307#else
24308  { "pread",        (sqlite3_syscall_ptr)0,          0  },
24309#endif
24310#define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
24311
24312#if defined(USE_PREAD64)
24313  { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
24314#else
24315  { "pread64",      (sqlite3_syscall_ptr)0,          0  },
24316#endif
24317#define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
24318
24319  { "write",        (sqlite3_syscall_ptr)write,      0  },
24320#define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
24321
24322#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
24323  { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
24324#else
24325  { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
24326#endif
24327#define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
24328                    aSyscall[12].pCurrent)
24329
24330#if defined(USE_PREAD64)
24331  { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
24332#else
24333  { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
24334#endif
24335#define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off_t))\
24336                    aSyscall[13].pCurrent)
24337
24338  { "fchmod",       (sqlite3_syscall_ptr)fchmod,     0  },
24339#define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
24340
24341#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
24342  { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
24343#else
24344  { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
24345#endif
24346#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
24347
24348  { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
24349#define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
24350
24351  { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
24352#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
24353
24354  { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
24355#define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
24356
24357  { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
24358#define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
24359
24360  { "fchown",       (sqlite3_syscall_ptr)posixFchown,     0 },
24361#define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
24362
24363#if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
24364  { "mmap",       (sqlite3_syscall_ptr)mmap,     0 },
24365#define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
24366
24367  { "munmap",       (sqlite3_syscall_ptr)munmap,          0 },
24368#define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
24369
24370#if HAVE_MREMAP
24371  { "mremap",       (sqlite3_syscall_ptr)mremap,          0 },
24372#else
24373  { "mremap",       (sqlite3_syscall_ptr)0,               0 },
24374#endif
24375#define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
24376#endif
24377
24378  { "getpagesize",  (sqlite3_syscall_ptr)unixGetpagesize, 0 },
24379#define osGetpagesize ((int(*)(void))aSyscall[24].pCurrent)
24380
24381}; /* End of the overrideable system calls */
24382
24383/*
24384** This is the xSetSystemCall() method of sqlite3_vfs for all of the
24385** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
24386** system call pointer, or SQLITE_NOTFOUND if there is no configurable
24387** system call named zName.
24388*/
24389static int unixSetSystemCall(
24390  sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
24391  const char *zName,            /* Name of system call to override */
24392  sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
24393){
24394  unsigned int i;
24395  int rc = SQLITE_NOTFOUND;
24396
24397  UNUSED_PARAMETER(pNotUsed);
24398  if( zName==0 ){
24399    /* If no zName is given, restore all system calls to their default
24400    ** settings and return NULL
24401    */
24402    rc = SQLITE_OK;
24403    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
24404      if( aSyscall[i].pDefault ){
24405        aSyscall[i].pCurrent = aSyscall[i].pDefault;
24406      }
24407    }
24408  }else{
24409    /* If zName is specified, operate on only the one system call
24410    ** specified.
24411    */
24412    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
24413      if( strcmp(zName, aSyscall[i].zName)==0 ){
24414        if( aSyscall[i].pDefault==0 ){
24415          aSyscall[i].pDefault = aSyscall[i].pCurrent;
24416        }
24417        rc = SQLITE_OK;
24418        if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
24419        aSyscall[i].pCurrent = pNewFunc;
24420        break;
24421      }
24422    }
24423  }
24424  return rc;
24425}
24426
24427/*
24428** Return the value of a system call.  Return NULL if zName is not a
24429** recognized system call name.  NULL is also returned if the system call
24430** is currently undefined.
24431*/
24432static sqlite3_syscall_ptr unixGetSystemCall(
24433  sqlite3_vfs *pNotUsed,
24434  const char *zName
24435){
24436  unsigned int i;
24437
24438  UNUSED_PARAMETER(pNotUsed);
24439  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
24440    if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
24441  }
24442  return 0;
24443}
24444
24445/*
24446** Return the name of the first system call after zName.  If zName==NULL
24447** then return the name of the first system call.  Return NULL if zName
24448** is the last system call or if zName is not the name of a valid
24449** system call.
24450*/
24451static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
24452  int i = -1;
24453
24454  UNUSED_PARAMETER(p);
24455  if( zName ){
24456    for(i=0; i<ArraySize(aSyscall)-1; i++){
24457      if( strcmp(zName, aSyscall[i].zName)==0 ) break;
24458    }
24459  }
24460  for(i++; i<ArraySize(aSyscall); i++){
24461    if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
24462  }
24463  return 0;
24464}
24465
24466/*
24467** Do not accept any file descriptor less than this value, in order to avoid
24468** opening database file using file descriptors that are commonly used for
24469** standard input, output, and error.
24470*/
24471#ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
24472# define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
24473#endif
24474
24475/*
24476** Invoke open().  Do so multiple times, until it either succeeds or
24477** fails for some reason other than EINTR.
24478**
24479** If the file creation mode "m" is 0 then set it to the default for
24480** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
24481** 0644) as modified by the system umask.  If m is not 0, then
24482** make the file creation mode be exactly m ignoring the umask.
24483**
24484** The m parameter will be non-zero only when creating -wal, -journal,
24485** and -shm files.  We want those files to have *exactly* the same
24486** permissions as their original database, unadulterated by the umask.
24487** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
24488** transaction crashes and leaves behind hot journals, then any
24489** process that is able to write to the database will also be able to
24490** recover the hot journals.
24491*/
24492static int robust_open(const char *z, int f, mode_t m){
24493  int fd;
24494  mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
24495  while(1){
24496#if defined(O_CLOEXEC)
24497    fd = osOpen(z,f|O_CLOEXEC,m2);
24498#else
24499    fd = osOpen(z,f,m2);
24500#endif
24501    if( fd<0 ){
24502      if( errno==EINTR ) continue;
24503      break;
24504    }
24505    if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
24506    osClose(fd);
24507    sqlite3_log(SQLITE_WARNING,
24508                "attempt to open \"%s\" as file descriptor %d", z, fd);
24509    fd = -1;
24510    if( osOpen("/dev/null", f, m)<0 ) break;
24511  }
24512  if( fd>=0 ){
24513    if( m!=0 ){
24514      struct stat statbuf;
24515      if( osFstat(fd, &statbuf)==0
24516       && statbuf.st_size==0
24517       && (statbuf.st_mode&0777)!=m
24518      ){
24519        osFchmod(fd, m);
24520      }
24521    }
24522#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
24523    osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
24524#endif
24525  }
24526  return fd;
24527}
24528
24529/*
24530** Helper functions to obtain and relinquish the global mutex. The
24531** global mutex is used to protect the unixInodeInfo and
24532** vxworksFileId objects used by this file, all of which may be
24533** shared by multiple threads.
24534**
24535** Function unixMutexHeld() is used to assert() that the global mutex
24536** is held when required. This function is only used as part of assert()
24537** statements. e.g.
24538**
24539**   unixEnterMutex()
24540**     assert( unixMutexHeld() );
24541**   unixEnterLeave()
24542*/
24543static void unixEnterMutex(void){
24544  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
24545}
24546static void unixLeaveMutex(void){
24547  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
24548}
24549#ifdef SQLITE_DEBUG
24550static int unixMutexHeld(void) {
24551  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
24552}
24553#endif
24554
24555
24556#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
24557/*
24558** Helper function for printing out trace information from debugging
24559** binaries. This returns the string represetation of the supplied
24560** integer lock-type.
24561*/
24562static const char *azFileLock(int eFileLock){
24563  switch( eFileLock ){
24564    case NO_LOCK: return "NONE";
24565    case SHARED_LOCK: return "SHARED";
24566    case RESERVED_LOCK: return "RESERVED";
24567    case PENDING_LOCK: return "PENDING";
24568    case EXCLUSIVE_LOCK: return "EXCLUSIVE";
24569  }
24570  return "ERROR";
24571}
24572#endif
24573
24574#ifdef SQLITE_LOCK_TRACE
24575/*
24576** Print out information about all locking operations.
24577**
24578** This routine is used for troubleshooting locks on multithreaded
24579** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
24580** command-line option on the compiler.  This code is normally
24581** turned off.
24582*/
24583static int lockTrace(int fd, int op, struct flock *p){
24584  char *zOpName, *zType;
24585  int s;
24586  int savedErrno;
24587  if( op==F_GETLK ){
24588    zOpName = "GETLK";
24589  }else if( op==F_SETLK ){
24590    zOpName = "SETLK";
24591  }else{
24592    s = osFcntl(fd, op, p);
24593    sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
24594    return s;
24595  }
24596  if( p->l_type==F_RDLCK ){
24597    zType = "RDLCK";
24598  }else if( p->l_type==F_WRLCK ){
24599    zType = "WRLCK";
24600  }else if( p->l_type==F_UNLCK ){
24601    zType = "UNLCK";
24602  }else{
24603    assert( 0 );
24604  }
24605  assert( p->l_whence==SEEK_SET );
24606  s = osFcntl(fd, op, p);
24607  savedErrno = errno;
24608  sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
24609     threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
24610     (int)p->l_pid, s);
24611  if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
24612    struct flock l2;
24613    l2 = *p;
24614    osFcntl(fd, F_GETLK, &l2);
24615    if( l2.l_type==F_RDLCK ){
24616      zType = "RDLCK";
24617    }else if( l2.l_type==F_WRLCK ){
24618      zType = "WRLCK";
24619    }else if( l2.l_type==F_UNLCK ){
24620      zType = "UNLCK";
24621    }else{
24622      assert( 0 );
24623    }
24624    sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
24625       zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
24626  }
24627  errno = savedErrno;
24628  return s;
24629}
24630#undef osFcntl
24631#define osFcntl lockTrace
24632#endif /* SQLITE_LOCK_TRACE */
24633
24634/*
24635** Retry ftruncate() calls that fail due to EINTR
24636*/
24637static int robust_ftruncate(int h, sqlite3_int64 sz){
24638  int rc;
24639  do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
24640  return rc;
24641}
24642
24643/*
24644** This routine translates a standard POSIX errno code into something
24645** useful to the clients of the sqlite3 functions.  Specifically, it is
24646** intended to translate a variety of "try again" errors into SQLITE_BUSY
24647** and a variety of "please close the file descriptor NOW" errors into
24648** SQLITE_IOERR
24649**
24650** Errors during initialization of locks, or file system support for locks,
24651** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
24652*/
24653static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
24654  switch (posixError) {
24655#if 0
24656  /* At one point this code was not commented out. In theory, this branch
24657  ** should never be hit, as this function should only be called after
24658  ** a locking-related function (i.e. fcntl()) has returned non-zero with
24659  ** the value of errno as the first argument. Since a system call has failed,
24660  ** errno should be non-zero.
24661  **
24662  ** Despite this, if errno really is zero, we still don't want to return
24663  ** SQLITE_OK. The system call failed, and *some* SQLite error should be
24664  ** propagated back to the caller. Commenting this branch out means errno==0
24665  ** will be handled by the "default:" case below.
24666  */
24667  case 0:
24668    return SQLITE_OK;
24669#endif
24670
24671  case EAGAIN:
24672  case ETIMEDOUT:
24673  case EBUSY:
24674  case EINTR:
24675  case ENOLCK:
24676    /* random NFS retry error, unless during file system support
24677     * introspection, in which it actually means what it says */
24678    return SQLITE_BUSY;
24679
24680  case EACCES:
24681    /* EACCES is like EAGAIN during locking operations, but not any other time*/
24682    if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
24683        (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
24684        (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
24685        (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
24686      return SQLITE_BUSY;
24687    }
24688    /* else fall through */
24689  case EPERM:
24690    return SQLITE_PERM;
24691
24692  /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
24693  ** this module never makes such a call. And the code in SQLite itself
24694  ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
24695  ** this case is also commented out. If the system does set errno to EDEADLK,
24696  ** the default SQLITE_IOERR_XXX code will be returned. */
24697#if 0
24698  case EDEADLK:
24699    return SQLITE_IOERR_BLOCKED;
24700#endif
24701
24702#if EOPNOTSUPP!=ENOTSUP
24703  case EOPNOTSUPP:
24704    /* something went terribly awry, unless during file system support
24705     * introspection, in which it actually means what it says */
24706#endif
24707#ifdef ENOTSUP
24708  case ENOTSUP:
24709    /* invalid fd, unless during file system support introspection, in which
24710     * it actually means what it says */
24711#endif
24712  case EIO:
24713  case EBADF:
24714  case EINVAL:
24715  case ENOTCONN:
24716  case ENODEV:
24717  case ENXIO:
24718  case ENOENT:
24719#ifdef ESTALE                     /* ESTALE is not defined on Interix systems */
24720  case ESTALE:
24721#endif
24722  case ENOSYS:
24723    /* these should force the client to close the file and reconnect */
24724
24725  default:
24726    return sqliteIOErr;
24727  }
24728}
24729
24730
24731/******************************************************************************
24732****************** Begin Unique File ID Utility Used By VxWorks ***************
24733**
24734** On most versions of unix, we can get a unique ID for a file by concatenating
24735** the device number and the inode number.  But this does not work on VxWorks.
24736** On VxWorks, a unique file id must be based on the canonical filename.
24737**
24738** A pointer to an instance of the following structure can be used as a
24739** unique file ID in VxWorks.  Each instance of this structure contains
24740** a copy of the canonical filename.  There is also a reference count.
24741** The structure is reclaimed when the number of pointers to it drops to
24742** zero.
24743**
24744** There are never very many files open at one time and lookups are not
24745** a performance-critical path, so it is sufficient to put these
24746** structures on a linked list.
24747*/
24748struct vxworksFileId {
24749  struct vxworksFileId *pNext;  /* Next in a list of them all */
24750  int nRef;                     /* Number of references to this one */
24751  int nName;                    /* Length of the zCanonicalName[] string */
24752  char *zCanonicalName;         /* Canonical filename */
24753};
24754
24755#if OS_VXWORKS
24756/*
24757** All unique filenames are held on a linked list headed by this
24758** variable:
24759*/
24760static struct vxworksFileId *vxworksFileList = 0;
24761
24762/*
24763** Simplify a filename into its canonical form
24764** by making the following changes:
24765**
24766**  * removing any trailing and duplicate /
24767**  * convert /./ into just /
24768**  * convert /A/../ where A is any simple name into just /
24769**
24770** Changes are made in-place.  Return the new name length.
24771**
24772** The original filename is in z[0..n-1].  Return the number of
24773** characters in the simplified name.
24774*/
24775static int vxworksSimplifyName(char *z, int n){
24776  int i, j;
24777  while( n>1 && z[n-1]=='/' ){ n--; }
24778  for(i=j=0; i<n; i++){
24779    if( z[i]=='/' ){
24780      if( z[i+1]=='/' ) continue;
24781      if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
24782        i += 1;
24783        continue;
24784      }
24785      if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
24786        while( j>0 && z[j-1]!='/' ){ j--; }
24787        if( j>0 ){ j--; }
24788        i += 2;
24789        continue;
24790      }
24791    }
24792    z[j++] = z[i];
24793  }
24794  z[j] = 0;
24795  return j;
24796}
24797
24798/*
24799** Find a unique file ID for the given absolute pathname.  Return
24800** a pointer to the vxworksFileId object.  This pointer is the unique
24801** file ID.
24802**
24803** The nRef field of the vxworksFileId object is incremented before
24804** the object is returned.  A new vxworksFileId object is created
24805** and added to the global list if necessary.
24806**
24807** If a memory allocation error occurs, return NULL.
24808*/
24809static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
24810  struct vxworksFileId *pNew;         /* search key and new file ID */
24811  struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
24812  int n;                              /* Length of zAbsoluteName string */
24813
24814  assert( zAbsoluteName[0]=='/' );
24815  n = (int)strlen(zAbsoluteName);
24816  pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
24817  if( pNew==0 ) return 0;
24818  pNew->zCanonicalName = (char*)&pNew[1];
24819  memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
24820  n = vxworksSimplifyName(pNew->zCanonicalName, n);
24821
24822  /* Search for an existing entry that matching the canonical name.
24823  ** If found, increment the reference count and return a pointer to
24824  ** the existing file ID.
24825  */
24826  unixEnterMutex();
24827  for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
24828    if( pCandidate->nName==n
24829     && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
24830    ){
24831       sqlite3_free(pNew);
24832       pCandidate->nRef++;
24833       unixLeaveMutex();
24834       return pCandidate;
24835    }
24836  }
24837
24838  /* No match was found.  We will make a new file ID */
24839  pNew->nRef = 1;
24840  pNew->nName = n;
24841  pNew->pNext = vxworksFileList;
24842  vxworksFileList = pNew;
24843  unixLeaveMutex();
24844  return pNew;
24845}
24846
24847/*
24848** Decrement the reference count on a vxworksFileId object.  Free
24849** the object when the reference count reaches zero.
24850*/
24851static void vxworksReleaseFileId(struct vxworksFileId *pId){
24852  unixEnterMutex();
24853  assert( pId->nRef>0 );
24854  pId->nRef--;
24855  if( pId->nRef==0 ){
24856    struct vxworksFileId **pp;
24857    for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
24858    assert( *pp==pId );
24859    *pp = pId->pNext;
24860    sqlite3_free(pId);
24861  }
24862  unixLeaveMutex();
24863}
24864#endif /* OS_VXWORKS */
24865/*************** End of Unique File ID Utility Used By VxWorks ****************
24866******************************************************************************/
24867
24868
24869/******************************************************************************
24870*************************** Posix Advisory Locking ****************************
24871**
24872** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
24873** section 6.5.2.2 lines 483 through 490 specify that when a process
24874** sets or clears a lock, that operation overrides any prior locks set
24875** by the same process.  It does not explicitly say so, but this implies
24876** that it overrides locks set by the same process using a different
24877** file descriptor.  Consider this test case:
24878**
24879**       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
24880**       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
24881**
24882** Suppose ./file1 and ./file2 are really the same file (because
24883** one is a hard or symbolic link to the other) then if you set
24884** an exclusive lock on fd1, then try to get an exclusive lock
24885** on fd2, it works.  I would have expected the second lock to
24886** fail since there was already a lock on the file due to fd1.
24887** But not so.  Since both locks came from the same process, the
24888** second overrides the first, even though they were on different
24889** file descriptors opened on different file names.
24890**
24891** This means that we cannot use POSIX locks to synchronize file access
24892** among competing threads of the same process.  POSIX locks will work fine
24893** to synchronize access for threads in separate processes, but not
24894** threads within the same process.
24895**
24896** To work around the problem, SQLite has to manage file locks internally
24897** on its own.  Whenever a new database is opened, we have to find the
24898** specific inode of the database file (the inode is determined by the
24899** st_dev and st_ino fields of the stat structure that fstat() fills in)
24900** and check for locks already existing on that inode.  When locks are
24901** created or removed, we have to look at our own internal record of the
24902** locks to see if another thread has previously set a lock on that same
24903** inode.
24904**
24905** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
24906** For VxWorks, we have to use the alternative unique ID system based on
24907** canonical filename and implemented in the previous division.)
24908**
24909** The sqlite3_file structure for POSIX is no longer just an integer file
24910** descriptor.  It is now a structure that holds the integer file
24911** descriptor and a pointer to a structure that describes the internal
24912** locks on the corresponding inode.  There is one locking structure
24913** per inode, so if the same inode is opened twice, both unixFile structures
24914** point to the same locking structure.  The locking structure keeps
24915** a reference count (so we will know when to delete it) and a "cnt"
24916** field that tells us its internal lock status.  cnt==0 means the
24917** file is unlocked.  cnt==-1 means the file has an exclusive lock.
24918** cnt>0 means there are cnt shared locks on the file.
24919**
24920** Any attempt to lock or unlock a file first checks the locking
24921** structure.  The fcntl() system call is only invoked to set a
24922** POSIX lock if the internal lock structure transitions between
24923** a locked and an unlocked state.
24924**
24925** But wait:  there are yet more problems with POSIX advisory locks.
24926**
24927** If you close a file descriptor that points to a file that has locks,
24928** all locks on that file that are owned by the current process are
24929** released.  To work around this problem, each unixInodeInfo object
24930** maintains a count of the number of pending locks on tha inode.
24931** When an attempt is made to close an unixFile, if there are
24932** other unixFile open on the same inode that are holding locks, the call
24933** to close() the file descriptor is deferred until all of the locks clear.
24934** The unixInodeInfo structure keeps a list of file descriptors that need to
24935** be closed and that list is walked (and cleared) when the last lock
24936** clears.
24937**
24938** Yet another problem:  LinuxThreads do not play well with posix locks.
24939**
24940** Many older versions of linux use the LinuxThreads library which is
24941** not posix compliant.  Under LinuxThreads, a lock created by thread
24942** A cannot be modified or overridden by a different thread B.
24943** Only thread A can modify the lock.  Locking behavior is correct
24944** if the appliation uses the newer Native Posix Thread Library (NPTL)
24945** on linux - with NPTL a lock created by thread A can override locks
24946** in thread B.  But there is no way to know at compile-time which
24947** threading library is being used.  So there is no way to know at
24948** compile-time whether or not thread A can override locks on thread B.
24949** One has to do a run-time check to discover the behavior of the
24950** current process.
24951**
24952** SQLite used to support LinuxThreads.  But support for LinuxThreads
24953** was dropped beginning with version 3.7.0.  SQLite will still work with
24954** LinuxThreads provided that (1) there is no more than one connection
24955** per database file in the same process and (2) database connections
24956** do not move across threads.
24957*/
24958
24959/*
24960** An instance of the following structure serves as the key used
24961** to locate a particular unixInodeInfo object.
24962*/
24963struct unixFileId {
24964  dev_t dev;                  /* Device number */
24965#if OS_VXWORKS
24966  struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
24967#else
24968  ino_t ino;                  /* Inode number */
24969#endif
24970};
24971
24972/*
24973** An instance of the following structure is allocated for each open
24974** inode.  Or, on LinuxThreads, there is one of these structures for
24975** each inode opened by each thread.
24976**
24977** A single inode can have multiple file descriptors, so each unixFile
24978** structure contains a pointer to an instance of this object and this
24979** object keeps a count of the number of unixFile pointing to it.
24980*/
24981struct unixInodeInfo {
24982  struct unixFileId fileId;       /* The lookup key */
24983  int nShared;                    /* Number of SHARED locks held */
24984  unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
24985  unsigned char bProcessLock;     /* An exclusive process lock is held */
24986  int nRef;                       /* Number of pointers to this structure */
24987  unixShmNode *pShmNode;          /* Shared memory associated with this inode */
24988  int nLock;                      /* Number of outstanding file locks */
24989  UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
24990  unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
24991  unixInodeInfo *pPrev;           /*    .... doubly linked */
24992#if SQLITE_ENABLE_LOCKING_STYLE
24993  unsigned long long sharedByte;  /* for AFP simulated shared lock */
24994#endif
24995#if OS_VXWORKS
24996  sem_t *pSem;                    /* Named POSIX semaphore */
24997  char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
24998#endif
24999};
25000
25001/*
25002** A lists of all unixInodeInfo objects.
25003*/
25004static unixInodeInfo *inodeList = 0;
25005
25006/*
25007**
25008** This function - unixLogError_x(), is only ever called via the macro
25009** unixLogError().
25010**
25011** It is invoked after an error occurs in an OS function and errno has been
25012** set. It logs a message using sqlite3_log() containing the current value of
25013** errno and, if possible, the human-readable equivalent from strerror() or
25014** strerror_r().
25015**
25016** The first argument passed to the macro should be the error code that
25017** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
25018** The two subsequent arguments should be the name of the OS function that
25019** failed (e.g. "unlink", "open") and the associated file-system path,
25020** if any.
25021*/
25022#define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
25023static int unixLogErrorAtLine(
25024  int errcode,                    /* SQLite error code */
25025  const char *zFunc,              /* Name of OS function that failed */
25026  const char *zPath,              /* File path associated with error */
25027  int iLine                       /* Source line number where error occurred */
25028){
25029  char *zErr;                     /* Message from strerror() or equivalent */
25030  int iErrno = errno;             /* Saved syscall error number */
25031
25032  /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
25033  ** the strerror() function to obtain the human-readable error message
25034  ** equivalent to errno. Otherwise, use strerror_r().
25035  */
25036#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
25037  char aErr[80];
25038  memset(aErr, 0, sizeof(aErr));
25039  zErr = aErr;
25040
25041  /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
25042  ** assume that the system provides the GNU version of strerror_r() that
25043  ** returns a pointer to a buffer containing the error message. That pointer
25044  ** may point to aErr[], or it may point to some static storage somewhere.
25045  ** Otherwise, assume that the system provides the POSIX version of
25046  ** strerror_r(), which always writes an error message into aErr[].
25047  **
25048  ** If the code incorrectly assumes that it is the POSIX version that is
25049  ** available, the error message will often be an empty string. Not a
25050  ** huge problem. Incorrectly concluding that the GNU version is available
25051  ** could lead to a segfault though.
25052  */
25053#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
25054  zErr =
25055# endif
25056  strerror_r(iErrno, aErr, sizeof(aErr)-1);
25057
25058#elif SQLITE_THREADSAFE
25059  /* This is a threadsafe build, but strerror_r() is not available. */
25060  zErr = "";
25061#else
25062  /* Non-threadsafe build, use strerror(). */
25063  zErr = strerror(iErrno);
25064#endif
25065
25066  if( zPath==0 ) zPath = "";
25067  sqlite3_log(errcode,
25068      "os_unix.c:%d: (%d) %s(%s) - %s",
25069      iLine, iErrno, zFunc, zPath, zErr
25070  );
25071
25072  return errcode;
25073}
25074
25075/*
25076** Close a file descriptor.
25077**
25078** We assume that close() almost always works, since it is only in a
25079** very sick application or on a very sick platform that it might fail.
25080** If it does fail, simply leak the file descriptor, but do log the
25081** error.
25082**
25083** Note that it is not safe to retry close() after EINTR since the
25084** file descriptor might have already been reused by another thread.
25085** So we don't even try to recover from an EINTR.  Just log the error
25086** and move on.
25087*/
25088static void robust_close(unixFile *pFile, int h, int lineno){
25089  if( osClose(h) ){
25090    unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
25091                       pFile ? pFile->zPath : 0, lineno);
25092  }
25093}
25094
25095/*
25096** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
25097*/
25098static void closePendingFds(unixFile *pFile){
25099  unixInodeInfo *pInode = pFile->pInode;
25100  UnixUnusedFd *p;
25101  UnixUnusedFd *pNext;
25102  for(p=pInode->pUnused; p; p=pNext){
25103    pNext = p->pNext;
25104    robust_close(pFile, p->fd, __LINE__);
25105    sqlite3_free(p);
25106  }
25107  pInode->pUnused = 0;
25108}
25109
25110/*
25111** Release a unixInodeInfo structure previously allocated by findInodeInfo().
25112**
25113** The mutex entered using the unixEnterMutex() function must be held
25114** when this function is called.
25115*/
25116static void releaseInodeInfo(unixFile *pFile){
25117  unixInodeInfo *pInode = pFile->pInode;
25118  assert( unixMutexHeld() );
25119  if( ALWAYS(pInode) ){
25120    pInode->nRef--;
25121    if( pInode->nRef==0 ){
25122      assert( pInode->pShmNode==0 );
25123      closePendingFds(pFile);
25124      if( pInode->pPrev ){
25125        assert( pInode->pPrev->pNext==pInode );
25126        pInode->pPrev->pNext = pInode->pNext;
25127      }else{
25128        assert( inodeList==pInode );
25129        inodeList = pInode->pNext;
25130      }
25131      if( pInode->pNext ){
25132        assert( pInode->pNext->pPrev==pInode );
25133        pInode->pNext->pPrev = pInode->pPrev;
25134      }
25135      sqlite3_free(pInode);
25136    }
25137  }
25138}
25139
25140/*
25141** Given a file descriptor, locate the unixInodeInfo object that
25142** describes that file descriptor.  Create a new one if necessary.  The
25143** return value might be uninitialized if an error occurs.
25144**
25145** The mutex entered using the unixEnterMutex() function must be held
25146** when this function is called.
25147**
25148** Return an appropriate error code.
25149*/
25150static int findInodeInfo(
25151  unixFile *pFile,               /* Unix file with file desc used in the key */
25152  unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
25153){
25154  int rc;                        /* System call return code */
25155  int fd;                        /* The file descriptor for pFile */
25156  struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
25157  struct stat statbuf;           /* Low-level file information */
25158  unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
25159
25160  assert( unixMutexHeld() );
25161
25162  /* Get low-level information about the file that we can used to
25163  ** create a unique name for the file.
25164  */
25165  fd = pFile->h;
25166  rc = osFstat(fd, &statbuf);
25167  if( rc!=0 ){
25168    pFile->lastErrno = errno;
25169#ifdef EOVERFLOW
25170    if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
25171#endif
25172    return SQLITE_IOERR;
25173  }
25174
25175#ifdef __APPLE__
25176  /* On OS X on an msdos filesystem, the inode number is reported
25177  ** incorrectly for zero-size files.  See ticket #3260.  To work
25178  ** around this problem (we consider it a bug in OS X, not SQLite)
25179  ** we always increase the file size to 1 by writing a single byte
25180  ** prior to accessing the inode number.  The one byte written is
25181  ** an ASCII 'S' character which also happens to be the first byte
25182  ** in the header of every SQLite database.  In this way, if there
25183  ** is a race condition such that another thread has already populated
25184  ** the first page of the database, no damage is done.
25185  */
25186  if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
25187    do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
25188    if( rc!=1 ){
25189      pFile->lastErrno = errno;
25190      return SQLITE_IOERR;
25191    }
25192    rc = osFstat(fd, &statbuf);
25193    if( rc!=0 ){
25194      pFile->lastErrno = errno;
25195      return SQLITE_IOERR;
25196    }
25197  }
25198#endif
25199
25200  memset(&fileId, 0, sizeof(fileId));
25201  fileId.dev = statbuf.st_dev;
25202#if OS_VXWORKS
25203  fileId.pId = pFile->pId;
25204#else
25205  fileId.ino = statbuf.st_ino;
25206#endif
25207  pInode = inodeList;
25208  while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
25209    pInode = pInode->pNext;
25210  }
25211  if( pInode==0 ){
25212    pInode = sqlite3_malloc( sizeof(*pInode) );
25213    if( pInode==0 ){
25214      return SQLITE_NOMEM;
25215    }
25216    memset(pInode, 0, sizeof(*pInode));
25217    memcpy(&pInode->fileId, &fileId, sizeof(fileId));
25218    pInode->nRef = 1;
25219    pInode->pNext = inodeList;
25220    pInode->pPrev = 0;
25221    if( inodeList ) inodeList->pPrev = pInode;
25222    inodeList = pInode;
25223  }else{
25224    pInode->nRef++;
25225  }
25226  *ppInode = pInode;
25227  return SQLITE_OK;
25228}
25229
25230/*
25231** Return TRUE if pFile has been renamed or unlinked since it was first opened.
25232*/
25233static int fileHasMoved(unixFile *pFile){
25234  struct stat buf;
25235  return pFile->pInode!=0 &&
25236         (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
25237}
25238
25239
25240/*
25241** Check a unixFile that is a database.  Verify the following:
25242**
25243** (1) There is exactly one hard link on the file
25244** (2) The file is not a symbolic link
25245** (3) The file has not been renamed or unlinked
25246**
25247** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
25248*/
25249static void verifyDbFile(unixFile *pFile){
25250  struct stat buf;
25251  int rc;
25252  if( pFile->ctrlFlags & UNIXFILE_WARNED ){
25253    /* One or more of the following warnings have already been issued.  Do not
25254    ** repeat them so as not to clutter the error log */
25255    return;
25256  }
25257  rc = osFstat(pFile->h, &buf);
25258  if( rc!=0 ){
25259    sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
25260    pFile->ctrlFlags |= UNIXFILE_WARNED;
25261    return;
25262  }
25263  if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
25264    sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
25265    pFile->ctrlFlags |= UNIXFILE_WARNED;
25266    return;
25267  }
25268  if( buf.st_nlink>1 ){
25269    sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
25270    pFile->ctrlFlags |= UNIXFILE_WARNED;
25271    return;
25272  }
25273  if( fileHasMoved(pFile) ){
25274    sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
25275    pFile->ctrlFlags |= UNIXFILE_WARNED;
25276    return;
25277  }
25278}
25279
25280
25281/*
25282** This routine checks if there is a RESERVED lock held on the specified
25283** file by this or any other process. If such a lock is held, set *pResOut
25284** to a non-zero value otherwise *pResOut is set to zero.  The return value
25285** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25286*/
25287static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
25288  int rc = SQLITE_OK;
25289  int reserved = 0;
25290  unixFile *pFile = (unixFile*)id;
25291
25292  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25293
25294  assert( pFile );
25295  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
25296
25297  /* Check if a thread in this process holds such a lock */
25298  if( pFile->pInode->eFileLock>SHARED_LOCK ){
25299    reserved = 1;
25300  }
25301
25302  /* Otherwise see if some other process holds it.
25303  */
25304#ifndef __DJGPP__
25305  if( !reserved && !pFile->pInode->bProcessLock ){
25306    struct flock lock;
25307    lock.l_whence = SEEK_SET;
25308    lock.l_start = RESERVED_BYTE;
25309    lock.l_len = 1;
25310    lock.l_type = F_WRLCK;
25311    if( osFcntl(pFile->h, F_GETLK, &lock) ){
25312      rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
25313      pFile->lastErrno = errno;
25314    } else if( lock.l_type!=F_UNLCK ){
25315      reserved = 1;
25316    }
25317  }
25318#endif
25319
25320  unixLeaveMutex();
25321  OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
25322
25323  *pResOut = reserved;
25324  return rc;
25325}
25326
25327/*
25328** Attempt to set a system-lock on the file pFile.  The lock is
25329** described by pLock.
25330**
25331** If the pFile was opened read/write from unix-excl, then the only lock
25332** ever obtained is an exclusive lock, and it is obtained exactly once
25333** the first time any lock is attempted.  All subsequent system locking
25334** operations become no-ops.  Locking operations still happen internally,
25335** in order to coordinate access between separate database connections
25336** within this process, but all of that is handled in memory and the
25337** operating system does not participate.
25338**
25339** This function is a pass-through to fcntl(F_SETLK) if pFile is using
25340** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
25341** and is read-only.
25342**
25343** Zero is returned if the call completes successfully, or -1 if a call
25344** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
25345*/
25346static int unixFileLock(unixFile *pFile, struct flock *pLock){
25347  int rc;
25348  unixInodeInfo *pInode = pFile->pInode;
25349  assert( unixMutexHeld() );
25350  assert( pInode!=0 );
25351  if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
25352   && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
25353  ){
25354    if( pInode->bProcessLock==0 ){
25355      struct flock lock;
25356      assert( pInode->nLock==0 );
25357      lock.l_whence = SEEK_SET;
25358      lock.l_start = SHARED_FIRST;
25359      lock.l_len = SHARED_SIZE;
25360      lock.l_type = F_WRLCK;
25361      rc = osFcntl(pFile->h, F_SETLK, &lock);
25362      if( rc<0 ) return rc;
25363      pInode->bProcessLock = 1;
25364      pInode->nLock++;
25365    }else{
25366      rc = 0;
25367    }
25368  }else{
25369    rc = osFcntl(pFile->h, F_SETLK, pLock);
25370  }
25371  return rc;
25372}
25373
25374/*
25375** Lock the file with the lock specified by parameter eFileLock - one
25376** of the following:
25377**
25378**     (1) SHARED_LOCK
25379**     (2) RESERVED_LOCK
25380**     (3) PENDING_LOCK
25381**     (4) EXCLUSIVE_LOCK
25382**
25383** Sometimes when requesting one lock state, additional lock states
25384** are inserted in between.  The locking might fail on one of the later
25385** transitions leaving the lock state different from what it started but
25386** still short of its goal.  The following chart shows the allowed
25387** transitions and the inserted intermediate states:
25388**
25389**    UNLOCKED -> SHARED
25390**    SHARED -> RESERVED
25391**    SHARED -> (PENDING) -> EXCLUSIVE
25392**    RESERVED -> (PENDING) -> EXCLUSIVE
25393**    PENDING -> EXCLUSIVE
25394**
25395** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25396** routine to lower a locking level.
25397*/
25398static int unixLock(sqlite3_file *id, int eFileLock){
25399  /* The following describes the implementation of the various locks and
25400  ** lock transitions in terms of the POSIX advisory shared and exclusive
25401  ** lock primitives (called read-locks and write-locks below, to avoid
25402  ** confusion with SQLite lock names). The algorithms are complicated
25403  ** slightly in order to be compatible with windows systems simultaneously
25404  ** accessing the same database file, in case that is ever required.
25405  **
25406  ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
25407  ** byte', each single bytes at well known offsets, and the 'shared byte
25408  ** range', a range of 510 bytes at a well known offset.
25409  **
25410  ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
25411  ** byte'.  If this is successful, a random byte from the 'shared byte
25412  ** range' is read-locked and the lock on the 'pending byte' released.
25413  **
25414  ** A process may only obtain a RESERVED lock after it has a SHARED lock.
25415  ** A RESERVED lock is implemented by grabbing a write-lock on the
25416  ** 'reserved byte'.
25417  **
25418  ** A process may only obtain a PENDING lock after it has obtained a
25419  ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
25420  ** on the 'pending byte'. This ensures that no new SHARED locks can be
25421  ** obtained, but existing SHARED locks are allowed to persist. A process
25422  ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
25423  ** This property is used by the algorithm for rolling back a journal file
25424  ** after a crash.
25425  **
25426  ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
25427  ** implemented by obtaining a write-lock on the entire 'shared byte
25428  ** range'. Since all other locks require a read-lock on one of the bytes
25429  ** within this range, this ensures that no other locks are held on the
25430  ** database.
25431  **
25432  ** The reason a single byte cannot be used instead of the 'shared byte
25433  ** range' is that some versions of windows do not support read-locks. By
25434  ** locking a random byte from a range, concurrent SHARED locks may exist
25435  ** even if the locking primitive used is always a write-lock.
25436  */
25437  int rc = SQLITE_OK;
25438  unixFile *pFile = (unixFile*)id;
25439  unixInodeInfo *pInode;
25440  struct flock lock;
25441  int tErrno = 0;
25442
25443  assert( pFile );
25444  OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
25445      azFileLock(eFileLock), azFileLock(pFile->eFileLock),
25446      azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
25447
25448  /* If there is already a lock of this type or more restrictive on the
25449  ** unixFile, do nothing. Don't use the end_lock: exit path, as
25450  ** unixEnterMutex() hasn't been called yet.
25451  */
25452  if( pFile->eFileLock>=eFileLock ){
25453    OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
25454            azFileLock(eFileLock)));
25455    return SQLITE_OK;
25456  }
25457
25458  /* Make sure the locking sequence is correct.
25459  **  (1) We never move from unlocked to anything higher than shared lock.
25460  **  (2) SQLite never explicitly requests a pendig lock.
25461  **  (3) A shared lock is always held when a reserve lock is requested.
25462  */
25463  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
25464  assert( eFileLock!=PENDING_LOCK );
25465  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
25466
25467  /* This mutex is needed because pFile->pInode is shared across threads
25468  */
25469  unixEnterMutex();
25470  pInode = pFile->pInode;
25471
25472  /* If some thread using this PID has a lock via a different unixFile*
25473  ** handle that precludes the requested lock, return BUSY.
25474  */
25475  if( (pFile->eFileLock!=pInode->eFileLock &&
25476          (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
25477  ){
25478    rc = SQLITE_BUSY;
25479    goto end_lock;
25480  }
25481
25482  /* If a SHARED lock is requested, and some thread using this PID already
25483  ** has a SHARED or RESERVED lock, then increment reference counts and
25484  ** return SQLITE_OK.
25485  */
25486  if( eFileLock==SHARED_LOCK &&
25487      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
25488    assert( eFileLock==SHARED_LOCK );
25489    assert( pFile->eFileLock==0 );
25490    assert( pInode->nShared>0 );
25491    pFile->eFileLock = SHARED_LOCK;
25492    pInode->nShared++;
25493    pInode->nLock++;
25494    goto end_lock;
25495  }
25496
25497
25498  /* A PENDING lock is needed before acquiring a SHARED lock and before
25499  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
25500  ** be released.
25501  */
25502  lock.l_len = 1L;
25503  lock.l_whence = SEEK_SET;
25504  if( eFileLock==SHARED_LOCK
25505      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
25506  ){
25507    lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
25508    lock.l_start = PENDING_BYTE;
25509    if( unixFileLock(pFile, &lock) ){
25510      tErrno = errno;
25511      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25512      if( rc!=SQLITE_BUSY ){
25513        pFile->lastErrno = tErrno;
25514      }
25515      goto end_lock;
25516    }
25517  }
25518
25519
25520  /* If control gets to this point, then actually go ahead and make
25521  ** operating system calls for the specified lock.
25522  */
25523  if( eFileLock==SHARED_LOCK ){
25524    assert( pInode->nShared==0 );
25525    assert( pInode->eFileLock==0 );
25526    assert( rc==SQLITE_OK );
25527
25528    /* Now get the read-lock */
25529    lock.l_start = SHARED_FIRST;
25530    lock.l_len = SHARED_SIZE;
25531    if( unixFileLock(pFile, &lock) ){
25532      tErrno = errno;
25533      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25534    }
25535
25536    /* Drop the temporary PENDING lock */
25537    lock.l_start = PENDING_BYTE;
25538    lock.l_len = 1L;
25539    lock.l_type = F_UNLCK;
25540    if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
25541      /* This could happen with a network mount */
25542      tErrno = errno;
25543      rc = SQLITE_IOERR_UNLOCK;
25544    }
25545
25546    if( rc ){
25547      if( rc!=SQLITE_BUSY ){
25548        pFile->lastErrno = tErrno;
25549      }
25550      goto end_lock;
25551    }else{
25552      pFile->eFileLock = SHARED_LOCK;
25553      pInode->nLock++;
25554      pInode->nShared = 1;
25555    }
25556  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
25557    /* We are trying for an exclusive lock but another thread in this
25558    ** same process is still holding a shared lock. */
25559    rc = SQLITE_BUSY;
25560  }else{
25561    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
25562    ** assumed that there is a SHARED or greater lock on the file
25563    ** already.
25564    */
25565    assert( 0!=pFile->eFileLock );
25566    lock.l_type = F_WRLCK;
25567
25568    assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
25569    if( eFileLock==RESERVED_LOCK ){
25570      lock.l_start = RESERVED_BYTE;
25571      lock.l_len = 1L;
25572    }else{
25573      lock.l_start = SHARED_FIRST;
25574      lock.l_len = SHARED_SIZE;
25575    }
25576
25577    if( unixFileLock(pFile, &lock) ){
25578      tErrno = errno;
25579      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25580      if( rc!=SQLITE_BUSY ){
25581        pFile->lastErrno = tErrno;
25582      }
25583    }
25584  }
25585
25586
25587#ifdef SQLITE_DEBUG
25588  /* Set up the transaction-counter change checking flags when
25589  ** transitioning from a SHARED to a RESERVED lock.  The change
25590  ** from SHARED to RESERVED marks the beginning of a normal
25591  ** write operation (not a hot journal rollback).
25592  */
25593  if( rc==SQLITE_OK
25594   && pFile->eFileLock<=SHARED_LOCK
25595   && eFileLock==RESERVED_LOCK
25596  ){
25597    pFile->transCntrChng = 0;
25598    pFile->dbUpdate = 0;
25599    pFile->inNormalWrite = 1;
25600  }
25601#endif
25602
25603
25604  if( rc==SQLITE_OK ){
25605    pFile->eFileLock = eFileLock;
25606    pInode->eFileLock = eFileLock;
25607  }else if( eFileLock==EXCLUSIVE_LOCK ){
25608    pFile->eFileLock = PENDING_LOCK;
25609    pInode->eFileLock = PENDING_LOCK;
25610  }
25611
25612end_lock:
25613  unixLeaveMutex();
25614  OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
25615      rc==SQLITE_OK ? "ok" : "failed"));
25616  return rc;
25617}
25618
25619/*
25620** Add the file descriptor used by file handle pFile to the corresponding
25621** pUnused list.
25622*/
25623static void setPendingFd(unixFile *pFile){
25624  unixInodeInfo *pInode = pFile->pInode;
25625  UnixUnusedFd *p = pFile->pUnused;
25626  p->pNext = pInode->pUnused;
25627  pInode->pUnused = p;
25628  pFile->h = -1;
25629  pFile->pUnused = 0;
25630}
25631
25632/*
25633** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25634** must be either NO_LOCK or SHARED_LOCK.
25635**
25636** If the locking level of the file descriptor is already at or below
25637** the requested locking level, this routine is a no-op.
25638**
25639** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
25640** the byte range is divided into 2 parts and the first part is unlocked then
25641** set to a read lock, then the other part is simply unlocked.  This works
25642** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
25643** remove the write lock on a region when a read lock is set.
25644*/
25645static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
25646  unixFile *pFile = (unixFile*)id;
25647  unixInodeInfo *pInode;
25648  struct flock lock;
25649  int rc = SQLITE_OK;
25650
25651  assert( pFile );
25652  OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
25653      pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
25654      getpid()));
25655
25656  assert( eFileLock<=SHARED_LOCK );
25657  if( pFile->eFileLock<=eFileLock ){
25658    return SQLITE_OK;
25659  }
25660  unixEnterMutex();
25661  pInode = pFile->pInode;
25662  assert( pInode->nShared!=0 );
25663  if( pFile->eFileLock>SHARED_LOCK ){
25664    assert( pInode->eFileLock==pFile->eFileLock );
25665
25666#ifdef SQLITE_DEBUG
25667    /* When reducing a lock such that other processes can start
25668    ** reading the database file again, make sure that the
25669    ** transaction counter was updated if any part of the database
25670    ** file changed.  If the transaction counter is not updated,
25671    ** other connections to the same file might not realize that
25672    ** the file has changed and hence might not know to flush their
25673    ** cache.  The use of a stale cache can lead to database corruption.
25674    */
25675    pFile->inNormalWrite = 0;
25676#endif
25677
25678    /* downgrading to a shared lock on NFS involves clearing the write lock
25679    ** before establishing the readlock - to avoid a race condition we downgrade
25680    ** the lock in 2 blocks, so that part of the range will be covered by a
25681    ** write lock until the rest is covered by a read lock:
25682    **  1:   [WWWWW]
25683    **  2:   [....W]
25684    **  3:   [RRRRW]
25685    **  4:   [RRRR.]
25686    */
25687    if( eFileLock==SHARED_LOCK ){
25688
25689#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
25690      (void)handleNFSUnlock;
25691      assert( handleNFSUnlock==0 );
25692#endif
25693#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25694      if( handleNFSUnlock ){
25695        int tErrno;               /* Error code from system call errors */
25696        off_t divSize = SHARED_SIZE - 1;
25697
25698        lock.l_type = F_UNLCK;
25699        lock.l_whence = SEEK_SET;
25700        lock.l_start = SHARED_FIRST;
25701        lock.l_len = divSize;
25702        if( unixFileLock(pFile, &lock)==(-1) ){
25703          tErrno = errno;
25704          rc = SQLITE_IOERR_UNLOCK;
25705          if( IS_LOCK_ERROR(rc) ){
25706            pFile->lastErrno = tErrno;
25707          }
25708          goto end_unlock;
25709        }
25710        lock.l_type = F_RDLCK;
25711        lock.l_whence = SEEK_SET;
25712        lock.l_start = SHARED_FIRST;
25713        lock.l_len = divSize;
25714        if( unixFileLock(pFile, &lock)==(-1) ){
25715          tErrno = errno;
25716          rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
25717          if( IS_LOCK_ERROR(rc) ){
25718            pFile->lastErrno = tErrno;
25719          }
25720          goto end_unlock;
25721        }
25722        lock.l_type = F_UNLCK;
25723        lock.l_whence = SEEK_SET;
25724        lock.l_start = SHARED_FIRST+divSize;
25725        lock.l_len = SHARED_SIZE-divSize;
25726        if( unixFileLock(pFile, &lock)==(-1) ){
25727          tErrno = errno;
25728          rc = SQLITE_IOERR_UNLOCK;
25729          if( IS_LOCK_ERROR(rc) ){
25730            pFile->lastErrno = tErrno;
25731          }
25732          goto end_unlock;
25733        }
25734      }else
25735#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
25736      {
25737        lock.l_type = F_RDLCK;
25738        lock.l_whence = SEEK_SET;
25739        lock.l_start = SHARED_FIRST;
25740        lock.l_len = SHARED_SIZE;
25741        if( unixFileLock(pFile, &lock) ){
25742          /* In theory, the call to unixFileLock() cannot fail because another
25743          ** process is holding an incompatible lock. If it does, this
25744          ** indicates that the other process is not following the locking
25745          ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
25746          ** SQLITE_BUSY would confuse the upper layer (in practice it causes
25747          ** an assert to fail). */
25748          rc = SQLITE_IOERR_RDLOCK;
25749          pFile->lastErrno = errno;
25750          goto end_unlock;
25751        }
25752      }
25753    }
25754    lock.l_type = F_UNLCK;
25755    lock.l_whence = SEEK_SET;
25756    lock.l_start = PENDING_BYTE;
25757    lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
25758    if( unixFileLock(pFile, &lock)==0 ){
25759      pInode->eFileLock = SHARED_LOCK;
25760    }else{
25761      rc = SQLITE_IOERR_UNLOCK;
25762      pFile->lastErrno = errno;
25763      goto end_unlock;
25764    }
25765  }
25766  if( eFileLock==NO_LOCK ){
25767    /* Decrement the shared lock counter.  Release the lock using an
25768    ** OS call only when all threads in this same process have released
25769    ** the lock.
25770    */
25771    pInode->nShared--;
25772    if( pInode->nShared==0 ){
25773      lock.l_type = F_UNLCK;
25774      lock.l_whence = SEEK_SET;
25775      lock.l_start = lock.l_len = 0L;
25776      if( unixFileLock(pFile, &lock)==0 ){
25777        pInode->eFileLock = NO_LOCK;
25778      }else{
25779        rc = SQLITE_IOERR_UNLOCK;
25780        pFile->lastErrno = errno;
25781        pInode->eFileLock = NO_LOCK;
25782        pFile->eFileLock = NO_LOCK;
25783      }
25784    }
25785
25786    /* Decrement the count of locks against this same file.  When the
25787    ** count reaches zero, close any other file descriptors whose close
25788    ** was deferred because of outstanding locks.
25789    */
25790    pInode->nLock--;
25791    assert( pInode->nLock>=0 );
25792    if( pInode->nLock==0 ){
25793      closePendingFds(pFile);
25794    }
25795  }
25796
25797end_unlock:
25798  unixLeaveMutex();
25799  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
25800  return rc;
25801}
25802
25803/*
25804** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25805** must be either NO_LOCK or SHARED_LOCK.
25806**
25807** If the locking level of the file descriptor is already at or below
25808** the requested locking level, this routine is a no-op.
25809*/
25810static int unixUnlock(sqlite3_file *id, int eFileLock){
25811#if SQLITE_MAX_MMAP_SIZE>0
25812  assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
25813#endif
25814  return posixUnlock(id, eFileLock, 0);
25815}
25816
25817#if SQLITE_MAX_MMAP_SIZE>0
25818static int unixMapfile(unixFile *pFd, i64 nByte);
25819static void unixUnmapfile(unixFile *pFd);
25820#endif
25821
25822/*
25823** This function performs the parts of the "close file" operation
25824** common to all locking schemes. It closes the directory and file
25825** handles, if they are valid, and sets all fields of the unixFile
25826** structure to 0.
25827**
25828** It is *not* necessary to hold the mutex when this routine is called,
25829** even on VxWorks.  A mutex will be acquired on VxWorks by the
25830** vxworksReleaseFileId() routine.
25831*/
25832static int closeUnixFile(sqlite3_file *id){
25833  unixFile *pFile = (unixFile*)id;
25834#if SQLITE_MAX_MMAP_SIZE>0
25835  unixUnmapfile(pFile);
25836#endif
25837  if( pFile->h>=0 ){
25838    robust_close(pFile, pFile->h, __LINE__);
25839    pFile->h = -1;
25840  }
25841#if OS_VXWORKS
25842  if( pFile->pId ){
25843    if( pFile->ctrlFlags & UNIXFILE_DELETE ){
25844      osUnlink(pFile->pId->zCanonicalName);
25845    }
25846    vxworksReleaseFileId(pFile->pId);
25847    pFile->pId = 0;
25848  }
25849#endif
25850  OSTRACE(("CLOSE   %-3d\n", pFile->h));
25851  OpenCounter(-1);
25852  sqlite3_free(pFile->pUnused);
25853  memset(pFile, 0, sizeof(unixFile));
25854  return SQLITE_OK;
25855}
25856
25857/*
25858** Close a file.
25859*/
25860static int unixClose(sqlite3_file *id){
25861  int rc = SQLITE_OK;
25862  unixFile *pFile = (unixFile *)id;
25863  verifyDbFile(pFile);
25864  unixUnlock(id, NO_LOCK);
25865  unixEnterMutex();
25866
25867  /* unixFile.pInode is always valid here. Otherwise, a different close
25868  ** routine (e.g. nolockClose()) would be called instead.
25869  */
25870  assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
25871  if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
25872    /* If there are outstanding locks, do not actually close the file just
25873    ** yet because that would clear those locks.  Instead, add the file
25874    ** descriptor to pInode->pUnused list.  It will be automatically closed
25875    ** when the last lock is cleared.
25876    */
25877    setPendingFd(pFile);
25878  }
25879  releaseInodeInfo(pFile);
25880  rc = closeUnixFile(id);
25881  unixLeaveMutex();
25882  return rc;
25883}
25884
25885/************** End of the posix advisory lock implementation *****************
25886******************************************************************************/
25887
25888/******************************************************************************
25889****************************** No-op Locking **********************************
25890**
25891** Of the various locking implementations available, this is by far the
25892** simplest:  locking is ignored.  No attempt is made to lock the database
25893** file for reading or writing.
25894**
25895** This locking mode is appropriate for use on read-only databases
25896** (ex: databases that are burned into CD-ROM, for example.)  It can
25897** also be used if the application employs some external mechanism to
25898** prevent simultaneous access of the same database by two or more
25899** database connections.  But there is a serious risk of database
25900** corruption if this locking mode is used in situations where multiple
25901** database connections are accessing the same database file at the same
25902** time and one or more of those connections are writing.
25903*/
25904
25905static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
25906  UNUSED_PARAMETER(NotUsed);
25907  *pResOut = 0;
25908  return SQLITE_OK;
25909}
25910static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
25911  UNUSED_PARAMETER2(NotUsed, NotUsed2);
25912  return SQLITE_OK;
25913}
25914static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
25915  UNUSED_PARAMETER2(NotUsed, NotUsed2);
25916  return SQLITE_OK;
25917}
25918
25919/*
25920** Close the file.
25921*/
25922static int nolockClose(sqlite3_file *id) {
25923  return closeUnixFile(id);
25924}
25925
25926/******************* End of the no-op lock implementation *********************
25927******************************************************************************/
25928
25929/******************************************************************************
25930************************* Begin dot-file Locking ******************************
25931**
25932** The dotfile locking implementation uses the existence of separate lock
25933** files (really a directory) to control access to the database.  This works
25934** on just about every filesystem imaginable.  But there are serious downsides:
25935**
25936**    (1)  There is zero concurrency.  A single reader blocks all other
25937**         connections from reading or writing the database.
25938**
25939**    (2)  An application crash or power loss can leave stale lock files
25940**         sitting around that need to be cleared manually.
25941**
25942** Nevertheless, a dotlock is an appropriate locking mode for use if no
25943** other locking strategy is available.
25944**
25945** Dotfile locking works by creating a subdirectory in the same directory as
25946** the database and with the same name but with a ".lock" extension added.
25947** The existence of a lock directory implies an EXCLUSIVE lock.  All other
25948** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
25949*/
25950
25951/*
25952** The file suffix added to the data base filename in order to create the
25953** lock directory.
25954*/
25955#define DOTLOCK_SUFFIX ".lock"
25956
25957/*
25958** This routine checks if there is a RESERVED lock held on the specified
25959** file by this or any other process. If such a lock is held, set *pResOut
25960** to a non-zero value otherwise *pResOut is set to zero.  The return value
25961** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25962**
25963** In dotfile locking, either a lock exists or it does not.  So in this
25964** variation of CheckReservedLock(), *pResOut is set to true if any lock
25965** is held on the file and false if the file is unlocked.
25966*/
25967static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
25968  int rc = SQLITE_OK;
25969  int reserved = 0;
25970  unixFile *pFile = (unixFile*)id;
25971
25972  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25973
25974  assert( pFile );
25975
25976  /* Check if a thread in this process holds such a lock */
25977  if( pFile->eFileLock>SHARED_LOCK ){
25978    /* Either this connection or some other connection in the same process
25979    ** holds a lock on the file.  No need to check further. */
25980    reserved = 1;
25981  }else{
25982    /* The lock is held if and only if the lockfile exists */
25983    const char *zLockFile = (const char*)pFile->lockingContext;
25984    reserved = osAccess(zLockFile, 0)==0;
25985  }
25986  OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
25987  *pResOut = reserved;
25988  return rc;
25989}
25990
25991/*
25992** Lock the file with the lock specified by parameter eFileLock - one
25993** of the following:
25994**
25995**     (1) SHARED_LOCK
25996**     (2) RESERVED_LOCK
25997**     (3) PENDING_LOCK
25998**     (4) EXCLUSIVE_LOCK
25999**
26000** Sometimes when requesting one lock state, additional lock states
26001** are inserted in between.  The locking might fail on one of the later
26002** transitions leaving the lock state different from what it started but
26003** still short of its goal.  The following chart shows the allowed
26004** transitions and the inserted intermediate states:
26005**
26006**    UNLOCKED -> SHARED
26007**    SHARED -> RESERVED
26008**    SHARED -> (PENDING) -> EXCLUSIVE
26009**    RESERVED -> (PENDING) -> EXCLUSIVE
26010**    PENDING -> EXCLUSIVE
26011**
26012** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26013** routine to lower a locking level.
26014**
26015** With dotfile locking, we really only support state (4): EXCLUSIVE.
26016** But we track the other locking levels internally.
26017*/
26018static int dotlockLock(sqlite3_file *id, int eFileLock) {
26019  unixFile *pFile = (unixFile*)id;
26020  char *zLockFile = (char *)pFile->lockingContext;
26021  int rc = SQLITE_OK;
26022
26023
26024  /* If we have any lock, then the lock file already exists.  All we have
26025  ** to do is adjust our internal record of the lock level.
26026  */
26027  if( pFile->eFileLock > NO_LOCK ){
26028    pFile->eFileLock = eFileLock;
26029    /* Always update the timestamp on the old file */
26030#ifdef HAVE_UTIME
26031    utime(zLockFile, NULL);
26032#else
26033    utimes(zLockFile, NULL);
26034#endif
26035    return SQLITE_OK;
26036  }
26037
26038  /* grab an exclusive lock */
26039  rc = osMkdir(zLockFile, 0777);
26040  if( rc<0 ){
26041    /* failed to open/create the lock directory */
26042    int tErrno = errno;
26043    if( EEXIST == tErrno ){
26044      rc = SQLITE_BUSY;
26045    } else {
26046      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26047      if( IS_LOCK_ERROR(rc) ){
26048        pFile->lastErrno = tErrno;
26049      }
26050    }
26051    return rc;
26052  }
26053
26054  /* got it, set the type and return ok */
26055  pFile->eFileLock = eFileLock;
26056  return rc;
26057}
26058
26059/*
26060** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26061** must be either NO_LOCK or SHARED_LOCK.
26062**
26063** If the locking level of the file descriptor is already at or below
26064** the requested locking level, this routine is a no-op.
26065**
26066** When the locking level reaches NO_LOCK, delete the lock file.
26067*/
26068static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
26069  unixFile *pFile = (unixFile*)id;
26070  char *zLockFile = (char *)pFile->lockingContext;
26071  int rc;
26072
26073  assert( pFile );
26074  OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
26075           pFile->eFileLock, getpid()));
26076  assert( eFileLock<=SHARED_LOCK );
26077
26078  /* no-op if possible */
26079  if( pFile->eFileLock==eFileLock ){
26080    return SQLITE_OK;
26081  }
26082
26083  /* To downgrade to shared, simply update our internal notion of the
26084  ** lock state.  No need to mess with the file on disk.
26085  */
26086  if( eFileLock==SHARED_LOCK ){
26087    pFile->eFileLock = SHARED_LOCK;
26088    return SQLITE_OK;
26089  }
26090
26091  /* To fully unlock the database, delete the lock file */
26092  assert( eFileLock==NO_LOCK );
26093  rc = osRmdir(zLockFile);
26094  if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
26095  if( rc<0 ){
26096    int tErrno = errno;
26097    rc = 0;
26098    if( ENOENT != tErrno ){
26099      rc = SQLITE_IOERR_UNLOCK;
26100    }
26101    if( IS_LOCK_ERROR(rc) ){
26102      pFile->lastErrno = tErrno;
26103    }
26104    return rc;
26105  }
26106  pFile->eFileLock = NO_LOCK;
26107  return SQLITE_OK;
26108}
26109
26110/*
26111** Close a file.  Make sure the lock has been released before closing.
26112*/
26113static int dotlockClose(sqlite3_file *id) {
26114  int rc = SQLITE_OK;
26115  if( id ){
26116    unixFile *pFile = (unixFile*)id;
26117    dotlockUnlock(id, NO_LOCK);
26118    sqlite3_free(pFile->lockingContext);
26119    rc = closeUnixFile(id);
26120  }
26121  return rc;
26122}
26123/****************** End of the dot-file lock implementation *******************
26124******************************************************************************/
26125
26126/******************************************************************************
26127************************** Begin flock Locking ********************************
26128**
26129** Use the flock() system call to do file locking.
26130**
26131** flock() locking is like dot-file locking in that the various
26132** fine-grain locking levels supported by SQLite are collapsed into
26133** a single exclusive lock.  In other words, SHARED, RESERVED, and
26134** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
26135** still works when you do this, but concurrency is reduced since
26136** only a single process can be reading the database at a time.
26137**
26138** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
26139** compiling for VXWORKS.
26140*/
26141#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
26142
26143/*
26144** Retry flock() calls that fail with EINTR
26145*/
26146#ifdef EINTR
26147static int robust_flock(int fd, int op){
26148  int rc;
26149  do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
26150  return rc;
26151}
26152#else
26153# define robust_flock(a,b) flock(a,b)
26154#endif
26155
26156
26157/*
26158** This routine checks if there is a RESERVED lock held on the specified
26159** file by this or any other process. If such a lock is held, set *pResOut
26160** to a non-zero value otherwise *pResOut is set to zero.  The return value
26161** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26162*/
26163static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
26164  int rc = SQLITE_OK;
26165  int reserved = 0;
26166  unixFile *pFile = (unixFile*)id;
26167
26168  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26169
26170  assert( pFile );
26171
26172  /* Check if a thread in this process holds such a lock */
26173  if( pFile->eFileLock>SHARED_LOCK ){
26174    reserved = 1;
26175  }
26176
26177  /* Otherwise see if some other process holds it. */
26178  if( !reserved ){
26179    /* attempt to get the lock */
26180    int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
26181    if( !lrc ){
26182      /* got the lock, unlock it */
26183      lrc = robust_flock(pFile->h, LOCK_UN);
26184      if ( lrc ) {
26185        int tErrno = errno;
26186        /* unlock failed with an error */
26187        lrc = SQLITE_IOERR_UNLOCK;
26188        if( IS_LOCK_ERROR(lrc) ){
26189          pFile->lastErrno = tErrno;
26190          rc = lrc;
26191        }
26192      }
26193    } else {
26194      int tErrno = errno;
26195      reserved = 1;
26196      /* someone else might have it reserved */
26197      lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26198      if( IS_LOCK_ERROR(lrc) ){
26199        pFile->lastErrno = tErrno;
26200        rc = lrc;
26201      }
26202    }
26203  }
26204  OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
26205
26206#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
26207  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
26208    rc = SQLITE_OK;
26209    reserved=1;
26210  }
26211#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
26212  *pResOut = reserved;
26213  return rc;
26214}
26215
26216/*
26217** Lock the file with the lock specified by parameter eFileLock - one
26218** of the following:
26219**
26220**     (1) SHARED_LOCK
26221**     (2) RESERVED_LOCK
26222**     (3) PENDING_LOCK
26223**     (4) EXCLUSIVE_LOCK
26224**
26225** Sometimes when requesting one lock state, additional lock states
26226** are inserted in between.  The locking might fail on one of the later
26227** transitions leaving the lock state different from what it started but
26228** still short of its goal.  The following chart shows the allowed
26229** transitions and the inserted intermediate states:
26230**
26231**    UNLOCKED -> SHARED
26232**    SHARED -> RESERVED
26233**    SHARED -> (PENDING) -> EXCLUSIVE
26234**    RESERVED -> (PENDING) -> EXCLUSIVE
26235**    PENDING -> EXCLUSIVE
26236**
26237** flock() only really support EXCLUSIVE locks.  We track intermediate
26238** lock states in the sqlite3_file structure, but all locks SHARED or
26239** above are really EXCLUSIVE locks and exclude all other processes from
26240** access the file.
26241**
26242** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26243** routine to lower a locking level.
26244*/
26245static int flockLock(sqlite3_file *id, int eFileLock) {
26246  int rc = SQLITE_OK;
26247  unixFile *pFile = (unixFile*)id;
26248
26249  assert( pFile );
26250
26251  /* if we already have a lock, it is exclusive.
26252  ** Just adjust level and punt on outta here. */
26253  if (pFile->eFileLock > NO_LOCK) {
26254    pFile->eFileLock = eFileLock;
26255    return SQLITE_OK;
26256  }
26257
26258  /* grab an exclusive lock */
26259
26260  if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
26261    int tErrno = errno;
26262    /* didn't get, must be busy */
26263    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26264    if( IS_LOCK_ERROR(rc) ){
26265      pFile->lastErrno = tErrno;
26266    }
26267  } else {
26268    /* got it, set the type and return ok */
26269    pFile->eFileLock = eFileLock;
26270  }
26271  OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
26272           rc==SQLITE_OK ? "ok" : "failed"));
26273#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
26274  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
26275    rc = SQLITE_BUSY;
26276  }
26277#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
26278  return rc;
26279}
26280
26281
26282/*
26283** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26284** must be either NO_LOCK or SHARED_LOCK.
26285**
26286** If the locking level of the file descriptor is already at or below
26287** the requested locking level, this routine is a no-op.
26288*/
26289static int flockUnlock(sqlite3_file *id, int eFileLock) {
26290  unixFile *pFile = (unixFile*)id;
26291
26292  assert( pFile );
26293  OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
26294           pFile->eFileLock, getpid()));
26295  assert( eFileLock<=SHARED_LOCK );
26296
26297  /* no-op if possible */
26298  if( pFile->eFileLock==eFileLock ){
26299    return SQLITE_OK;
26300  }
26301
26302  /* shared can just be set because we always have an exclusive */
26303  if (eFileLock==SHARED_LOCK) {
26304    pFile->eFileLock = eFileLock;
26305    return SQLITE_OK;
26306  }
26307
26308  /* no, really, unlock. */
26309  if( robust_flock(pFile->h, LOCK_UN) ){
26310#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
26311    return SQLITE_OK;
26312#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
26313    return SQLITE_IOERR_UNLOCK;
26314  }else{
26315    pFile->eFileLock = NO_LOCK;
26316    return SQLITE_OK;
26317  }
26318}
26319
26320/*
26321** Close a file.
26322*/
26323static int flockClose(sqlite3_file *id) {
26324  int rc = SQLITE_OK;
26325  if( id ){
26326    flockUnlock(id, NO_LOCK);
26327    rc = closeUnixFile(id);
26328  }
26329  return rc;
26330}
26331
26332#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
26333
26334/******************* End of the flock lock implementation *********************
26335******************************************************************************/
26336
26337/******************************************************************************
26338************************ Begin Named Semaphore Locking ************************
26339**
26340** Named semaphore locking is only supported on VxWorks.
26341**
26342** Semaphore locking is like dot-lock and flock in that it really only
26343** supports EXCLUSIVE locking.  Only a single process can read or write
26344** the database file at a time.  This reduces potential concurrency, but
26345** makes the lock implementation much easier.
26346*/
26347#if OS_VXWORKS
26348
26349/*
26350** This routine checks if there is a RESERVED lock held on the specified
26351** file by this or any other process. If such a lock is held, set *pResOut
26352** to a non-zero value otherwise *pResOut is set to zero.  The return value
26353** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26354*/
26355static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
26356  int rc = SQLITE_OK;
26357  int reserved = 0;
26358  unixFile *pFile = (unixFile*)id;
26359
26360  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26361
26362  assert( pFile );
26363
26364  /* Check if a thread in this process holds such a lock */
26365  if( pFile->eFileLock>SHARED_LOCK ){
26366    reserved = 1;
26367  }
26368
26369  /* Otherwise see if some other process holds it. */
26370  if( !reserved ){
26371    sem_t *pSem = pFile->pInode->pSem;
26372    struct stat statBuf;
26373
26374    if( sem_trywait(pSem)==-1 ){
26375      int tErrno = errno;
26376      if( EAGAIN != tErrno ){
26377        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
26378        pFile->lastErrno = tErrno;
26379      } else {
26380        /* someone else has the lock when we are in NO_LOCK */
26381        reserved = (pFile->eFileLock < SHARED_LOCK);
26382      }
26383    }else{
26384      /* we could have it if we want it */
26385      sem_post(pSem);
26386    }
26387  }
26388  OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
26389
26390  *pResOut = reserved;
26391  return rc;
26392}
26393
26394/*
26395** Lock the file with the lock specified by parameter eFileLock - one
26396** of the following:
26397**
26398**     (1) SHARED_LOCK
26399**     (2) RESERVED_LOCK
26400**     (3) PENDING_LOCK
26401**     (4) EXCLUSIVE_LOCK
26402**
26403** Sometimes when requesting one lock state, additional lock states
26404** are inserted in between.  The locking might fail on one of the later
26405** transitions leaving the lock state different from what it started but
26406** still short of its goal.  The following chart shows the allowed
26407** transitions and the inserted intermediate states:
26408**
26409**    UNLOCKED -> SHARED
26410**    SHARED -> RESERVED
26411**    SHARED -> (PENDING) -> EXCLUSIVE
26412**    RESERVED -> (PENDING) -> EXCLUSIVE
26413**    PENDING -> EXCLUSIVE
26414**
26415** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
26416** lock states in the sqlite3_file structure, but all locks SHARED or
26417** above are really EXCLUSIVE locks and exclude all other processes from
26418** access the file.
26419**
26420** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26421** routine to lower a locking level.
26422*/
26423static int semLock(sqlite3_file *id, int eFileLock) {
26424  unixFile *pFile = (unixFile*)id;
26425  int fd;
26426  sem_t *pSem = pFile->pInode->pSem;
26427  int rc = SQLITE_OK;
26428
26429  /* if we already have a lock, it is exclusive.
26430  ** Just adjust level and punt on outta here. */
26431  if (pFile->eFileLock > NO_LOCK) {
26432    pFile->eFileLock = eFileLock;
26433    rc = SQLITE_OK;
26434    goto sem_end_lock;
26435  }
26436
26437  /* lock semaphore now but bail out when already locked. */
26438  if( sem_trywait(pSem)==-1 ){
26439    rc = SQLITE_BUSY;
26440    goto sem_end_lock;
26441  }
26442
26443  /* got it, set the type and return ok */
26444  pFile->eFileLock = eFileLock;
26445
26446 sem_end_lock:
26447  return rc;
26448}
26449
26450/*
26451** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26452** must be either NO_LOCK or SHARED_LOCK.
26453**
26454** If the locking level of the file descriptor is already at or below
26455** the requested locking level, this routine is a no-op.
26456*/
26457static int semUnlock(sqlite3_file *id, int eFileLock) {
26458  unixFile *pFile = (unixFile*)id;
26459  sem_t *pSem = pFile->pInode->pSem;
26460
26461  assert( pFile );
26462  assert( pSem );
26463  OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
26464           pFile->eFileLock, getpid()));
26465  assert( eFileLock<=SHARED_LOCK );
26466
26467  /* no-op if possible */
26468  if( pFile->eFileLock==eFileLock ){
26469    return SQLITE_OK;
26470  }
26471
26472  /* shared can just be set because we always have an exclusive */
26473  if (eFileLock==SHARED_LOCK) {
26474    pFile->eFileLock = eFileLock;
26475    return SQLITE_OK;
26476  }
26477
26478  /* no, really unlock. */
26479  if ( sem_post(pSem)==-1 ) {
26480    int rc, tErrno = errno;
26481    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
26482    if( IS_LOCK_ERROR(rc) ){
26483      pFile->lastErrno = tErrno;
26484    }
26485    return rc;
26486  }
26487  pFile->eFileLock = NO_LOCK;
26488  return SQLITE_OK;
26489}
26490
26491/*
26492 ** Close a file.
26493 */
26494static int semClose(sqlite3_file *id) {
26495  if( id ){
26496    unixFile *pFile = (unixFile*)id;
26497    semUnlock(id, NO_LOCK);
26498    assert( pFile );
26499    unixEnterMutex();
26500    releaseInodeInfo(pFile);
26501    unixLeaveMutex();
26502    closeUnixFile(id);
26503  }
26504  return SQLITE_OK;
26505}
26506
26507#endif /* OS_VXWORKS */
26508/*
26509** Named semaphore locking is only available on VxWorks.
26510**
26511*************** End of the named semaphore lock implementation ****************
26512******************************************************************************/
26513
26514
26515/******************************************************************************
26516*************************** Begin AFP Locking *********************************
26517**
26518** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
26519** on Apple Macintosh computers - both OS9 and OSX.
26520**
26521** Third-party implementations of AFP are available.  But this code here
26522** only works on OSX.
26523*/
26524
26525#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26526/*
26527** The afpLockingContext structure contains all afp lock specific state
26528*/
26529typedef struct afpLockingContext afpLockingContext;
26530struct afpLockingContext {
26531  int reserved;
26532  const char *dbPath;             /* Name of the open file */
26533};
26534
26535struct ByteRangeLockPB2
26536{
26537  unsigned long long offset;        /* offset to first byte to lock */
26538  unsigned long long length;        /* nbr of bytes to lock */
26539  unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
26540  unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
26541  unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
26542  int fd;                           /* file desc to assoc this lock with */
26543};
26544
26545#define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
26546
26547/*
26548** This is a utility for setting or clearing a bit-range lock on an
26549** AFP filesystem.
26550**
26551** Return SQLITE_OK on success, SQLITE_BUSY on failure.
26552*/
26553static int afpSetLock(
26554  const char *path,              /* Name of the file to be locked or unlocked */
26555  unixFile *pFile,               /* Open file descriptor on path */
26556  unsigned long long offset,     /* First byte to be locked */
26557  unsigned long long length,     /* Number of bytes to lock */
26558  int setLockFlag                /* True to set lock.  False to clear lock */
26559){
26560  struct ByteRangeLockPB2 pb;
26561  int err;
26562
26563  pb.unLockFlag = setLockFlag ? 0 : 1;
26564  pb.startEndFlag = 0;
26565  pb.offset = offset;
26566  pb.length = length;
26567  pb.fd = pFile->h;
26568
26569  OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
26570    (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
26571    offset, length));
26572  err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
26573  if ( err==-1 ) {
26574    int rc;
26575    int tErrno = errno;
26576    OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
26577             path, tErrno, strerror(tErrno)));
26578#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
26579    rc = SQLITE_BUSY;
26580#else
26581    rc = sqliteErrorFromPosixError(tErrno,
26582                    setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
26583#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
26584    if( IS_LOCK_ERROR(rc) ){
26585      pFile->lastErrno = tErrno;
26586    }
26587    return rc;
26588  } else {
26589    return SQLITE_OK;
26590  }
26591}
26592
26593/*
26594** This routine checks if there is a RESERVED lock held on the specified
26595** file by this or any other process. If such a lock is held, set *pResOut
26596** to a non-zero value otherwise *pResOut is set to zero.  The return value
26597** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26598*/
26599static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
26600  int rc = SQLITE_OK;
26601  int reserved = 0;
26602  unixFile *pFile = (unixFile*)id;
26603  afpLockingContext *context;
26604
26605  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26606
26607  assert( pFile );
26608  context = (afpLockingContext *) pFile->lockingContext;
26609  if( context->reserved ){
26610    *pResOut = 1;
26611    return SQLITE_OK;
26612  }
26613  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
26614
26615  /* Check if a thread in this process holds such a lock */
26616  if( pFile->pInode->eFileLock>SHARED_LOCK ){
26617    reserved = 1;
26618  }
26619
26620  /* Otherwise see if some other process holds it.
26621   */
26622  if( !reserved ){
26623    /* lock the RESERVED byte */
26624    int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
26625    if( SQLITE_OK==lrc ){
26626      /* if we succeeded in taking the reserved lock, unlock it to restore
26627      ** the original state */
26628      lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
26629    } else {
26630      /* if we failed to get the lock then someone else must have it */
26631      reserved = 1;
26632    }
26633    if( IS_LOCK_ERROR(lrc) ){
26634      rc=lrc;
26635    }
26636  }
26637
26638  unixLeaveMutex();
26639  OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
26640
26641  *pResOut = reserved;
26642  return rc;
26643}
26644
26645/*
26646** Lock the file with the lock specified by parameter eFileLock - one
26647** of the following:
26648**
26649**     (1) SHARED_LOCK
26650**     (2) RESERVED_LOCK
26651**     (3) PENDING_LOCK
26652**     (4) EXCLUSIVE_LOCK
26653**
26654** Sometimes when requesting one lock state, additional lock states
26655** are inserted in between.  The locking might fail on one of the later
26656** transitions leaving the lock state different from what it started but
26657** still short of its goal.  The following chart shows the allowed
26658** transitions and the inserted intermediate states:
26659**
26660**    UNLOCKED -> SHARED
26661**    SHARED -> RESERVED
26662**    SHARED -> (PENDING) -> EXCLUSIVE
26663**    RESERVED -> (PENDING) -> EXCLUSIVE
26664**    PENDING -> EXCLUSIVE
26665**
26666** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26667** routine to lower a locking level.
26668*/
26669static int afpLock(sqlite3_file *id, int eFileLock){
26670  int rc = SQLITE_OK;
26671  unixFile *pFile = (unixFile*)id;
26672  unixInodeInfo *pInode = pFile->pInode;
26673  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
26674
26675  assert( pFile );
26676  OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
26677           azFileLock(eFileLock), azFileLock(pFile->eFileLock),
26678           azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
26679
26680  /* If there is already a lock of this type or more restrictive on the
26681  ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
26682  ** unixEnterMutex() hasn't been called yet.
26683  */
26684  if( pFile->eFileLock>=eFileLock ){
26685    OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
26686           azFileLock(eFileLock)));
26687    return SQLITE_OK;
26688  }
26689
26690  /* Make sure the locking sequence is correct
26691  **  (1) We never move from unlocked to anything higher than shared lock.
26692  **  (2) SQLite never explicitly requests a pendig lock.
26693  **  (3) A shared lock is always held when a reserve lock is requested.
26694  */
26695  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
26696  assert( eFileLock!=PENDING_LOCK );
26697  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
26698
26699  /* This mutex is needed because pFile->pInode is shared across threads
26700  */
26701  unixEnterMutex();
26702  pInode = pFile->pInode;
26703
26704  /* If some thread using this PID has a lock via a different unixFile*
26705  ** handle that precludes the requested lock, return BUSY.
26706  */
26707  if( (pFile->eFileLock!=pInode->eFileLock &&
26708       (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
26709     ){
26710    rc = SQLITE_BUSY;
26711    goto afp_end_lock;
26712  }
26713
26714  /* If a SHARED lock is requested, and some thread using this PID already
26715  ** has a SHARED or RESERVED lock, then increment reference counts and
26716  ** return SQLITE_OK.
26717  */
26718  if( eFileLock==SHARED_LOCK &&
26719     (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
26720    assert( eFileLock==SHARED_LOCK );
26721    assert( pFile->eFileLock==0 );
26722    assert( pInode->nShared>0 );
26723    pFile->eFileLock = SHARED_LOCK;
26724    pInode->nShared++;
26725    pInode->nLock++;
26726    goto afp_end_lock;
26727  }
26728
26729  /* A PENDING lock is needed before acquiring a SHARED lock and before
26730  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
26731  ** be released.
26732  */
26733  if( eFileLock==SHARED_LOCK
26734      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
26735  ){
26736    int failed;
26737    failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
26738    if (failed) {
26739      rc = failed;
26740      goto afp_end_lock;
26741    }
26742  }
26743
26744  /* If control gets to this point, then actually go ahead and make
26745  ** operating system calls for the specified lock.
26746  */
26747  if( eFileLock==SHARED_LOCK ){
26748    int lrc1, lrc2, lrc1Errno = 0;
26749    long lk, mask;
26750
26751    assert( pInode->nShared==0 );
26752    assert( pInode->eFileLock==0 );
26753
26754    mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
26755    /* Now get the read-lock SHARED_LOCK */
26756    /* note that the quality of the randomness doesn't matter that much */
26757    lk = random();
26758    pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
26759    lrc1 = afpSetLock(context->dbPath, pFile,
26760          SHARED_FIRST+pInode->sharedByte, 1, 1);
26761    if( IS_LOCK_ERROR(lrc1) ){
26762      lrc1Errno = pFile->lastErrno;
26763    }
26764    /* Drop the temporary PENDING lock */
26765    lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
26766
26767    if( IS_LOCK_ERROR(lrc1) ) {
26768      pFile->lastErrno = lrc1Errno;
26769      rc = lrc1;
26770      goto afp_end_lock;
26771    } else if( IS_LOCK_ERROR(lrc2) ){
26772      rc = lrc2;
26773      goto afp_end_lock;
26774    } else if( lrc1 != SQLITE_OK ) {
26775      rc = lrc1;
26776    } else {
26777      pFile->eFileLock = SHARED_LOCK;
26778      pInode->nLock++;
26779      pInode->nShared = 1;
26780    }
26781  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
26782    /* We are trying for an exclusive lock but another thread in this
26783     ** same process is still holding a shared lock. */
26784    rc = SQLITE_BUSY;
26785  }else{
26786    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
26787    ** assumed that there is a SHARED or greater lock on the file
26788    ** already.
26789    */
26790    int failed = 0;
26791    assert( 0!=pFile->eFileLock );
26792    if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
26793        /* Acquire a RESERVED lock */
26794        failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
26795      if( !failed ){
26796        context->reserved = 1;
26797      }
26798    }
26799    if (!failed && eFileLock == EXCLUSIVE_LOCK) {
26800      /* Acquire an EXCLUSIVE lock */
26801
26802      /* Remove the shared lock before trying the range.  we'll need to
26803      ** reestablish the shared lock if we can't get the  afpUnlock
26804      */
26805      if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
26806                         pInode->sharedByte, 1, 0)) ){
26807        int failed2 = SQLITE_OK;
26808        /* now attemmpt to get the exclusive lock range */
26809        failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
26810                               SHARED_SIZE, 1);
26811        if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
26812                       SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
26813          /* Can't reestablish the shared lock.  Sqlite can't deal, this is
26814          ** a critical I/O error
26815          */
26816          rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
26817               SQLITE_IOERR_LOCK;
26818          goto afp_end_lock;
26819        }
26820      }else{
26821        rc = failed;
26822      }
26823    }
26824    if( failed ){
26825      rc = failed;
26826    }
26827  }
26828
26829  if( rc==SQLITE_OK ){
26830    pFile->eFileLock = eFileLock;
26831    pInode->eFileLock = eFileLock;
26832  }else if( eFileLock==EXCLUSIVE_LOCK ){
26833    pFile->eFileLock = PENDING_LOCK;
26834    pInode->eFileLock = PENDING_LOCK;
26835  }
26836
26837afp_end_lock:
26838  unixLeaveMutex();
26839  OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
26840         rc==SQLITE_OK ? "ok" : "failed"));
26841  return rc;
26842}
26843
26844/*
26845** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26846** must be either NO_LOCK or SHARED_LOCK.
26847**
26848** If the locking level of the file descriptor is already at or below
26849** the requested locking level, this routine is a no-op.
26850*/
26851static int afpUnlock(sqlite3_file *id, int eFileLock) {
26852  int rc = SQLITE_OK;
26853  unixFile *pFile = (unixFile*)id;
26854  unixInodeInfo *pInode;
26855  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
26856  int skipShared = 0;
26857#ifdef SQLITE_TEST
26858  int h = pFile->h;
26859#endif
26860
26861  assert( pFile );
26862  OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
26863           pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
26864           getpid()));
26865
26866  assert( eFileLock<=SHARED_LOCK );
26867  if( pFile->eFileLock<=eFileLock ){
26868    return SQLITE_OK;
26869  }
26870  unixEnterMutex();
26871  pInode = pFile->pInode;
26872  assert( pInode->nShared!=0 );
26873  if( pFile->eFileLock>SHARED_LOCK ){
26874    assert( pInode->eFileLock==pFile->eFileLock );
26875    SimulateIOErrorBenign(1);
26876    SimulateIOError( h=(-1) )
26877    SimulateIOErrorBenign(0);
26878
26879#ifdef SQLITE_DEBUG
26880    /* When reducing a lock such that other processes can start
26881    ** reading the database file again, make sure that the
26882    ** transaction counter was updated if any part of the database
26883    ** file changed.  If the transaction counter is not updated,
26884    ** other connections to the same file might not realize that
26885    ** the file has changed and hence might not know to flush their
26886    ** cache.  The use of a stale cache can lead to database corruption.
26887    */
26888    assert( pFile->inNormalWrite==0
26889           || pFile->dbUpdate==0
26890           || pFile->transCntrChng==1 );
26891    pFile->inNormalWrite = 0;
26892#endif
26893
26894    if( pFile->eFileLock==EXCLUSIVE_LOCK ){
26895      rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
26896      if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
26897        /* only re-establish the shared lock if necessary */
26898        int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
26899        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
26900      } else {
26901        skipShared = 1;
26902      }
26903    }
26904    if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
26905      rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
26906    }
26907    if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
26908      rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
26909      if( !rc ){
26910        context->reserved = 0;
26911      }
26912    }
26913    if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
26914      pInode->eFileLock = SHARED_LOCK;
26915    }
26916  }
26917  if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
26918
26919    /* Decrement the shared lock counter.  Release the lock using an
26920    ** OS call only when all threads in this same process have released
26921    ** the lock.
26922    */
26923    unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
26924    pInode->nShared--;
26925    if( pInode->nShared==0 ){
26926      SimulateIOErrorBenign(1);
26927      SimulateIOError( h=(-1) )
26928      SimulateIOErrorBenign(0);
26929      if( !skipShared ){
26930        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
26931      }
26932      if( !rc ){
26933        pInode->eFileLock = NO_LOCK;
26934        pFile->eFileLock = NO_LOCK;
26935      }
26936    }
26937    if( rc==SQLITE_OK ){
26938      pInode->nLock--;
26939      assert( pInode->nLock>=0 );
26940      if( pInode->nLock==0 ){
26941        closePendingFds(pFile);
26942      }
26943    }
26944  }
26945
26946  unixLeaveMutex();
26947  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
26948  return rc;
26949}
26950
26951/*
26952** Close a file & cleanup AFP specific locking context
26953*/
26954static int afpClose(sqlite3_file *id) {
26955  int rc = SQLITE_OK;
26956  if( id ){
26957    unixFile *pFile = (unixFile*)id;
26958    afpUnlock(id, NO_LOCK);
26959    unixEnterMutex();
26960    if( pFile->pInode && pFile->pInode->nLock ){
26961      /* If there are outstanding locks, do not actually close the file just
26962      ** yet because that would clear those locks.  Instead, add the file
26963      ** descriptor to pInode->aPending.  It will be automatically closed when
26964      ** the last lock is cleared.
26965      */
26966      setPendingFd(pFile);
26967    }
26968    releaseInodeInfo(pFile);
26969    sqlite3_free(pFile->lockingContext);
26970    rc = closeUnixFile(id);
26971    unixLeaveMutex();
26972  }
26973  return rc;
26974}
26975
26976#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26977/*
26978** The code above is the AFP lock implementation.  The code is specific
26979** to MacOSX and does not work on other unix platforms.  No alternative
26980** is available.  If you don't compile for a mac, then the "unix-afp"
26981** VFS is not available.
26982**
26983********************* End of the AFP lock implementation **********************
26984******************************************************************************/
26985
26986/******************************************************************************
26987*************************** Begin NFS Locking ********************************/
26988
26989#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26990/*
26991 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26992 ** must be either NO_LOCK or SHARED_LOCK.
26993 **
26994 ** If the locking level of the file descriptor is already at or below
26995 ** the requested locking level, this routine is a no-op.
26996 */
26997static int nfsUnlock(sqlite3_file *id, int eFileLock){
26998  return posixUnlock(id, eFileLock, 1);
26999}
27000
27001#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27002/*
27003** The code above is the NFS lock implementation.  The code is specific
27004** to MacOSX and does not work on other unix platforms.  No alternative
27005** is available.
27006**
27007********************* End of the NFS lock implementation **********************
27008******************************************************************************/
27009
27010/******************************************************************************
27011**************** Non-locking sqlite3_file methods *****************************
27012**
27013** The next division contains implementations for all methods of the
27014** sqlite3_file object other than the locking methods.  The locking
27015** methods were defined in divisions above (one locking method per
27016** division).  Those methods that are common to all locking modes
27017** are gather together into this division.
27018*/
27019
27020/*
27021** Seek to the offset passed as the second argument, then read cnt
27022** bytes into pBuf. Return the number of bytes actually read.
27023**
27024** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
27025** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
27026** one system to another.  Since SQLite does not define USE_PREAD
27027** any any form by default, we will not attempt to define _XOPEN_SOURCE.
27028** See tickets #2741 and #2681.
27029**
27030** To avoid stomping the errno value on a failed read the lastErrno value
27031** is set before returning.
27032*/
27033static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
27034  int got;
27035  int prior = 0;
27036#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
27037  i64 newOffset;
27038#endif
27039  TIMER_START;
27040  assert( cnt==(cnt&0x1ffff) );
27041  assert( id->h>2 );
27042  cnt &= 0x1ffff;
27043  do{
27044#if defined(USE_PREAD)
27045    got = osPread(id->h, pBuf, cnt, offset);
27046    SimulateIOError( got = -1 );
27047#elif defined(USE_PREAD64)
27048    got = osPread64(id->h, pBuf, cnt, offset);
27049    SimulateIOError( got = -1 );
27050#else
27051    newOffset = lseek(id->h, offset, SEEK_SET);
27052    SimulateIOError( newOffset-- );
27053    if( newOffset!=offset ){
27054      if( newOffset == -1 ){
27055        ((unixFile*)id)->lastErrno = errno;
27056      }else{
27057        ((unixFile*)id)->lastErrno = 0;
27058      }
27059      return -1;
27060    }
27061    got = osRead(id->h, pBuf, cnt);
27062#endif
27063    if( got==cnt ) break;
27064    if( got<0 ){
27065      if( errno==EINTR ){ got = 1; continue; }
27066      prior = 0;
27067      ((unixFile*)id)->lastErrno = errno;
27068      break;
27069    }else if( got>0 ){
27070      cnt -= got;
27071      offset += got;
27072      prior += got;
27073      pBuf = (void*)(got + (char*)pBuf);
27074    }
27075  }while( got>0 );
27076  TIMER_END;
27077  OSTRACE(("READ    %-3d %5d %7lld %llu\n",
27078            id->h, got+prior, offset-prior, TIMER_ELAPSED));
27079  return got+prior;
27080}
27081
27082/*
27083** Read data from a file into a buffer.  Return SQLITE_OK if all
27084** bytes were read successfully and SQLITE_IOERR if anything goes
27085** wrong.
27086*/
27087static int unixRead(
27088  sqlite3_file *id,
27089  void *pBuf,
27090  int amt,
27091  sqlite3_int64 offset
27092){
27093  unixFile *pFile = (unixFile *)id;
27094  int got;
27095  assert( id );
27096  assert( offset>=0 );
27097  assert( amt>0 );
27098
27099  /* If this is a database file (not a journal, master-journal or temp
27100  ** file), the bytes in the locking range should never be read or written. */
27101#if 0
27102  assert( pFile->pUnused==0
27103       || offset>=PENDING_BYTE+512
27104       || offset+amt<=PENDING_BYTE
27105  );
27106#endif
27107
27108#if SQLITE_MAX_MMAP_SIZE>0
27109  /* Deal with as much of this read request as possible by transfering
27110  ** data from the memory mapping using memcpy().  */
27111  if( offset<pFile->mmapSize ){
27112    if( offset+amt <= pFile->mmapSize ){
27113      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
27114      return SQLITE_OK;
27115    }else{
27116      int nCopy = pFile->mmapSize - offset;
27117      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
27118      pBuf = &((u8 *)pBuf)[nCopy];
27119      amt -= nCopy;
27120      offset += nCopy;
27121    }
27122  }
27123#endif
27124
27125  got = seekAndRead(pFile, offset, pBuf, amt);
27126  if( got==amt ){
27127    return SQLITE_OK;
27128  }else if( got<0 ){
27129    /* lastErrno set by seekAndRead */
27130    return SQLITE_IOERR_READ;
27131  }else{
27132    pFile->lastErrno = 0; /* not a system error */
27133    /* Unread parts of the buffer must be zero-filled */
27134    memset(&((char*)pBuf)[got], 0, amt-got);
27135    return SQLITE_IOERR_SHORT_READ;
27136  }
27137}
27138
27139/*
27140** Attempt to seek the file-descriptor passed as the first argument to
27141** absolute offset iOff, then attempt to write nBuf bytes of data from
27142** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
27143** return the actual number of bytes written (which may be less than
27144** nBuf).
27145*/
27146static int seekAndWriteFd(
27147  int fd,                         /* File descriptor to write to */
27148  i64 iOff,                       /* File offset to begin writing at */
27149  const void *pBuf,               /* Copy data from this buffer to the file */
27150  int nBuf,                       /* Size of buffer pBuf in bytes */
27151  int *piErrno                    /* OUT: Error number if error occurs */
27152){
27153  int rc = 0;                     /* Value returned by system call */
27154
27155  assert( nBuf==(nBuf&0x1ffff) );
27156  assert( fd>2 );
27157  nBuf &= 0x1ffff;
27158  TIMER_START;
27159
27160#if defined(USE_PREAD)
27161  do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
27162#elif defined(USE_PREAD64)
27163  do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
27164#else
27165  do{
27166    i64 iSeek = lseek(fd, iOff, SEEK_SET);
27167    SimulateIOError( iSeek-- );
27168
27169    if( iSeek!=iOff ){
27170      if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
27171      return -1;
27172    }
27173    rc = osWrite(fd, pBuf, nBuf);
27174  }while( rc<0 && errno==EINTR );
27175#endif
27176
27177  TIMER_END;
27178  OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
27179
27180  if( rc<0 && piErrno ) *piErrno = errno;
27181  return rc;
27182}
27183
27184
27185/*
27186** Seek to the offset in id->offset then read cnt bytes into pBuf.
27187** Return the number of bytes actually read.  Update the offset.
27188**
27189** To avoid stomping the errno value on a failed write the lastErrno value
27190** is set before returning.
27191*/
27192static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
27193  return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
27194}
27195
27196
27197/*
27198** Write data from a buffer into a file.  Return SQLITE_OK on success
27199** or some other error code on failure.
27200*/
27201static int unixWrite(
27202  sqlite3_file *id,
27203  const void *pBuf,
27204  int amt,
27205  sqlite3_int64 offset
27206){
27207  unixFile *pFile = (unixFile*)id;
27208  int wrote = 0;
27209  assert( id );
27210  assert( amt>0 );
27211
27212  /* If this is a database file (not a journal, master-journal or temp
27213  ** file), the bytes in the locking range should never be read or written. */
27214#if 0
27215  assert( pFile->pUnused==0
27216       || offset>=PENDING_BYTE+512
27217       || offset+amt<=PENDING_BYTE
27218  );
27219#endif
27220
27221#ifdef SQLITE_DEBUG
27222  /* If we are doing a normal write to a database file (as opposed to
27223  ** doing a hot-journal rollback or a write to some file other than a
27224  ** normal database file) then record the fact that the database
27225  ** has changed.  If the transaction counter is modified, record that
27226  ** fact too.
27227  */
27228  if( pFile->inNormalWrite ){
27229    pFile->dbUpdate = 1;  /* The database has been modified */
27230    if( offset<=24 && offset+amt>=27 ){
27231      int rc;
27232      char oldCntr[4];
27233      SimulateIOErrorBenign(1);
27234      rc = seekAndRead(pFile, 24, oldCntr, 4);
27235      SimulateIOErrorBenign(0);
27236      if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
27237        pFile->transCntrChng = 1;  /* The transaction counter has changed */
27238      }
27239    }
27240  }
27241#endif
27242
27243#if SQLITE_MAX_MMAP_SIZE>0
27244  /* Deal with as much of this write request as possible by transfering
27245  ** data from the memory mapping using memcpy().  */
27246  if( offset<pFile->mmapSize ){
27247    if( offset+amt <= pFile->mmapSize ){
27248      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
27249      return SQLITE_OK;
27250    }else{
27251      int nCopy = pFile->mmapSize - offset;
27252      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
27253      pBuf = &((u8 *)pBuf)[nCopy];
27254      amt -= nCopy;
27255      offset += nCopy;
27256    }
27257  }
27258#endif
27259
27260  while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
27261    amt -= wrote;
27262    offset += wrote;
27263    pBuf = &((char*)pBuf)[wrote];
27264  }
27265  SimulateIOError(( wrote=(-1), amt=1 ));
27266  SimulateDiskfullError(( wrote=0, amt=1 ));
27267
27268  if( amt>0 ){
27269    if( wrote<0 && pFile->lastErrno!=ENOSPC ){
27270      /* lastErrno set by seekAndWrite */
27271      return SQLITE_IOERR_WRITE;
27272    }else{
27273      pFile->lastErrno = 0; /* not a system error */
27274      return SQLITE_FULL;
27275    }
27276  }
27277
27278  return SQLITE_OK;
27279}
27280
27281#ifdef SQLITE_TEST
27282/*
27283** Count the number of fullsyncs and normal syncs.  This is used to test
27284** that syncs and fullsyncs are occurring at the right times.
27285*/
27286SQLITE_API int sqlite3_sync_count = 0;
27287SQLITE_API int sqlite3_fullsync_count = 0;
27288#endif
27289
27290/*
27291** We do not trust systems to provide a working fdatasync().  Some do.
27292** Others do no.  To be safe, we will stick with the (slightly slower)
27293** fsync(). If you know that your system does support fdatasync() correctly,
27294** then simply compile with -Dfdatasync=fdatasync
27295*/
27296#if !defined(fdatasync)
27297# define fdatasync fsync
27298#endif
27299
27300/*
27301** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
27302** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
27303** only available on Mac OS X.  But that could change.
27304*/
27305#ifdef F_FULLFSYNC
27306# define HAVE_FULLFSYNC 1
27307#else
27308# define HAVE_FULLFSYNC 0
27309#endif
27310
27311
27312/*
27313** The fsync() system call does not work as advertised on many
27314** unix systems.  The following procedure is an attempt to make
27315** it work better.
27316**
27317** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
27318** for testing when we want to run through the test suite quickly.
27319** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
27320** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
27321** or power failure will likely corrupt the database file.
27322**
27323** SQLite sets the dataOnly flag if the size of the file is unchanged.
27324** The idea behind dataOnly is that it should only write the file content
27325** to disk, not the inode.  We only set dataOnly if the file size is
27326** unchanged since the file size is part of the inode.  However,
27327** Ted Ts'o tells us that fdatasync() will also write the inode if the
27328** file size has changed.  The only real difference between fdatasync()
27329** and fsync(), Ted tells us, is that fdatasync() will not flush the
27330** inode if the mtime or owner or other inode attributes have changed.
27331** We only care about the file size, not the other file attributes, so
27332** as far as SQLite is concerned, an fdatasync() is always adequate.
27333** So, we always use fdatasync() if it is available, regardless of
27334** the value of the dataOnly flag.
27335*/
27336static int full_fsync(int fd, int fullSync, int dataOnly){
27337  int rc;
27338
27339  /* The following "ifdef/elif/else/" block has the same structure as
27340  ** the one below. It is replicated here solely to avoid cluttering
27341  ** up the real code with the UNUSED_PARAMETER() macros.
27342  */
27343#ifdef SQLITE_NO_SYNC
27344  UNUSED_PARAMETER(fd);
27345  UNUSED_PARAMETER(fullSync);
27346  UNUSED_PARAMETER(dataOnly);
27347#elif HAVE_FULLFSYNC
27348  UNUSED_PARAMETER(dataOnly);
27349#else
27350  UNUSED_PARAMETER(fullSync);
27351  UNUSED_PARAMETER(dataOnly);
27352#endif
27353
27354  /* Record the number of times that we do a normal fsync() and
27355  ** FULLSYNC.  This is used during testing to verify that this procedure
27356  ** gets called with the correct arguments.
27357  */
27358#ifdef SQLITE_TEST
27359  if( fullSync ) sqlite3_fullsync_count++;
27360  sqlite3_sync_count++;
27361#endif
27362
27363  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
27364  ** no-op
27365  */
27366#ifdef SQLITE_NO_SYNC
27367  rc = SQLITE_OK;
27368#elif HAVE_FULLFSYNC
27369  if( fullSync ){
27370    rc = osFcntl(fd, F_FULLFSYNC, 0);
27371  }else{
27372    rc = 1;
27373  }
27374  /* If the FULLFSYNC failed, fall back to attempting an fsync().
27375  ** It shouldn't be possible for fullfsync to fail on the local
27376  ** file system (on OSX), so failure indicates that FULLFSYNC
27377  ** isn't supported for this file system. So, attempt an fsync
27378  ** and (for now) ignore the overhead of a superfluous fcntl call.
27379  ** It'd be better to detect fullfsync support once and avoid
27380  ** the fcntl call every time sync is called.
27381  */
27382  if( rc ) rc = fsync(fd);
27383
27384#elif defined(__APPLE__)
27385  /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
27386  ** so currently we default to the macro that redefines fdatasync to fsync
27387  */
27388  rc = fsync(fd);
27389#else
27390  rc = fdatasync(fd);
27391#if OS_VXWORKS
27392  if( rc==-1 && errno==ENOTSUP ){
27393    rc = fsync(fd);
27394  }
27395#endif /* OS_VXWORKS */
27396#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
27397
27398  if( OS_VXWORKS && rc!= -1 ){
27399    rc = 0;
27400  }
27401  return rc;
27402}
27403
27404/*
27405** Open a file descriptor to the directory containing file zFilename.
27406** If successful, *pFd is set to the opened file descriptor and
27407** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
27408** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
27409** value.
27410**
27411** The directory file descriptor is used for only one thing - to
27412** fsync() a directory to make sure file creation and deletion events
27413** are flushed to disk.  Such fsyncs are not needed on newer
27414** journaling filesystems, but are required on older filesystems.
27415**
27416** This routine can be overridden using the xSetSysCall interface.
27417** The ability to override this routine was added in support of the
27418** chromium sandbox.  Opening a directory is a security risk (we are
27419** told) so making it overrideable allows the chromium sandbox to
27420** replace this routine with a harmless no-op.  To make this routine
27421** a no-op, replace it with a stub that returns SQLITE_OK but leaves
27422** *pFd set to a negative number.
27423**
27424** If SQLITE_OK is returned, the caller is responsible for closing
27425** the file descriptor *pFd using close().
27426*/
27427static int openDirectory(const char *zFilename, int *pFd){
27428  int ii;
27429  int fd = -1;
27430  char zDirname[MAX_PATHNAME+1];
27431
27432  sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
27433  for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
27434  if( ii>0 ){
27435    zDirname[ii] = '\0';
27436    fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
27437    if( fd>=0 ){
27438      OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
27439    }
27440  }
27441  *pFd = fd;
27442  return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
27443}
27444
27445/*
27446** Make sure all writes to a particular file are committed to disk.
27447**
27448** If dataOnly==0 then both the file itself and its metadata (file
27449** size, access time, etc) are synced.  If dataOnly!=0 then only the
27450** file data is synced.
27451**
27452** Under Unix, also make sure that the directory entry for the file
27453** has been created by fsync-ing the directory that contains the file.
27454** If we do not do this and we encounter a power failure, the directory
27455** entry for the journal might not exist after we reboot.  The next
27456** SQLite to access the file will not know that the journal exists (because
27457** the directory entry for the journal was never created) and the transaction
27458** will not roll back - possibly leading to database corruption.
27459*/
27460static int unixSync(sqlite3_file *id, int flags){
27461  int rc;
27462  unixFile *pFile = (unixFile*)id;
27463
27464  int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
27465  int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
27466
27467  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
27468  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
27469      || (flags&0x0F)==SQLITE_SYNC_FULL
27470  );
27471
27472  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
27473  ** line is to test that doing so does not cause any problems.
27474  */
27475  SimulateDiskfullError( return SQLITE_FULL );
27476
27477  assert( pFile );
27478  OSTRACE(("SYNC    %-3d\n", pFile->h));
27479  rc = full_fsync(pFile->h, isFullsync, isDataOnly);
27480  SimulateIOError( rc=1 );
27481  if( rc ){
27482    pFile->lastErrno = errno;
27483    return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
27484  }
27485
27486  /* Also fsync the directory containing the file if the DIRSYNC flag
27487  ** is set.  This is a one-time occurrence.  Many systems (examples: AIX)
27488  ** are unable to fsync a directory, so ignore errors on the fsync.
27489  */
27490  if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
27491    int dirfd;
27492    OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
27493            HAVE_FULLFSYNC, isFullsync));
27494    rc = osOpenDirectory(pFile->zPath, &dirfd);
27495    if( rc==SQLITE_OK && dirfd>=0 ){
27496      full_fsync(dirfd, 0, 0);
27497      robust_close(pFile, dirfd, __LINE__);
27498    }else if( rc==SQLITE_CANTOPEN ){
27499      rc = SQLITE_OK;
27500    }
27501    pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
27502  }
27503  return rc;
27504}
27505
27506/*
27507** Truncate an open file to a specified size
27508*/
27509static int unixTruncate(sqlite3_file *id, i64 nByte){
27510  unixFile *pFile = (unixFile *)id;
27511  int rc;
27512  assert( pFile );
27513  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
27514
27515  /* If the user has configured a chunk-size for this file, truncate the
27516  ** file so that it consists of an integer number of chunks (i.e. the
27517  ** actual file size after the operation may be larger than the requested
27518  ** size).
27519  */
27520  if( pFile->szChunk>0 ){
27521    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
27522  }
27523
27524  rc = robust_ftruncate(pFile->h, (off_t)nByte);
27525  if( rc ){
27526    pFile->lastErrno = errno;
27527    return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
27528  }else{
27529#ifdef SQLITE_DEBUG
27530    /* If we are doing a normal write to a database file (as opposed to
27531    ** doing a hot-journal rollback or a write to some file other than a
27532    ** normal database file) and we truncate the file to zero length,
27533    ** that effectively updates the change counter.  This might happen
27534    ** when restoring a database using the backup API from a zero-length
27535    ** source.
27536    */
27537    if( pFile->inNormalWrite && nByte==0 ){
27538      pFile->transCntrChng = 1;
27539    }
27540#endif
27541
27542#if SQLITE_MAX_MMAP_SIZE>0
27543    /* If the file was just truncated to a size smaller than the currently
27544    ** mapped region, reduce the effective mapping size as well. SQLite will
27545    ** use read() and write() to access data beyond this point from now on.
27546    */
27547    if( nByte<pFile->mmapSize ){
27548      pFile->mmapSize = nByte;
27549    }
27550#endif
27551
27552    return SQLITE_OK;
27553  }
27554}
27555
27556/*
27557** Determine the current size of a file in bytes
27558*/
27559static int unixFileSize(sqlite3_file *id, i64 *pSize){
27560  int rc;
27561  struct stat buf;
27562  assert( id );
27563  rc = osFstat(((unixFile*)id)->h, &buf);
27564  SimulateIOError( rc=1 );
27565  if( rc!=0 ){
27566    ((unixFile*)id)->lastErrno = errno;
27567    return SQLITE_IOERR_FSTAT;
27568  }
27569  *pSize = buf.st_size;
27570
27571  /* When opening a zero-size database, the findInodeInfo() procedure
27572  ** writes a single byte into that file in order to work around a bug
27573  ** in the OS-X msdos filesystem.  In order to avoid problems with upper
27574  ** layers, we need to report this file size as zero even though it is
27575  ** really 1.   Ticket #3260.
27576  */
27577  if( *pSize==1 ) *pSize = 0;
27578
27579
27580  return SQLITE_OK;
27581}
27582
27583#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27584/*
27585** Handler for proxy-locking file-control verbs.  Defined below in the
27586** proxying locking division.
27587*/
27588static int proxyFileControl(sqlite3_file*,int,void*);
27589#endif
27590
27591/*
27592** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
27593** file-control operation.  Enlarge the database to nBytes in size
27594** (rounded up to the next chunk-size).  If the database is already
27595** nBytes or larger, this routine is a no-op.
27596*/
27597static int fcntlSizeHint(unixFile *pFile, i64 nByte){
27598  if( pFile->szChunk>0 ){
27599    i64 nSize;                    /* Required file size */
27600    struct stat buf;              /* Used to hold return values of fstat() */
27601
27602    if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
27603
27604    nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
27605    if( nSize>(i64)buf.st_size ){
27606
27607#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
27608      /* The code below is handling the return value of osFallocate()
27609      ** correctly. posix_fallocate() is defined to "returns zero on success,
27610      ** or an error number on  failure". See the manpage for details. */
27611      int err;
27612      do{
27613        err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
27614      }while( err==EINTR );
27615      if( err ) return SQLITE_IOERR_WRITE;
27616#else
27617      /* If the OS does not have posix_fallocate(), fake it. First use
27618      ** ftruncate() to set the file size, then write a single byte to
27619      ** the last byte in each block within the extended region. This
27620      ** is the same technique used by glibc to implement posix_fallocate()
27621      ** on systems that do not have a real fallocate() system call.
27622      */
27623      int nBlk = buf.st_blksize;  /* File-system block size */
27624      i64 iWrite;                 /* Next offset to write to */
27625
27626      if( robust_ftruncate(pFile->h, nSize) ){
27627        pFile->lastErrno = errno;
27628        return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
27629      }
27630      iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
27631      while( iWrite<nSize ){
27632        int nWrite = seekAndWrite(pFile, iWrite, "", 1);
27633        if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
27634        iWrite += nBlk;
27635      }
27636#endif
27637    }
27638  }
27639
27640#if SQLITE_MAX_MMAP_SIZE>0
27641  if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
27642    int rc;
27643    if( pFile->szChunk<=0 ){
27644      if( robust_ftruncate(pFile->h, nByte) ){
27645        pFile->lastErrno = errno;
27646        return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
27647      }
27648    }
27649
27650    rc = unixMapfile(pFile, nByte);
27651    return rc;
27652  }
27653#endif
27654
27655  return SQLITE_OK;
27656}
27657
27658/*
27659** If *pArg is inititially negative then this is a query.  Set *pArg to
27660** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
27661**
27662** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
27663*/
27664static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
27665  if( *pArg<0 ){
27666    *pArg = (pFile->ctrlFlags & mask)!=0;
27667  }else if( (*pArg)==0 ){
27668    pFile->ctrlFlags &= ~mask;
27669  }else{
27670    pFile->ctrlFlags |= mask;
27671  }
27672}
27673
27674/* Forward declaration */
27675static int unixGetTempname(int nBuf, char *zBuf);
27676
27677/*
27678** Information and control of an open file handle.
27679*/
27680static int unixFileControl(sqlite3_file *id, int op, void *pArg){
27681  unixFile *pFile = (unixFile*)id;
27682  switch( op ){
27683    case SQLITE_FCNTL_LOCKSTATE: {
27684      *(int*)pArg = pFile->eFileLock;
27685      return SQLITE_OK;
27686    }
27687    case SQLITE_LAST_ERRNO: {
27688      *(int*)pArg = pFile->lastErrno;
27689      return SQLITE_OK;
27690    }
27691    case SQLITE_FCNTL_CHUNK_SIZE: {
27692      pFile->szChunk = *(int *)pArg;
27693      return SQLITE_OK;
27694    }
27695    case SQLITE_FCNTL_SIZE_HINT: {
27696      int rc;
27697      SimulateIOErrorBenign(1);
27698      rc = fcntlSizeHint(pFile, *(i64 *)pArg);
27699      SimulateIOErrorBenign(0);
27700      return rc;
27701    }
27702    case SQLITE_FCNTL_PERSIST_WAL: {
27703      unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
27704      return SQLITE_OK;
27705    }
27706    case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
27707      unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
27708      return SQLITE_OK;
27709    }
27710    case SQLITE_FCNTL_VFSNAME: {
27711      *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
27712      return SQLITE_OK;
27713    }
27714    case SQLITE_FCNTL_TEMPFILENAME: {
27715      char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
27716      if( zTFile ){
27717        unixGetTempname(pFile->pVfs->mxPathname, zTFile);
27718        *(char**)pArg = zTFile;
27719      }
27720      return SQLITE_OK;
27721    }
27722    case SQLITE_FCNTL_HAS_MOVED: {
27723      *(int*)pArg = fileHasMoved(pFile);
27724      return SQLITE_OK;
27725    }
27726#if SQLITE_MAX_MMAP_SIZE>0
27727    case SQLITE_FCNTL_MMAP_SIZE: {
27728      i64 newLimit = *(i64*)pArg;
27729      int rc = SQLITE_OK;
27730      if( newLimit>sqlite3GlobalConfig.mxMmap ){
27731        newLimit = sqlite3GlobalConfig.mxMmap;
27732      }
27733      *(i64*)pArg = pFile->mmapSizeMax;
27734      if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
27735        pFile->mmapSizeMax = newLimit;
27736        if( pFile->mmapSize>0 ){
27737          unixUnmapfile(pFile);
27738          rc = unixMapfile(pFile, -1);
27739        }
27740      }
27741      return rc;
27742    }
27743#endif
27744#ifdef SQLITE_DEBUG
27745    /* The pager calls this method to signal that it has done
27746    ** a rollback and that the database is therefore unchanged and
27747    ** it hence it is OK for the transaction change counter to be
27748    ** unchanged.
27749    */
27750    case SQLITE_FCNTL_DB_UNCHANGED: {
27751      ((unixFile*)id)->dbUpdate = 0;
27752      return SQLITE_OK;
27753    }
27754#endif
27755#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27756    case SQLITE_SET_LOCKPROXYFILE:
27757    case SQLITE_GET_LOCKPROXYFILE: {
27758      return proxyFileControl(id,op,pArg);
27759    }
27760#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
27761  }
27762  return SQLITE_NOTFOUND;
27763}
27764
27765/*
27766** Return the sector size in bytes of the underlying block device for
27767** the specified file. This is almost always 512 bytes, but may be
27768** larger for some devices.
27769**
27770** SQLite code assumes this function cannot fail. It also assumes that
27771** if two files are created in the same file-system directory (i.e.
27772** a database and its journal file) that the sector size will be the
27773** same for both.
27774*/
27775#ifndef __QNXNTO__
27776static int unixSectorSize(sqlite3_file *NotUsed){
27777  UNUSED_PARAMETER(NotUsed);
27778  return SQLITE_DEFAULT_SECTOR_SIZE;
27779}
27780#endif
27781
27782/*
27783** The following version of unixSectorSize() is optimized for QNX.
27784*/
27785#ifdef __QNXNTO__
27786#include <sys/dcmd_blk.h>
27787#include <sys/statvfs.h>
27788static int unixSectorSize(sqlite3_file *id){
27789  unixFile *pFile = (unixFile*)id;
27790  if( pFile->sectorSize == 0 ){
27791    struct statvfs fsInfo;
27792
27793    /* Set defaults for non-supported filesystems */
27794    pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
27795    pFile->deviceCharacteristics = 0;
27796    if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
27797      return pFile->sectorSize;
27798    }
27799
27800    if( !strcmp(fsInfo.f_basetype, "tmp") ) {
27801      pFile->sectorSize = fsInfo.f_bsize;
27802      pFile->deviceCharacteristics =
27803        SQLITE_IOCAP_ATOMIC4K |       /* All ram filesystem writes are atomic */
27804        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
27805                                      ** the write succeeds */
27806        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
27807                                      ** so it is ordered */
27808        0;
27809    }else if( strstr(fsInfo.f_basetype, "etfs") ){
27810      pFile->sectorSize = fsInfo.f_bsize;
27811      pFile->deviceCharacteristics =
27812        /* etfs cluster size writes are atomic */
27813        (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
27814        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
27815                                      ** the write succeeds */
27816        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
27817                                      ** so it is ordered */
27818        0;
27819    }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
27820      pFile->sectorSize = fsInfo.f_bsize;
27821      pFile->deviceCharacteristics =
27822        SQLITE_IOCAP_ATOMIC |         /* All filesystem writes are atomic */
27823        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
27824                                      ** the write succeeds */
27825        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
27826                                      ** so it is ordered */
27827        0;
27828    }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
27829      pFile->sectorSize = fsInfo.f_bsize;
27830      pFile->deviceCharacteristics =
27831        /* full bitset of atomics from max sector size and smaller */
27832        ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
27833        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
27834                                      ** so it is ordered */
27835        0;
27836    }else if( strstr(fsInfo.f_basetype, "dos") ){
27837      pFile->sectorSize = fsInfo.f_bsize;
27838      pFile->deviceCharacteristics =
27839        /* full bitset of atomics from max sector size and smaller */
27840        ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
27841        SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
27842                                      ** so it is ordered */
27843        0;
27844    }else{
27845      pFile->deviceCharacteristics =
27846        SQLITE_IOCAP_ATOMIC512 |      /* blocks are atomic */
27847        SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
27848                                      ** the write succeeds */
27849        0;
27850    }
27851  }
27852  /* Last chance verification.  If the sector size isn't a multiple of 512
27853  ** then it isn't valid.*/
27854  if( pFile->sectorSize % 512 != 0 ){
27855    pFile->deviceCharacteristics = 0;
27856    pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
27857  }
27858  return pFile->sectorSize;
27859}
27860#endif /* __QNXNTO__ */
27861
27862/*
27863** Return the device characteristics for the file.
27864**
27865** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
27866** However, that choice is contraversial since technically the underlying
27867** file system does not always provide powersafe overwrites.  (In other
27868** words, after a power-loss event, parts of the file that were never
27869** written might end up being altered.)  However, non-PSOW behavior is very,
27870** very rare.  And asserting PSOW makes a large reduction in the amount
27871** of required I/O for journaling, since a lot of padding is eliminated.
27872**  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
27873** available to turn it off and URI query parameter available to turn it off.
27874*/
27875static int unixDeviceCharacteristics(sqlite3_file *id){
27876  unixFile *p = (unixFile*)id;
27877  int rc = 0;
27878#ifdef __QNXNTO__
27879  if( p->sectorSize==0 ) unixSectorSize(id);
27880  rc = p->deviceCharacteristics;
27881#endif
27882  if( p->ctrlFlags & UNIXFILE_PSOW ){
27883    rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
27884  }
27885  return rc;
27886}
27887
27888#ifndef SQLITE_OMIT_WAL
27889
27890
27891/*
27892** Object used to represent an shared memory buffer.
27893**
27894** When multiple threads all reference the same wal-index, each thread
27895** has its own unixShm object, but they all point to a single instance
27896** of this unixShmNode object.  In other words, each wal-index is opened
27897** only once per process.
27898**
27899** Each unixShmNode object is connected to a single unixInodeInfo object.
27900** We could coalesce this object into unixInodeInfo, but that would mean
27901** every open file that does not use shared memory (in other words, most
27902** open files) would have to carry around this extra information.  So
27903** the unixInodeInfo object contains a pointer to this unixShmNode object
27904** and the unixShmNode object is created only when needed.
27905**
27906** unixMutexHeld() must be true when creating or destroying
27907** this object or while reading or writing the following fields:
27908**
27909**      nRef
27910**
27911** The following fields are read-only after the object is created:
27912**
27913**      fid
27914**      zFilename
27915**
27916** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
27917** unixMutexHeld() is true when reading or writing any other field
27918** in this structure.
27919*/
27920struct unixShmNode {
27921  unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
27922  sqlite3_mutex *mutex;      /* Mutex to access this object */
27923  char *zFilename;           /* Name of the mmapped file */
27924  int h;                     /* Open file descriptor */
27925  int szRegion;              /* Size of shared-memory regions */
27926  u16 nRegion;               /* Size of array apRegion */
27927  u8 isReadonly;             /* True if read-only */
27928  char **apRegion;           /* Array of mapped shared-memory regions */
27929  int nRef;                  /* Number of unixShm objects pointing to this */
27930  unixShm *pFirst;           /* All unixShm objects pointing to this */
27931#ifdef SQLITE_DEBUG
27932  u8 exclMask;               /* Mask of exclusive locks held */
27933  u8 sharedMask;             /* Mask of shared locks held */
27934  u8 nextShmId;              /* Next available unixShm.id value */
27935#endif
27936};
27937
27938/*
27939** Structure used internally by this VFS to record the state of an
27940** open shared memory connection.
27941**
27942** The following fields are initialized when this object is created and
27943** are read-only thereafter:
27944**
27945**    unixShm.pFile
27946**    unixShm.id
27947**
27948** All other fields are read/write.  The unixShm.pFile->mutex must be held
27949** while accessing any read/write fields.
27950*/
27951struct unixShm {
27952  unixShmNode *pShmNode;     /* The underlying unixShmNode object */
27953  unixShm *pNext;            /* Next unixShm with the same unixShmNode */
27954  u8 hasMutex;               /* True if holding the unixShmNode mutex */
27955  u8 id;                     /* Id of this connection within its unixShmNode */
27956  u16 sharedMask;            /* Mask of shared locks held */
27957  u16 exclMask;              /* Mask of exclusive locks held */
27958};
27959
27960/*
27961** Constants used for locking
27962*/
27963#define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
27964#define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
27965
27966/*
27967** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
27968**
27969** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
27970** otherwise.
27971*/
27972static int unixShmSystemLock(
27973  unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
27974  int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
27975  int ofst,              /* First byte of the locking range */
27976  int n                  /* Number of bytes to lock */
27977){
27978  struct flock f;       /* The posix advisory locking structure */
27979  int rc = SQLITE_OK;   /* Result code form fcntl() */
27980
27981  /* Access to the unixShmNode object is serialized by the caller */
27982  assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
27983
27984  /* Shared locks never span more than one byte */
27985  assert( n==1 || lockType!=F_RDLCK );
27986
27987  /* Locks are within range */
27988  assert( n>=1 && n<SQLITE_SHM_NLOCK );
27989
27990  if( pShmNode->h>=0 ){
27991    /* Initialize the locking parameters */
27992    memset(&f, 0, sizeof(f));
27993    f.l_type = lockType;
27994    f.l_whence = SEEK_SET;
27995    f.l_start = ofst;
27996    f.l_len = n;
27997
27998    rc = osFcntl(pShmNode->h, F_SETLK, &f);
27999    rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
28000  }
28001
28002  /* Update the global lock state and do debug tracing */
28003#ifdef SQLITE_DEBUG
28004  { u16 mask;
28005  OSTRACE(("SHM-LOCK "));
28006  mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
28007  if( rc==SQLITE_OK ){
28008    if( lockType==F_UNLCK ){
28009      OSTRACE(("unlock %d ok", ofst));
28010      pShmNode->exclMask &= ~mask;
28011      pShmNode->sharedMask &= ~mask;
28012    }else if( lockType==F_RDLCK ){
28013      OSTRACE(("read-lock %d ok", ofst));
28014      pShmNode->exclMask &= ~mask;
28015      pShmNode->sharedMask |= mask;
28016    }else{
28017      assert( lockType==F_WRLCK );
28018      OSTRACE(("write-lock %d ok", ofst));
28019      pShmNode->exclMask |= mask;
28020      pShmNode->sharedMask &= ~mask;
28021    }
28022  }else{
28023    if( lockType==F_UNLCK ){
28024      OSTRACE(("unlock %d failed", ofst));
28025    }else if( lockType==F_RDLCK ){
28026      OSTRACE(("read-lock failed"));
28027    }else{
28028      assert( lockType==F_WRLCK );
28029      OSTRACE(("write-lock %d failed", ofst));
28030    }
28031  }
28032  OSTRACE((" - afterwards %03x,%03x\n",
28033           pShmNode->sharedMask, pShmNode->exclMask));
28034  }
28035#endif
28036
28037  return rc;
28038}
28039
28040/*
28041** Return the system page size.
28042**
28043** This function should not be called directly by other code in this file.
28044** Instead, it should be called via macro osGetpagesize().
28045*/
28046static int unixGetpagesize(void){
28047#if defined(_BSD_SOURCE)
28048  return getpagesize();
28049#else
28050  return (int)sysconf(_SC_PAGESIZE);
28051#endif
28052}
28053
28054/*
28055** Return the minimum number of 32KB shm regions that should be mapped at
28056** a time, assuming that each mapping must be an integer multiple of the
28057** current system page-size.
28058**
28059** Usually, this is 1. The exception seems to be systems that are configured
28060** to use 64KB pages - in this case each mapping must cover at least two
28061** shm regions.
28062*/
28063static int unixShmRegionPerMap(void){
28064  int shmsz = 32*1024;            /* SHM region size */
28065  int pgsz = osGetpagesize();   /* System page size */
28066  assert( ((pgsz-1)&pgsz)==0 );   /* Page size must be a power of 2 */
28067  if( pgsz<shmsz ) return 1;
28068  return pgsz/shmsz;
28069}
28070
28071/*
28072** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
28073**
28074** This is not a VFS shared-memory method; it is a utility function called
28075** by VFS shared-memory methods.
28076*/
28077static void unixShmPurge(unixFile *pFd){
28078  unixShmNode *p = pFd->pInode->pShmNode;
28079  assert( unixMutexHeld() );
28080  if( p && p->nRef==0 ){
28081    int nShmPerMap = unixShmRegionPerMap();
28082    int i;
28083    assert( p->pInode==pFd->pInode );
28084    sqlite3_mutex_free(p->mutex);
28085    for(i=0; i<p->nRegion; i+=nShmPerMap){
28086      if( p->h>=0 ){
28087        osMunmap(p->apRegion[i], p->szRegion);
28088      }else{
28089        sqlite3_free(p->apRegion[i]);
28090      }
28091    }
28092    sqlite3_free(p->apRegion);
28093    if( p->h>=0 ){
28094      robust_close(pFd, p->h, __LINE__);
28095      p->h = -1;
28096    }
28097    p->pInode->pShmNode = 0;
28098    sqlite3_free(p);
28099  }
28100}
28101
28102/*
28103** Open a shared-memory area associated with open database file pDbFd.
28104** This particular implementation uses mmapped files.
28105**
28106** The file used to implement shared-memory is in the same directory
28107** as the open database file and has the same name as the open database
28108** file with the "-shm" suffix added.  For example, if the database file
28109** is "/home/user1/config.db" then the file that is created and mmapped
28110** for shared memory will be called "/home/user1/config.db-shm".
28111**
28112** Another approach to is to use files in /dev/shm or /dev/tmp or an
28113** some other tmpfs mount. But if a file in a different directory
28114** from the database file is used, then differing access permissions
28115** or a chroot() might cause two different processes on the same
28116** database to end up using different files for shared memory -
28117** meaning that their memory would not really be shared - resulting
28118** in database corruption.  Nevertheless, this tmpfs file usage
28119** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
28120** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
28121** option results in an incompatible build of SQLite;  builds of SQLite
28122** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
28123** same database file at the same time, database corruption will likely
28124** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
28125** "unsupported" and may go away in a future SQLite release.
28126**
28127** When opening a new shared-memory file, if no other instances of that
28128** file are currently open, in this process or in other processes, then
28129** the file must be truncated to zero length or have its header cleared.
28130**
28131** If the original database file (pDbFd) is using the "unix-excl" VFS
28132** that means that an exclusive lock is held on the database file and
28133** that no other processes are able to read or write the database.  In
28134** that case, we do not really need shared memory.  No shared memory
28135** file is created.  The shared memory will be simulated with heap memory.
28136*/
28137static int unixOpenSharedMemory(unixFile *pDbFd){
28138  struct unixShm *p = 0;          /* The connection to be opened */
28139  struct unixShmNode *pShmNode;   /* The underlying mmapped file */
28140  int rc;                         /* Result code */
28141  unixInodeInfo *pInode;          /* The inode of fd */
28142  char *zShmFilename;             /* Name of the file used for SHM */
28143  int nShmFilename;               /* Size of the SHM filename in bytes */
28144
28145  /* Allocate space for the new unixShm object. */
28146  p = sqlite3_malloc( sizeof(*p) );
28147  if( p==0 ) return SQLITE_NOMEM;
28148  memset(p, 0, sizeof(*p));
28149  assert( pDbFd->pShm==0 );
28150
28151  /* Check to see if a unixShmNode object already exists. Reuse an existing
28152  ** one if present. Create a new one if necessary.
28153  */
28154  unixEnterMutex();
28155  pInode = pDbFd->pInode;
28156  pShmNode = pInode->pShmNode;
28157  if( pShmNode==0 ){
28158    struct stat sStat;                 /* fstat() info for database file */
28159
28160    /* Call fstat() to figure out the permissions on the database file. If
28161    ** a new *-shm file is created, an attempt will be made to create it
28162    ** with the same permissions.
28163    */
28164    if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
28165      rc = SQLITE_IOERR_FSTAT;
28166      goto shm_open_err;
28167    }
28168
28169#ifdef SQLITE_SHM_DIRECTORY
28170    nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
28171#else
28172    nShmFilename = 6 + (int)strlen(pDbFd->zPath);
28173#endif
28174    pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
28175    if( pShmNode==0 ){
28176      rc = SQLITE_NOMEM;
28177      goto shm_open_err;
28178    }
28179    memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
28180    zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
28181#ifdef SQLITE_SHM_DIRECTORY
28182    sqlite3_snprintf(nShmFilename, zShmFilename,
28183                     SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
28184                     (u32)sStat.st_ino, (u32)sStat.st_dev);
28185#else
28186    sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
28187    sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
28188#endif
28189    pShmNode->h = -1;
28190    pDbFd->pInode->pShmNode = pShmNode;
28191    pShmNode->pInode = pDbFd->pInode;
28192    pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
28193    if( pShmNode->mutex==0 ){
28194      rc = SQLITE_NOMEM;
28195      goto shm_open_err;
28196    }
28197
28198    if( pInode->bProcessLock==0 ){
28199      int openFlags = O_RDWR | O_CREAT;
28200      if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
28201        openFlags = O_RDONLY;
28202        pShmNode->isReadonly = 1;
28203      }
28204      pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
28205      if( pShmNode->h<0 ){
28206        rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
28207        goto shm_open_err;
28208      }
28209
28210      /* If this process is running as root, make sure that the SHM file
28211      ** is owned by the same user that owns the original database.  Otherwise,
28212      ** the original owner will not be able to connect.
28213      */
28214      osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
28215
28216      /* Check to see if another process is holding the dead-man switch.
28217      ** If not, truncate the file to zero length.
28218      */
28219      rc = SQLITE_OK;
28220      if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
28221        if( robust_ftruncate(pShmNode->h, 0) ){
28222          rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
28223        }
28224      }
28225      if( rc==SQLITE_OK ){
28226        rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
28227      }
28228      if( rc ) goto shm_open_err;
28229    }
28230  }
28231
28232  /* Make the new connection a child of the unixShmNode */
28233  p->pShmNode = pShmNode;
28234#ifdef SQLITE_DEBUG
28235  p->id = pShmNode->nextShmId++;
28236#endif
28237  pShmNode->nRef++;
28238  pDbFd->pShm = p;
28239  unixLeaveMutex();
28240
28241  /* The reference count on pShmNode has already been incremented under
28242  ** the cover of the unixEnterMutex() mutex and the pointer from the
28243  ** new (struct unixShm) object to the pShmNode has been set. All that is
28244  ** left to do is to link the new object into the linked list starting
28245  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
28246  ** mutex.
28247  */
28248  sqlite3_mutex_enter(pShmNode->mutex);
28249  p->pNext = pShmNode->pFirst;
28250  pShmNode->pFirst = p;
28251  sqlite3_mutex_leave(pShmNode->mutex);
28252  return SQLITE_OK;
28253
28254  /* Jump here on any error */
28255shm_open_err:
28256  unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
28257  sqlite3_free(p);
28258  unixLeaveMutex();
28259  return rc;
28260}
28261
28262/*
28263** This function is called to obtain a pointer to region iRegion of the
28264** shared-memory associated with the database file fd. Shared-memory regions
28265** are numbered starting from zero. Each shared-memory region is szRegion
28266** bytes in size.
28267**
28268** If an error occurs, an error code is returned and *pp is set to NULL.
28269**
28270** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
28271** region has not been allocated (by any client, including one running in a
28272** separate process), then *pp is set to NULL and SQLITE_OK returned. If
28273** bExtend is non-zero and the requested shared-memory region has not yet
28274** been allocated, it is allocated by this function.
28275**
28276** If the shared-memory region has already been allocated or is allocated by
28277** this call as described above, then it is mapped into this processes
28278** address space (if it is not already), *pp is set to point to the mapped
28279** memory and SQLITE_OK returned.
28280*/
28281static int unixShmMap(
28282  sqlite3_file *fd,               /* Handle open on database file */
28283  int iRegion,                    /* Region to retrieve */
28284  int szRegion,                   /* Size of regions */
28285  int bExtend,                    /* True to extend file if necessary */
28286  void volatile **pp              /* OUT: Mapped memory */
28287){
28288  unixFile *pDbFd = (unixFile*)fd;
28289  unixShm *p;
28290  unixShmNode *pShmNode;
28291  int rc = SQLITE_OK;
28292  int nShmPerMap = unixShmRegionPerMap();
28293  int nReqRegion;
28294
28295  /* If the shared-memory file has not yet been opened, open it now. */
28296  if( pDbFd->pShm==0 ){
28297    rc = unixOpenSharedMemory(pDbFd);
28298    if( rc!=SQLITE_OK ) return rc;
28299  }
28300
28301  p = pDbFd->pShm;
28302  pShmNode = p->pShmNode;
28303  sqlite3_mutex_enter(pShmNode->mutex);
28304  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
28305  assert( pShmNode->pInode==pDbFd->pInode );
28306  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
28307  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
28308
28309  /* Minimum number of regions required to be mapped. */
28310  nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
28311
28312  if( pShmNode->nRegion<nReqRegion ){
28313    char **apNew;                      /* New apRegion[] array */
28314    int nByte = nReqRegion*szRegion;   /* Minimum required file size */
28315    struct stat sStat;                 /* Used by fstat() */
28316
28317    pShmNode->szRegion = szRegion;
28318
28319    if( pShmNode->h>=0 ){
28320      /* The requested region is not mapped into this processes address space.
28321      ** Check to see if it has been allocated (i.e. if the wal-index file is
28322      ** large enough to contain the requested region).
28323      */
28324      if( osFstat(pShmNode->h, &sStat) ){
28325        rc = SQLITE_IOERR_SHMSIZE;
28326        goto shmpage_out;
28327      }
28328
28329      if( sStat.st_size<nByte ){
28330        /* The requested memory region does not exist. If bExtend is set to
28331        ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
28332        */
28333        if( !bExtend ){
28334          goto shmpage_out;
28335        }
28336
28337        /* Alternatively, if bExtend is true, extend the file. Do this by
28338        ** writing a single byte to the end of each (OS) page being
28339        ** allocated or extended. Technically, we need only write to the
28340        ** last page in order to extend the file. But writing to all new
28341        ** pages forces the OS to allocate them immediately, which reduces
28342        ** the chances of SIGBUS while accessing the mapped region later on.
28343        */
28344        else{
28345          static const int pgsz = 4096;
28346          int iPg;
28347
28348          /* Write to the last byte of each newly allocated or extended page */
28349          assert( (nByte % pgsz)==0 );
28350          for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
28351            if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
28352              const char *zFile = pShmNode->zFilename;
28353              rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
28354              goto shmpage_out;
28355            }
28356          }
28357        }
28358      }
28359    }
28360
28361    /* Map the requested memory region into this processes address space. */
28362    apNew = (char **)sqlite3_realloc(
28363        pShmNode->apRegion, nReqRegion*sizeof(char *)
28364    );
28365    if( !apNew ){
28366      rc = SQLITE_IOERR_NOMEM;
28367      goto shmpage_out;
28368    }
28369    pShmNode->apRegion = apNew;
28370    while( pShmNode->nRegion<nReqRegion ){
28371      int nMap = szRegion*nShmPerMap;
28372      int i;
28373      void *pMem;
28374      if( pShmNode->h>=0 ){
28375        pMem = osMmap(0, nMap,
28376            pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
28377            MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
28378        );
28379        if( pMem==MAP_FAILED ){
28380          rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
28381          goto shmpage_out;
28382        }
28383      }else{
28384        pMem = sqlite3_malloc(szRegion);
28385        if( pMem==0 ){
28386          rc = SQLITE_NOMEM;
28387          goto shmpage_out;
28388        }
28389        memset(pMem, 0, szRegion);
28390      }
28391
28392      for(i=0; i<nShmPerMap; i++){
28393        pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
28394      }
28395      pShmNode->nRegion += nShmPerMap;
28396    }
28397  }
28398
28399shmpage_out:
28400  if( pShmNode->nRegion>iRegion ){
28401    *pp = pShmNode->apRegion[iRegion];
28402  }else{
28403    *pp = 0;
28404  }
28405  if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
28406  sqlite3_mutex_leave(pShmNode->mutex);
28407  return rc;
28408}
28409
28410/*
28411** Change the lock state for a shared-memory segment.
28412**
28413** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
28414** different here than in posix.  In xShmLock(), one can go from unlocked
28415** to shared and back or from unlocked to exclusive and back.  But one may
28416** not go from shared to exclusive or from exclusive to shared.
28417*/
28418static int unixShmLock(
28419  sqlite3_file *fd,          /* Database file holding the shared memory */
28420  int ofst,                  /* First lock to acquire or release */
28421  int n,                     /* Number of locks to acquire or release */
28422  int flags                  /* What to do with the lock */
28423){
28424  unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
28425  unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
28426  unixShm *pX;                          /* For looping over all siblings */
28427  unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
28428  int rc = SQLITE_OK;                   /* Result code */
28429  u16 mask;                             /* Mask of locks to take or release */
28430
28431  assert( pShmNode==pDbFd->pInode->pShmNode );
28432  assert( pShmNode->pInode==pDbFd->pInode );
28433  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
28434  assert( n>=1 );
28435  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
28436       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
28437       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
28438       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
28439  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
28440  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
28441  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
28442
28443  mask = (1<<(ofst+n)) - (1<<ofst);
28444  assert( n>1 || mask==(1<<ofst) );
28445  sqlite3_mutex_enter(pShmNode->mutex);
28446  if( flags & SQLITE_SHM_UNLOCK ){
28447    u16 allMask = 0; /* Mask of locks held by siblings */
28448
28449    /* See if any siblings hold this same lock */
28450    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
28451      if( pX==p ) continue;
28452      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
28453      allMask |= pX->sharedMask;
28454    }
28455
28456    /* Unlock the system-level locks */
28457    if( (mask & allMask)==0 ){
28458      rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
28459    }else{
28460      rc = SQLITE_OK;
28461    }
28462
28463    /* Undo the local locks */
28464    if( rc==SQLITE_OK ){
28465      p->exclMask &= ~mask;
28466      p->sharedMask &= ~mask;
28467    }
28468  }else if( flags & SQLITE_SHM_SHARED ){
28469    u16 allShared = 0;  /* Union of locks held by connections other than "p" */
28470
28471    /* Find out which shared locks are already held by sibling connections.
28472    ** If any sibling already holds an exclusive lock, go ahead and return
28473    ** SQLITE_BUSY.
28474    */
28475    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
28476      if( (pX->exclMask & mask)!=0 ){
28477        rc = SQLITE_BUSY;
28478        break;
28479      }
28480      allShared |= pX->sharedMask;
28481    }
28482
28483    /* Get shared locks at the system level, if necessary */
28484    if( rc==SQLITE_OK ){
28485      if( (allShared & mask)==0 ){
28486        rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
28487      }else{
28488        rc = SQLITE_OK;
28489      }
28490    }
28491
28492    /* Get the local shared locks */
28493    if( rc==SQLITE_OK ){
28494      p->sharedMask |= mask;
28495    }
28496  }else{
28497    /* Make sure no sibling connections hold locks that will block this
28498    ** lock.  If any do, return SQLITE_BUSY right away.
28499    */
28500    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
28501      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
28502        rc = SQLITE_BUSY;
28503        break;
28504      }
28505    }
28506
28507    /* Get the exclusive locks at the system level.  Then if successful
28508    ** also mark the local connection as being locked.
28509    */
28510    if( rc==SQLITE_OK ){
28511      rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
28512      if( rc==SQLITE_OK ){
28513        assert( (p->sharedMask & mask)==0 );
28514        p->exclMask |= mask;
28515      }
28516    }
28517  }
28518  sqlite3_mutex_leave(pShmNode->mutex);
28519  OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
28520           p->id, getpid(), p->sharedMask, p->exclMask));
28521  return rc;
28522}
28523
28524/*
28525** Implement a memory barrier or memory fence on shared memory.
28526**
28527** All loads and stores begun before the barrier must complete before
28528** any load or store begun after the barrier.
28529*/
28530static void unixShmBarrier(
28531  sqlite3_file *fd                /* Database file holding the shared memory */
28532){
28533  UNUSED_PARAMETER(fd);
28534  unixEnterMutex();
28535  unixLeaveMutex();
28536}
28537
28538/*
28539** Close a connection to shared-memory.  Delete the underlying
28540** storage if deleteFlag is true.
28541**
28542** If there is no shared memory associated with the connection then this
28543** routine is a harmless no-op.
28544*/
28545static int unixShmUnmap(
28546  sqlite3_file *fd,               /* The underlying database file */
28547  int deleteFlag                  /* Delete shared-memory if true */
28548){
28549  unixShm *p;                     /* The connection to be closed */
28550  unixShmNode *pShmNode;          /* The underlying shared-memory file */
28551  unixShm **pp;                   /* For looping over sibling connections */
28552  unixFile *pDbFd;                /* The underlying database file */
28553
28554  pDbFd = (unixFile*)fd;
28555  p = pDbFd->pShm;
28556  if( p==0 ) return SQLITE_OK;
28557  pShmNode = p->pShmNode;
28558
28559  assert( pShmNode==pDbFd->pInode->pShmNode );
28560  assert( pShmNode->pInode==pDbFd->pInode );
28561
28562  /* Remove connection p from the set of connections associated
28563  ** with pShmNode */
28564  sqlite3_mutex_enter(pShmNode->mutex);
28565  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
28566  *pp = p->pNext;
28567
28568  /* Free the connection p */
28569  sqlite3_free(p);
28570  pDbFd->pShm = 0;
28571  sqlite3_mutex_leave(pShmNode->mutex);
28572
28573  /* If pShmNode->nRef has reached 0, then close the underlying
28574  ** shared-memory file, too */
28575  unixEnterMutex();
28576  assert( pShmNode->nRef>0 );
28577  pShmNode->nRef--;
28578  if( pShmNode->nRef==0 ){
28579    if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
28580    unixShmPurge(pDbFd);
28581  }
28582  unixLeaveMutex();
28583
28584  return SQLITE_OK;
28585}
28586
28587
28588#else
28589# define unixShmMap     0
28590# define unixShmLock    0
28591# define unixShmBarrier 0
28592# define unixShmUnmap   0
28593#endif /* #ifndef SQLITE_OMIT_WAL */
28594
28595#if SQLITE_MAX_MMAP_SIZE>0
28596/*
28597** If it is currently memory mapped, unmap file pFd.
28598*/
28599static void unixUnmapfile(unixFile *pFd){
28600  assert( pFd->nFetchOut==0 );
28601  if( pFd->pMapRegion ){
28602    osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
28603    pFd->pMapRegion = 0;
28604    pFd->mmapSize = 0;
28605    pFd->mmapSizeActual = 0;
28606  }
28607}
28608
28609/*
28610** Attempt to set the size of the memory mapping maintained by file
28611** descriptor pFd to nNew bytes. Any existing mapping is discarded.
28612**
28613** If successful, this function sets the following variables:
28614**
28615**       unixFile.pMapRegion
28616**       unixFile.mmapSize
28617**       unixFile.mmapSizeActual
28618**
28619** If unsuccessful, an error message is logged via sqlite3_log() and
28620** the three variables above are zeroed. In this case SQLite should
28621** continue accessing the database using the xRead() and xWrite()
28622** methods.
28623*/
28624static void unixRemapfile(
28625  unixFile *pFd,                  /* File descriptor object */
28626  i64 nNew                        /* Required mapping size */
28627){
28628  const char *zErr = "mmap";
28629  int h = pFd->h;                      /* File descriptor open on db file */
28630  u8 *pOrig = (u8 *)pFd->pMapRegion;   /* Pointer to current file mapping */
28631  i64 nOrig = pFd->mmapSizeActual;     /* Size of pOrig region in bytes */
28632  u8 *pNew = 0;                        /* Location of new mapping */
28633  int flags = PROT_READ;               /* Flags to pass to mmap() */
28634
28635  assert( pFd->nFetchOut==0 );
28636  assert( nNew>pFd->mmapSize );
28637  assert( nNew<=pFd->mmapSizeMax );
28638  assert( nNew>0 );
28639  assert( pFd->mmapSizeActual>=pFd->mmapSize );
28640  assert( MAP_FAILED!=0 );
28641
28642  if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
28643
28644  if( pOrig ){
28645#if HAVE_MREMAP
28646    i64 nReuse = pFd->mmapSize;
28647#else
28648    const int szSyspage = osGetpagesize();
28649    i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
28650#endif
28651    u8 *pReq = &pOrig[nReuse];
28652
28653    /* Unmap any pages of the existing mapping that cannot be reused. */
28654    if( nReuse!=nOrig ){
28655      osMunmap(pReq, nOrig-nReuse);
28656    }
28657
28658#if HAVE_MREMAP
28659    pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
28660    zErr = "mremap";
28661#else
28662    pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
28663    if( pNew!=MAP_FAILED ){
28664      if( pNew!=pReq ){
28665        osMunmap(pNew, nNew - nReuse);
28666        pNew = 0;
28667      }else{
28668        pNew = pOrig;
28669      }
28670    }
28671#endif
28672
28673    /* The attempt to extend the existing mapping failed. Free it. */
28674    if( pNew==MAP_FAILED || pNew==0 ){
28675      osMunmap(pOrig, nReuse);
28676    }
28677  }
28678
28679  /* If pNew is still NULL, try to create an entirely new mapping. */
28680  if( pNew==0 ){
28681    pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
28682  }
28683
28684  if( pNew==MAP_FAILED ){
28685    pNew = 0;
28686    nNew = 0;
28687    unixLogError(SQLITE_OK, zErr, pFd->zPath);
28688
28689    /* If the mmap() above failed, assume that all subsequent mmap() calls
28690    ** will probably fail too. Fall back to using xRead/xWrite exclusively
28691    ** in this case.  */
28692    pFd->mmapSizeMax = 0;
28693  }
28694  pFd->pMapRegion = (void *)pNew;
28695  pFd->mmapSize = pFd->mmapSizeActual = nNew;
28696}
28697
28698/*
28699** Memory map or remap the file opened by file-descriptor pFd (if the file
28700** is already mapped, the existing mapping is replaced by the new). Or, if
28701** there already exists a mapping for this file, and there are still
28702** outstanding xFetch() references to it, this function is a no-op.
28703**
28704** If parameter nByte is non-negative, then it is the requested size of
28705** the mapping to create. Otherwise, if nByte is less than zero, then the
28706** requested size is the size of the file on disk. The actual size of the
28707** created mapping is either the requested size or the value configured
28708** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
28709**
28710** SQLITE_OK is returned if no error occurs (even if the mapping is not
28711** recreated as a result of outstanding references) or an SQLite error
28712** code otherwise.
28713*/
28714static int unixMapfile(unixFile *pFd, i64 nByte){
28715  i64 nMap = nByte;
28716  int rc;
28717
28718  assert( nMap>=0 || pFd->nFetchOut==0 );
28719  if( pFd->nFetchOut>0 ) return SQLITE_OK;
28720
28721  if( nMap<0 ){
28722    struct stat statbuf;          /* Low-level file information */
28723    rc = osFstat(pFd->h, &statbuf);
28724    if( rc!=SQLITE_OK ){
28725      return SQLITE_IOERR_FSTAT;
28726    }
28727    nMap = statbuf.st_size;
28728  }
28729  if( nMap>pFd->mmapSizeMax ){
28730    nMap = pFd->mmapSizeMax;
28731  }
28732
28733  if( nMap!=pFd->mmapSize ){
28734    if( nMap>0 ){
28735      unixRemapfile(pFd, nMap);
28736    }else{
28737      unixUnmapfile(pFd);
28738    }
28739  }
28740
28741  return SQLITE_OK;
28742}
28743#endif /* SQLITE_MAX_MMAP_SIZE>0 */
28744
28745/*
28746** If possible, return a pointer to a mapping of file fd starting at offset
28747** iOff. The mapping must be valid for at least nAmt bytes.
28748**
28749** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
28750** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
28751** Finally, if an error does occur, return an SQLite error code. The final
28752** value of *pp is undefined in this case.
28753**
28754** If this function does return a pointer, the caller must eventually
28755** release the reference by calling unixUnfetch().
28756*/
28757static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
28758#if SQLITE_MAX_MMAP_SIZE>0
28759  unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
28760#endif
28761  *pp = 0;
28762
28763#if SQLITE_MAX_MMAP_SIZE>0
28764  if( pFd->mmapSizeMax>0 ){
28765    if( pFd->pMapRegion==0 ){
28766      int rc = unixMapfile(pFd, -1);
28767      if( rc!=SQLITE_OK ) return rc;
28768    }
28769    if( pFd->mmapSize >= iOff+nAmt ){
28770      *pp = &((u8 *)pFd->pMapRegion)[iOff];
28771      pFd->nFetchOut++;
28772    }
28773  }
28774#endif
28775  return SQLITE_OK;
28776}
28777
28778/*
28779** If the third argument is non-NULL, then this function releases a
28780** reference obtained by an earlier call to unixFetch(). The second
28781** argument passed to this function must be the same as the corresponding
28782** argument that was passed to the unixFetch() invocation.
28783**
28784** Or, if the third argument is NULL, then this function is being called
28785** to inform the VFS layer that, according to POSIX, any existing mapping
28786** may now be invalid and should be unmapped.
28787*/
28788static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
28789#if SQLITE_MAX_MMAP_SIZE>0
28790  unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
28791  UNUSED_PARAMETER(iOff);
28792
28793  /* If p==0 (unmap the entire file) then there must be no outstanding
28794  ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
28795  ** then there must be at least one outstanding.  */
28796  assert( (p==0)==(pFd->nFetchOut==0) );
28797
28798  /* If p!=0, it must match the iOff value. */
28799  assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
28800
28801  if( p ){
28802    pFd->nFetchOut--;
28803  }else{
28804    unixUnmapfile(pFd);
28805  }
28806
28807  assert( pFd->nFetchOut>=0 );
28808#else
28809  UNUSED_PARAMETER(fd);
28810  UNUSED_PARAMETER(p);
28811  UNUSED_PARAMETER(iOff);
28812#endif
28813  return SQLITE_OK;
28814}
28815
28816/*
28817** Here ends the implementation of all sqlite3_file methods.
28818**
28819********************** End sqlite3_file Methods *******************************
28820******************************************************************************/
28821
28822/*
28823** This division contains definitions of sqlite3_io_methods objects that
28824** implement various file locking strategies.  It also contains definitions
28825** of "finder" functions.  A finder-function is used to locate the appropriate
28826** sqlite3_io_methods object for a particular database file.  The pAppData
28827** field of the sqlite3_vfs VFS objects are initialized to be pointers to
28828** the correct finder-function for that VFS.
28829**
28830** Most finder functions return a pointer to a fixed sqlite3_io_methods
28831** object.  The only interesting finder-function is autolockIoFinder, which
28832** looks at the filesystem type and tries to guess the best locking
28833** strategy from that.
28834**
28835** For finder-funtion F, two objects are created:
28836**
28837**    (1) The real finder-function named "FImpt()".
28838**
28839**    (2) A constant pointer to this function named just "F".
28840**
28841**
28842** A pointer to the F pointer is used as the pAppData value for VFS
28843** objects.  We have to do this instead of letting pAppData point
28844** directly at the finder-function since C90 rules prevent a void*
28845** from be cast into a function pointer.
28846**
28847**
28848** Each instance of this macro generates two objects:
28849**
28850**   *  A constant sqlite3_io_methods object call METHOD that has locking
28851**      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
28852**
28853**   *  An I/O method finder function called FINDER that returns a pointer
28854**      to the METHOD object in the previous bullet.
28855*/
28856#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
28857static const sqlite3_io_methods METHOD = {                                   \
28858   VERSION,                    /* iVersion */                                \
28859   CLOSE,                      /* xClose */                                  \
28860   unixRead,                   /* xRead */                                   \
28861   unixWrite,                  /* xWrite */                                  \
28862   unixTruncate,               /* xTruncate */                               \
28863   unixSync,                   /* xSync */                                   \
28864   unixFileSize,               /* xFileSize */                               \
28865   LOCK,                       /* xLock */                                   \
28866   UNLOCK,                     /* xUnlock */                                 \
28867   CKLOCK,                     /* xCheckReservedLock */                      \
28868   unixFileControl,            /* xFileControl */                            \
28869   unixSectorSize,             /* xSectorSize */                             \
28870   unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
28871   unixShmMap,                 /* xShmMap */                                 \
28872   unixShmLock,                /* xShmLock */                                \
28873   unixShmBarrier,             /* xShmBarrier */                             \
28874   unixShmUnmap,               /* xShmUnmap */                               \
28875   unixFetch,                  /* xFetch */                                  \
28876   unixUnfetch,                /* xUnfetch */                                \
28877};                                                                           \
28878static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
28879  UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
28880  return &METHOD;                                                            \
28881}                                                                            \
28882static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
28883    = FINDER##Impl;
28884
28885/*
28886** Here are all of the sqlite3_io_methods objects for each of the
28887** locking strategies.  Functions that return pointers to these methods
28888** are also created.
28889*/
28890IOMETHODS(
28891  posixIoFinder,            /* Finder function name */
28892  posixIoMethods,           /* sqlite3_io_methods object name */
28893  3,                        /* shared memory and mmap are enabled */
28894  unixClose,                /* xClose method */
28895  unixLock,                 /* xLock method */
28896  unixUnlock,               /* xUnlock method */
28897  unixCheckReservedLock     /* xCheckReservedLock method */
28898)
28899IOMETHODS(
28900  nolockIoFinder,           /* Finder function name */
28901  nolockIoMethods,          /* sqlite3_io_methods object name */
28902  1,                        /* shared memory is disabled */
28903  nolockClose,              /* xClose method */
28904  nolockLock,               /* xLock method */
28905  nolockUnlock,             /* xUnlock method */
28906  nolockCheckReservedLock   /* xCheckReservedLock method */
28907)
28908IOMETHODS(
28909  dotlockIoFinder,          /* Finder function name */
28910  dotlockIoMethods,         /* sqlite3_io_methods object name */
28911  1,                        /* shared memory is disabled */
28912  dotlockClose,             /* xClose method */
28913  dotlockLock,              /* xLock method */
28914  dotlockUnlock,            /* xUnlock method */
28915  dotlockCheckReservedLock  /* xCheckReservedLock method */
28916)
28917
28918#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
28919IOMETHODS(
28920  flockIoFinder,            /* Finder function name */
28921  flockIoMethods,           /* sqlite3_io_methods object name */
28922  1,                        /* shared memory is disabled */
28923  flockClose,               /* xClose method */
28924  flockLock,                /* xLock method */
28925  flockUnlock,              /* xUnlock method */
28926  flockCheckReservedLock    /* xCheckReservedLock method */
28927)
28928#endif
28929
28930#if OS_VXWORKS
28931IOMETHODS(
28932  semIoFinder,              /* Finder function name */
28933  semIoMethods,             /* sqlite3_io_methods object name */
28934  1,                        /* shared memory is disabled */
28935  semClose,                 /* xClose method */
28936  semLock,                  /* xLock method */
28937  semUnlock,                /* xUnlock method */
28938  semCheckReservedLock      /* xCheckReservedLock method */
28939)
28940#endif
28941
28942#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28943IOMETHODS(
28944  afpIoFinder,              /* Finder function name */
28945  afpIoMethods,             /* sqlite3_io_methods object name */
28946  1,                        /* shared memory is disabled */
28947  afpClose,                 /* xClose method */
28948  afpLock,                  /* xLock method */
28949  afpUnlock,                /* xUnlock method */
28950  afpCheckReservedLock      /* xCheckReservedLock method */
28951)
28952#endif
28953
28954/*
28955** The proxy locking method is a "super-method" in the sense that it
28956** opens secondary file descriptors for the conch and lock files and
28957** it uses proxy, dot-file, AFP, and flock() locking methods on those
28958** secondary files.  For this reason, the division that implements
28959** proxy locking is located much further down in the file.  But we need
28960** to go ahead and define the sqlite3_io_methods and finder function
28961** for proxy locking here.  So we forward declare the I/O methods.
28962*/
28963#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28964static int proxyClose(sqlite3_file*);
28965static int proxyLock(sqlite3_file*, int);
28966static int proxyUnlock(sqlite3_file*, int);
28967static int proxyCheckReservedLock(sqlite3_file*, int*);
28968IOMETHODS(
28969  proxyIoFinder,            /* Finder function name */
28970  proxyIoMethods,           /* sqlite3_io_methods object name */
28971  1,                        /* shared memory is disabled */
28972  proxyClose,               /* xClose method */
28973  proxyLock,                /* xLock method */
28974  proxyUnlock,              /* xUnlock method */
28975  proxyCheckReservedLock    /* xCheckReservedLock method */
28976)
28977#endif
28978
28979/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
28980#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28981IOMETHODS(
28982  nfsIoFinder,               /* Finder function name */
28983  nfsIoMethods,              /* sqlite3_io_methods object name */
28984  1,                         /* shared memory is disabled */
28985  unixClose,                 /* xClose method */
28986  unixLock,                  /* xLock method */
28987  nfsUnlock,                 /* xUnlock method */
28988  unixCheckReservedLock      /* xCheckReservedLock method */
28989)
28990#endif
28991
28992#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28993/*
28994** This "finder" function attempts to determine the best locking strategy
28995** for the database file "filePath".  It then returns the sqlite3_io_methods
28996** object that implements that strategy.
28997**
28998** This is for MacOSX only.
28999*/
29000static const sqlite3_io_methods *autolockIoFinderImpl(
29001  const char *filePath,    /* name of the database file */
29002  unixFile *pNew           /* open file object for the database file */
29003){
29004  static const struct Mapping {
29005    const char *zFilesystem;              /* Filesystem type name */
29006    const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
29007  } aMap[] = {
29008    { "hfs",    &posixIoMethods },
29009    { "ufs",    &posixIoMethods },
29010    { "afpfs",  &afpIoMethods },
29011    { "smbfs",  &afpIoMethods },
29012    { "webdav", &nolockIoMethods },
29013    { 0, 0 }
29014  };
29015  int i;
29016  struct statfs fsInfo;
29017  struct flock lockInfo;
29018
29019  if( !filePath ){
29020    /* If filePath==NULL that means we are dealing with a transient file
29021    ** that does not need to be locked. */
29022    return &nolockIoMethods;
29023  }
29024  if( statfs(filePath, &fsInfo) != -1 ){
29025    if( fsInfo.f_flags & MNT_RDONLY ){
29026      return &nolockIoMethods;
29027    }
29028    for(i=0; aMap[i].zFilesystem; i++){
29029      if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
29030        return aMap[i].pMethods;
29031      }
29032    }
29033  }
29034
29035  /* Default case. Handles, amongst others, "nfs".
29036  ** Test byte-range lock using fcntl(). If the call succeeds,
29037  ** assume that the file-system supports POSIX style locks.
29038  */
29039  lockInfo.l_len = 1;
29040  lockInfo.l_start = 0;
29041  lockInfo.l_whence = SEEK_SET;
29042  lockInfo.l_type = F_RDLCK;
29043  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
29044    if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
29045      return &nfsIoMethods;
29046    } else {
29047      return &posixIoMethods;
29048    }
29049  }else{
29050    return &dotlockIoMethods;
29051  }
29052}
29053static const sqlite3_io_methods
29054  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
29055
29056#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
29057
29058#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
29059/*
29060** This "finder" function attempts to determine the best locking strategy
29061** for the database file "filePath".  It then returns the sqlite3_io_methods
29062** object that implements that strategy.
29063**
29064** This is for VXWorks only.
29065*/
29066static const sqlite3_io_methods *autolockIoFinderImpl(
29067  const char *filePath,    /* name of the database file */
29068  unixFile *pNew           /* the open file object */
29069){
29070  struct flock lockInfo;
29071
29072  if( !filePath ){
29073    /* If filePath==NULL that means we are dealing with a transient file
29074    ** that does not need to be locked. */
29075    return &nolockIoMethods;
29076  }
29077
29078  /* Test if fcntl() is supported and use POSIX style locks.
29079  ** Otherwise fall back to the named semaphore method.
29080  */
29081  lockInfo.l_len = 1;
29082  lockInfo.l_start = 0;
29083  lockInfo.l_whence = SEEK_SET;
29084  lockInfo.l_type = F_RDLCK;
29085  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
29086    return &posixIoMethods;
29087  }else{
29088    return &semIoMethods;
29089  }
29090}
29091static const sqlite3_io_methods
29092  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
29093
29094#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
29095
29096/*
29097** An abstract type for a pointer to a IO method finder function:
29098*/
29099typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
29100
29101
29102/****************************************************************************
29103**************************** sqlite3_vfs methods ****************************
29104**
29105** This division contains the implementation of methods on the
29106** sqlite3_vfs object.
29107*/
29108
29109/*
29110** Initialize the contents of the unixFile structure pointed to by pId.
29111*/
29112static int fillInUnixFile(
29113  sqlite3_vfs *pVfs,      /* Pointer to vfs object */
29114  int h,                  /* Open file descriptor of file being opened */
29115  sqlite3_file *pId,      /* Write to the unixFile structure here */
29116  const char *zFilename,  /* Name of the file being opened */
29117  int ctrlFlags           /* Zero or more UNIXFILE_* values */
29118){
29119  const sqlite3_io_methods *pLockingStyle;
29120  unixFile *pNew = (unixFile *)pId;
29121  int rc = SQLITE_OK;
29122
29123  assert( pNew->pInode==NULL );
29124
29125  /* Usually the path zFilename should not be a relative pathname. The
29126  ** exception is when opening the proxy "conch" file in builds that
29127  ** include the special Apple locking styles.
29128  */
29129#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29130  assert( zFilename==0 || zFilename[0]=='/'
29131    || pVfs->pAppData==(void*)&autolockIoFinder );
29132#else
29133  assert( zFilename==0 || zFilename[0]=='/' );
29134#endif
29135
29136  /* No locking occurs in temporary files */
29137  assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
29138
29139  OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
29140  pNew->h = h;
29141  pNew->pVfs = pVfs;
29142  pNew->zPath = zFilename;
29143  pNew->ctrlFlags = (u8)ctrlFlags;
29144#if SQLITE_MAX_MMAP_SIZE>0
29145  pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
29146#endif
29147  if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
29148                           "psow", SQLITE_POWERSAFE_OVERWRITE) ){
29149    pNew->ctrlFlags |= UNIXFILE_PSOW;
29150  }
29151  if( strcmp(pVfs->zName,"unix-excl")==0 ){
29152    pNew->ctrlFlags |= UNIXFILE_EXCL;
29153  }
29154
29155#if OS_VXWORKS
29156  pNew->pId = vxworksFindFileId(zFilename);
29157  if( pNew->pId==0 ){
29158    ctrlFlags |= UNIXFILE_NOLOCK;
29159    rc = SQLITE_NOMEM;
29160  }
29161#endif
29162
29163  if( ctrlFlags & UNIXFILE_NOLOCK ){
29164    pLockingStyle = &nolockIoMethods;
29165  }else{
29166    pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
29167#if SQLITE_ENABLE_LOCKING_STYLE
29168    /* Cache zFilename in the locking context (AFP and dotlock override) for
29169    ** proxyLock activation is possible (remote proxy is based on db name)
29170    ** zFilename remains valid until file is closed, to support */
29171    pNew->lockingContext = (void*)zFilename;
29172#endif
29173  }
29174
29175  if( pLockingStyle == &posixIoMethods
29176#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29177    || pLockingStyle == &nfsIoMethods
29178#endif
29179  ){
29180    unixEnterMutex();
29181    rc = findInodeInfo(pNew, &pNew->pInode);
29182    if( rc!=SQLITE_OK ){
29183      /* If an error occurred in findInodeInfo(), close the file descriptor
29184      ** immediately, before releasing the mutex. findInodeInfo() may fail
29185      ** in two scenarios:
29186      **
29187      **   (a) A call to fstat() failed.
29188      **   (b) A malloc failed.
29189      **
29190      ** Scenario (b) may only occur if the process is holding no other
29191      ** file descriptors open on the same file. If there were other file
29192      ** descriptors on this file, then no malloc would be required by
29193      ** findInodeInfo(). If this is the case, it is quite safe to close
29194      ** handle h - as it is guaranteed that no posix locks will be released
29195      ** by doing so.
29196      **
29197      ** If scenario (a) caused the error then things are not so safe. The
29198      ** implicit assumption here is that if fstat() fails, things are in
29199      ** such bad shape that dropping a lock or two doesn't matter much.
29200      */
29201      robust_close(pNew, h, __LINE__);
29202      h = -1;
29203    }
29204    unixLeaveMutex();
29205  }
29206
29207#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
29208  else if( pLockingStyle == &afpIoMethods ){
29209    /* AFP locking uses the file path so it needs to be included in
29210    ** the afpLockingContext.
29211    */
29212    afpLockingContext *pCtx;
29213    pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
29214    if( pCtx==0 ){
29215      rc = SQLITE_NOMEM;
29216    }else{
29217      /* NB: zFilename exists and remains valid until the file is closed
29218      ** according to requirement F11141.  So we do not need to make a
29219      ** copy of the filename. */
29220      pCtx->dbPath = zFilename;
29221      pCtx->reserved = 0;
29222      srandomdev();
29223      unixEnterMutex();
29224      rc = findInodeInfo(pNew, &pNew->pInode);
29225      if( rc!=SQLITE_OK ){
29226        sqlite3_free(pNew->lockingContext);
29227        robust_close(pNew, h, __LINE__);
29228        h = -1;
29229      }
29230      unixLeaveMutex();
29231    }
29232  }
29233#endif
29234
29235  else if( pLockingStyle == &dotlockIoMethods ){
29236    /* Dotfile locking uses the file path so it needs to be included in
29237    ** the dotlockLockingContext
29238    */
29239    char *zLockFile;
29240    int nFilename;
29241    assert( zFilename!=0 );
29242    nFilename = (int)strlen(zFilename) + 6;
29243    zLockFile = (char *)sqlite3_malloc(nFilename);
29244    if( zLockFile==0 ){
29245      rc = SQLITE_NOMEM;
29246    }else{
29247      sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
29248    }
29249    pNew->lockingContext = zLockFile;
29250  }
29251
29252#if OS_VXWORKS
29253  else if( pLockingStyle == &semIoMethods ){
29254    /* Named semaphore locking uses the file path so it needs to be
29255    ** included in the semLockingContext
29256    */
29257    unixEnterMutex();
29258    rc = findInodeInfo(pNew, &pNew->pInode);
29259    if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
29260      char *zSemName = pNew->pInode->aSemName;
29261      int n;
29262      sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
29263                       pNew->pId->zCanonicalName);
29264      for( n=1; zSemName[n]; n++ )
29265        if( zSemName[n]=='/' ) zSemName[n] = '_';
29266      pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
29267      if( pNew->pInode->pSem == SEM_FAILED ){
29268        rc = SQLITE_NOMEM;
29269        pNew->pInode->aSemName[0] = '\0';
29270      }
29271    }
29272    unixLeaveMutex();
29273  }
29274#endif
29275
29276  pNew->lastErrno = 0;
29277#if OS_VXWORKS
29278  if( rc!=SQLITE_OK ){
29279    if( h>=0 ) robust_close(pNew, h, __LINE__);
29280    h = -1;
29281    osUnlink(zFilename);
29282    pNew->ctrlFlags |= UNIXFILE_DELETE;
29283  }
29284#endif
29285  if( rc!=SQLITE_OK ){
29286    if( h>=0 ) robust_close(pNew, h, __LINE__);
29287  }else{
29288    pNew->pMethod = pLockingStyle;
29289    OpenCounter(+1);
29290    verifyDbFile(pNew);
29291  }
29292  return rc;
29293}
29294
29295/*
29296** Return the name of a directory in which to put temporary files.
29297** If no suitable temporary file directory can be found, return NULL.
29298*/
29299static const char *unixTempFileDir(void){
29300  static const char *azDirs[] = {
29301     0,
29302     0,
29303     0,
29304     "/var/tmp",
29305     "/usr/tmp",
29306     "/tmp",
29307     0        /* List terminator */
29308  };
29309  unsigned int i;
29310  struct stat buf;
29311  const char *zDir = 0;
29312
29313  azDirs[0] = sqlite3_temp_directory;
29314  if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
29315  if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
29316  for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
29317    if( zDir==0 ) continue;
29318    if( osStat(zDir, &buf) ) continue;
29319    if( !S_ISDIR(buf.st_mode) ) continue;
29320    if( osAccess(zDir, 07) ) continue;
29321    break;
29322  }
29323  return zDir;
29324}
29325
29326/*
29327** Create a temporary file name in zBuf.  zBuf must be allocated
29328** by the calling process and must be big enough to hold at least
29329** pVfs->mxPathname bytes.
29330*/
29331static int unixGetTempname(int nBuf, char *zBuf){
29332  static const unsigned char zChars[] =
29333    "abcdefghijklmnopqrstuvwxyz"
29334    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
29335    "0123456789";
29336  unsigned int i, j;
29337  const char *zDir;
29338
29339  /* It's odd to simulate an io-error here, but really this is just
29340  ** using the io-error infrastructure to test that SQLite handles this
29341  ** function failing.
29342  */
29343  SimulateIOError( return SQLITE_IOERR );
29344
29345  zDir = unixTempFileDir();
29346  if( zDir==0 ) zDir = ".";
29347
29348  /* Check that the output buffer is large enough for the temporary file
29349  ** name. If it is not, return SQLITE_ERROR.
29350  */
29351  if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
29352    return SQLITE_ERROR;
29353  }
29354
29355  do{
29356    sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
29357    j = (int)strlen(zBuf);
29358    sqlite3_randomness(15, &zBuf[j]);
29359    for(i=0; i<15; i++, j++){
29360      zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
29361    }
29362    zBuf[j] = 0;
29363    zBuf[j+1] = 0;
29364  }while( osAccess(zBuf,0)==0 );
29365  return SQLITE_OK;
29366}
29367
29368#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
29369/*
29370** Routine to transform a unixFile into a proxy-locking unixFile.
29371** Implementation in the proxy-lock division, but used by unixOpen()
29372** if SQLITE_PREFER_PROXY_LOCKING is defined.
29373*/
29374static int proxyTransformUnixFile(unixFile*, const char*);
29375#endif
29376
29377/*
29378** Search for an unused file descriptor that was opened on the database
29379** file (not a journal or master-journal file) identified by pathname
29380** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
29381** argument to this function.
29382**
29383** Such a file descriptor may exist if a database connection was closed
29384** but the associated file descriptor could not be closed because some
29385** other file descriptor open on the same file is holding a file-lock.
29386** Refer to comments in the unixClose() function and the lengthy comment
29387** describing "Posix Advisory Locking" at the start of this file for
29388** further details. Also, ticket #4018.
29389**
29390** If a suitable file descriptor is found, then it is returned. If no
29391** such file descriptor is located, -1 is returned.
29392*/
29393static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
29394  UnixUnusedFd *pUnused = 0;
29395
29396  /* Do not search for an unused file descriptor on vxworks. Not because
29397  ** vxworks would not benefit from the change (it might, we're not sure),
29398  ** but because no way to test it is currently available. It is better
29399  ** not to risk breaking vxworks support for the sake of such an obscure
29400  ** feature.  */
29401#if !OS_VXWORKS
29402  struct stat sStat;                   /* Results of stat() call */
29403
29404  /* A stat() call may fail for various reasons. If this happens, it is
29405  ** almost certain that an open() call on the same path will also fail.
29406  ** For this reason, if an error occurs in the stat() call here, it is
29407  ** ignored and -1 is returned. The caller will try to open a new file
29408  ** descriptor on the same path, fail, and return an error to SQLite.
29409  **
29410  ** Even if a subsequent open() call does succeed, the consequences of
29411  ** not searching for a resusable file descriptor are not dire.  */
29412  if( 0==osStat(zPath, &sStat) ){
29413    unixInodeInfo *pInode;
29414
29415    unixEnterMutex();
29416    pInode = inodeList;
29417    while( pInode && (pInode->fileId.dev!=sStat.st_dev
29418                     || pInode->fileId.ino!=sStat.st_ino) ){
29419       pInode = pInode->pNext;
29420    }
29421    if( pInode ){
29422      UnixUnusedFd **pp;
29423      for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
29424      pUnused = *pp;
29425      if( pUnused ){
29426        *pp = pUnused->pNext;
29427      }
29428    }
29429    unixLeaveMutex();
29430  }
29431#endif    /* if !OS_VXWORKS */
29432  return pUnused;
29433}
29434
29435/*
29436** This function is called by unixOpen() to determine the unix permissions
29437** to create new files with. If no error occurs, then SQLITE_OK is returned
29438** and a value suitable for passing as the third argument to open(2) is
29439** written to *pMode. If an IO error occurs, an SQLite error code is
29440** returned and the value of *pMode is not modified.
29441**
29442** In most cases cases, this routine sets *pMode to 0, which will become
29443** an indication to robust_open() to create the file using
29444** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
29445** But if the file being opened is a WAL or regular journal file, then
29446** this function queries the file-system for the permissions on the
29447** corresponding database file and sets *pMode to this value. Whenever
29448** possible, WAL and journal files are created using the same permissions
29449** as the associated database file.
29450**
29451** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
29452** original filename is unavailable.  But 8_3_NAMES is only used for
29453** FAT filesystems and permissions do not matter there, so just use
29454** the default permissions.
29455*/
29456static int findCreateFileMode(
29457  const char *zPath,              /* Path of file (possibly) being created */
29458  int flags,                      /* Flags passed as 4th argument to xOpen() */
29459  mode_t *pMode,                  /* OUT: Permissions to open file with */
29460  uid_t *pUid,                    /* OUT: uid to set on the file */
29461  gid_t *pGid                     /* OUT: gid to set on the file */
29462){
29463  int rc = SQLITE_OK;             /* Return Code */
29464  *pMode = 0;
29465  *pUid = 0;
29466  *pGid = 0;
29467  if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
29468    char zDb[MAX_PATHNAME+1];     /* Database file path */
29469    int nDb;                      /* Number of valid bytes in zDb */
29470    struct stat sStat;            /* Output of stat() on database file */
29471
29472    /* zPath is a path to a WAL or journal file. The following block derives
29473    ** the path to the associated database file from zPath. This block handles
29474    ** the following naming conventions:
29475    **
29476    **   "<path to db>-journal"
29477    **   "<path to db>-wal"
29478    **   "<path to db>-journalNN"
29479    **   "<path to db>-walNN"
29480    **
29481    ** where NN is a decimal number. The NN naming schemes are
29482    ** used by the test_multiplex.c module.
29483    */
29484    nDb = sqlite3Strlen30(zPath) - 1;
29485#ifdef SQLITE_ENABLE_8_3_NAMES
29486    while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
29487    if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
29488#else
29489    while( zPath[nDb]!='-' ){
29490      assert( nDb>0 );
29491      assert( zPath[nDb]!='\n' );
29492      nDb--;
29493    }
29494#endif
29495    memcpy(zDb, zPath, nDb);
29496    zDb[nDb] = '\0';
29497
29498    if( 0==osStat(zDb, &sStat) ){
29499      *pMode = sStat.st_mode & 0777;
29500      *pUid = sStat.st_uid;
29501      *pGid = sStat.st_gid;
29502    }else{
29503      rc = SQLITE_IOERR_FSTAT;
29504    }
29505  }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
29506    *pMode = 0600;
29507  }
29508  return rc;
29509}
29510
29511/*
29512** Open the file zPath.
29513**
29514** Previously, the SQLite OS layer used three functions in place of this
29515** one:
29516**
29517**     sqlite3OsOpenReadWrite();
29518**     sqlite3OsOpenReadOnly();
29519**     sqlite3OsOpenExclusive();
29520**
29521** These calls correspond to the following combinations of flags:
29522**
29523**     ReadWrite() ->     (READWRITE | CREATE)
29524**     ReadOnly()  ->     (READONLY)
29525**     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
29526**
29527** The old OpenExclusive() accepted a boolean argument - "delFlag". If
29528** true, the file was configured to be automatically deleted when the
29529** file handle closed. To achieve the same effect using this new
29530** interface, add the DELETEONCLOSE flag to those specified above for
29531** OpenExclusive().
29532*/
29533static int unixOpen(
29534  sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
29535  const char *zPath,           /* Pathname of file to be opened */
29536  sqlite3_file *pFile,         /* The file descriptor to be filled in */
29537  int flags,                   /* Input flags to control the opening */
29538  int *pOutFlags               /* Output flags returned to SQLite core */
29539){
29540  unixFile *p = (unixFile *)pFile;
29541  int fd = -1;                   /* File descriptor returned by open() */
29542  int openFlags = 0;             /* Flags to pass to open() */
29543  int eType = flags&0xFFFFFF00;  /* Type of file to open */
29544  int noLock;                    /* True to omit locking primitives */
29545  int rc = SQLITE_OK;            /* Function Return Code */
29546  int ctrlFlags = 0;             /* UNIXFILE_* flags */
29547
29548  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
29549  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
29550  int isCreate     = (flags & SQLITE_OPEN_CREATE);
29551  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
29552  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
29553#if SQLITE_ENABLE_LOCKING_STYLE
29554  int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
29555#endif
29556#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
29557  struct statfs fsInfo;
29558#endif
29559
29560  /* If creating a master or main-file journal, this function will open
29561  ** a file-descriptor on the directory too. The first time unixSync()
29562  ** is called the directory file descriptor will be fsync()ed and close()d.
29563  */
29564  int syncDir = (isCreate && (
29565        eType==SQLITE_OPEN_MASTER_JOURNAL
29566     || eType==SQLITE_OPEN_MAIN_JOURNAL
29567     || eType==SQLITE_OPEN_WAL
29568  ));
29569
29570  /* If argument zPath is a NULL pointer, this function is required to open
29571  ** a temporary file. Use this buffer to store the file name in.
29572  */
29573  char zTmpname[MAX_PATHNAME+2];
29574  const char *zName = zPath;
29575
29576  /* Check the following statements are true:
29577  **
29578  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
29579  **   (b) if CREATE is set, then READWRITE must also be set, and
29580  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
29581  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
29582  */
29583  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
29584  assert(isCreate==0 || isReadWrite);
29585  assert(isExclusive==0 || isCreate);
29586  assert(isDelete==0 || isCreate);
29587
29588  /* The main DB, main journal, WAL file and master journal are never
29589  ** automatically deleted. Nor are they ever temporary files.  */
29590  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
29591  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
29592  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
29593  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
29594
29595  /* Assert that the upper layer has set one of the "file-type" flags. */
29596  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
29597       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
29598       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
29599       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
29600  );
29601
29602  /* Detect a pid change and reset the PRNG.  There is a race condition
29603  ** here such that two or more threads all trying to open databases at
29604  ** the same instant might all reset the PRNG.  But multiple resets
29605  ** are harmless.
29606  */
29607  if( randomnessPid!=getpid() ){
29608    randomnessPid = getpid();
29609    sqlite3_randomness(0,0);
29610  }
29611
29612  memset(p, 0, sizeof(unixFile));
29613
29614  if( eType==SQLITE_OPEN_MAIN_DB ){
29615    UnixUnusedFd *pUnused;
29616    pUnused = findReusableFd(zName, flags);
29617    if( pUnused ){
29618      fd = pUnused->fd;
29619    }else{
29620      pUnused = sqlite3_malloc(sizeof(*pUnused));
29621      if( !pUnused ){
29622        return SQLITE_NOMEM;
29623      }
29624    }
29625    p->pUnused = pUnused;
29626
29627    /* Database filenames are double-zero terminated if they are not
29628    ** URIs with parameters.  Hence, they can always be passed into
29629    ** sqlite3_uri_parameter(). */
29630    assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
29631
29632  }else if( !zName ){
29633    /* If zName is NULL, the upper layer is requesting a temp file. */
29634    assert(isDelete && !syncDir);
29635    rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
29636    if( rc!=SQLITE_OK ){
29637      return rc;
29638    }
29639    zName = zTmpname;
29640
29641    /* Generated temporary filenames are always double-zero terminated
29642    ** for use by sqlite3_uri_parameter(). */
29643    assert( zName[strlen(zName)+1]==0 );
29644  }
29645
29646  /* Determine the value of the flags parameter passed to POSIX function
29647  ** open(). These must be calculated even if open() is not called, as
29648  ** they may be stored as part of the file handle and used by the
29649  ** 'conch file' locking functions later on.  */
29650  if( isReadonly )  openFlags |= O_RDONLY;
29651  if( isReadWrite ) openFlags |= O_RDWR;
29652  if( isCreate )    openFlags |= O_CREAT;
29653  if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
29654  openFlags |= (O_LARGEFILE|O_BINARY);
29655
29656  if( fd<0 ){
29657    mode_t openMode;              /* Permissions to create file with */
29658    uid_t uid;                    /* Userid for the file */
29659    gid_t gid;                    /* Groupid for the file */
29660    rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
29661    if( rc!=SQLITE_OK ){
29662      assert( !p->pUnused );
29663      assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
29664      return rc;
29665    }
29666    fd = robust_open(zName, openFlags, openMode);
29667    OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
29668    if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
29669      /* Failed to open the file for read/write access. Try read-only. */
29670      flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
29671      openFlags &= ~(O_RDWR|O_CREAT);
29672      flags |= SQLITE_OPEN_READONLY;
29673      openFlags |= O_RDONLY;
29674      isReadonly = 1;
29675      fd = robust_open(zName, openFlags, openMode);
29676    }
29677    if( fd<0 ){
29678      rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
29679      goto open_finished;
29680    }
29681
29682    /* If this process is running as root and if creating a new rollback
29683    ** journal or WAL file, set the ownership of the journal or WAL to be
29684    ** the same as the original database.
29685    */
29686    if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
29687      osFchown(fd, uid, gid);
29688    }
29689  }
29690  assert( fd>=0 );
29691  if( pOutFlags ){
29692    *pOutFlags = flags;
29693  }
29694
29695  if( p->pUnused ){
29696    p->pUnused->fd = fd;
29697    p->pUnused->flags = flags;
29698  }
29699
29700  if( isDelete ){
29701#if OS_VXWORKS
29702    zPath = zName;
29703#else
29704    osUnlink(zName);
29705#endif
29706  }
29707#if SQLITE_ENABLE_LOCKING_STYLE
29708  else{
29709    p->openFlags = openFlags;
29710  }
29711#endif
29712
29713  noLock = eType!=SQLITE_OPEN_MAIN_DB;
29714
29715
29716#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
29717  if( fstatfs(fd, &fsInfo) == -1 ){
29718    ((unixFile*)pFile)->lastErrno = errno;
29719    robust_close(p, fd, __LINE__);
29720    return SQLITE_IOERR_ACCESS;
29721  }
29722  if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
29723    ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
29724  }
29725#endif
29726
29727  /* Set up appropriate ctrlFlags */
29728  if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;
29729  if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;
29730  if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;
29731  if( syncDir )                 ctrlFlags |= UNIXFILE_DIRSYNC;
29732  if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
29733
29734#if SQLITE_ENABLE_LOCKING_STYLE
29735#if SQLITE_PREFER_PROXY_LOCKING
29736  isAutoProxy = 1;
29737#endif
29738  if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
29739    char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
29740    int useProxy = 0;
29741
29742    /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
29743    ** never use proxy, NULL means use proxy for non-local files only.  */
29744    if( envforce!=NULL ){
29745      useProxy = atoi(envforce)>0;
29746    }else{
29747      if( statfs(zPath, &fsInfo) == -1 ){
29748        /* In theory, the close(fd) call is sub-optimal. If the file opened
29749        ** with fd is a database file, and there are other connections open
29750        ** on that file that are currently holding advisory locks on it,
29751        ** then the call to close() will cancel those locks. In practice,
29752        ** we're assuming that statfs() doesn't fail very often. At least
29753        ** not while other file descriptors opened by the same process on
29754        ** the same file are working.  */
29755        p->lastErrno = errno;
29756        robust_close(p, fd, __LINE__);
29757        rc = SQLITE_IOERR_ACCESS;
29758        goto open_finished;
29759      }
29760      useProxy = !(fsInfo.f_flags&MNT_LOCAL);
29761    }
29762    if( useProxy ){
29763      rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
29764      if( rc==SQLITE_OK ){
29765        rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
29766        if( rc!=SQLITE_OK ){
29767          /* Use unixClose to clean up the resources added in fillInUnixFile
29768          ** and clear all the structure's references.  Specifically,
29769          ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
29770          */
29771          unixClose(pFile);
29772          return rc;
29773        }
29774      }
29775      goto open_finished;
29776    }
29777  }
29778#endif
29779
29780  rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
29781
29782open_finished:
29783  if( rc!=SQLITE_OK ){
29784    sqlite3_free(p->pUnused);
29785  }
29786  return rc;
29787}
29788
29789
29790/*
29791** Delete the file at zPath. If the dirSync argument is true, fsync()
29792** the directory after deleting the file.
29793*/
29794static int unixDelete(
29795  sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
29796  const char *zPath,        /* Name of file to be deleted */
29797  int dirSync               /* If true, fsync() directory after deleting file */
29798){
29799  int rc = SQLITE_OK;
29800  UNUSED_PARAMETER(NotUsed);
29801  SimulateIOError(return SQLITE_IOERR_DELETE);
29802  if( osUnlink(zPath)==(-1) ){
29803    if( errno==ENOENT ){
29804      rc = SQLITE_IOERR_DELETE_NOENT;
29805    }else{
29806      rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
29807    }
29808    return rc;
29809  }
29810#ifndef SQLITE_DISABLE_DIRSYNC
29811  if( (dirSync & 1)!=0 ){
29812    int fd;
29813    rc = osOpenDirectory(zPath, &fd);
29814    if( rc==SQLITE_OK ){
29815#if OS_VXWORKS
29816      if( fsync(fd)==-1 )
29817#else
29818      if( fsync(fd) )
29819#endif
29820      {
29821        rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
29822      }
29823      robust_close(0, fd, __LINE__);
29824    }else if( rc==SQLITE_CANTOPEN ){
29825      rc = SQLITE_OK;
29826    }
29827  }
29828#endif
29829  return rc;
29830}
29831
29832/*
29833** Test the existence of or access permissions of file zPath. The
29834** test performed depends on the value of flags:
29835**
29836**     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
29837**     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
29838**     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
29839**
29840** Otherwise return 0.
29841*/
29842static int unixAccess(
29843  sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
29844  const char *zPath,      /* Path of the file to examine */
29845  int flags,              /* What do we want to learn about the zPath file? */
29846  int *pResOut            /* Write result boolean here */
29847){
29848  int amode = 0;
29849  UNUSED_PARAMETER(NotUsed);
29850  SimulateIOError( return SQLITE_IOERR_ACCESS; );
29851  switch( flags ){
29852    case SQLITE_ACCESS_EXISTS:
29853      amode = F_OK;
29854      break;
29855    case SQLITE_ACCESS_READWRITE:
29856      amode = W_OK|R_OK;
29857      break;
29858    case SQLITE_ACCESS_READ:
29859      amode = R_OK;
29860      break;
29861
29862    default:
29863      assert(!"Invalid flags argument");
29864  }
29865  *pResOut = (osAccess(zPath, amode)==0);
29866  if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
29867    struct stat buf;
29868    if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
29869      *pResOut = 0;
29870    }
29871  }
29872  return SQLITE_OK;
29873}
29874
29875
29876/*
29877** Turn a relative pathname into a full pathname. The relative path
29878** is stored as a nul-terminated string in the buffer pointed to by
29879** zPath.
29880**
29881** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
29882** (in this case, MAX_PATHNAME bytes). The full-path is written to
29883** this buffer before returning.
29884*/
29885static int unixFullPathname(
29886  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
29887  const char *zPath,            /* Possibly relative input path */
29888  int nOut,                     /* Size of output buffer in bytes */
29889  char *zOut                    /* Output buffer */
29890){
29891
29892  /* It's odd to simulate an io-error here, but really this is just
29893  ** using the io-error infrastructure to test that SQLite handles this
29894  ** function failing. This function could fail if, for example, the
29895  ** current working directory has been unlinked.
29896  */
29897  SimulateIOError( return SQLITE_ERROR );
29898
29899  assert( pVfs->mxPathname==MAX_PATHNAME );
29900  UNUSED_PARAMETER(pVfs);
29901
29902  zOut[nOut-1] = '\0';
29903  if( zPath[0]=='/' ){
29904    sqlite3_snprintf(nOut, zOut, "%s", zPath);
29905  }else{
29906    int nCwd;
29907    if( osGetcwd(zOut, nOut-1)==0 ){
29908      return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
29909    }
29910    nCwd = (int)strlen(zOut);
29911    sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
29912  }
29913  return SQLITE_OK;
29914}
29915
29916
29917#ifndef SQLITE_OMIT_LOAD_EXTENSION
29918/*
29919** Interfaces for opening a shared library, finding entry points
29920** within the shared library, and closing the shared library.
29921*/
29922#include <dlfcn.h>
29923static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
29924  UNUSED_PARAMETER(NotUsed);
29925  return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
29926}
29927
29928/*
29929** SQLite calls this function immediately after a call to unixDlSym() or
29930** unixDlOpen() fails (returns a null pointer). If a more detailed error
29931** message is available, it is written to zBufOut. If no error message
29932** is available, zBufOut is left unmodified and SQLite uses a default
29933** error message.
29934*/
29935static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
29936  const char *zErr;
29937  UNUSED_PARAMETER(NotUsed);
29938  unixEnterMutex();
29939  zErr = dlerror();
29940  if( zErr ){
29941    sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
29942  }
29943  unixLeaveMutex();
29944}
29945static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
29946  /*
29947  ** GCC with -pedantic-errors says that C90 does not allow a void* to be
29948  ** cast into a pointer to a function.  And yet the library dlsym() routine
29949  ** returns a void* which is really a pointer to a function.  So how do we
29950  ** use dlsym() with -pedantic-errors?
29951  **
29952  ** Variable x below is defined to be a pointer to a function taking
29953  ** parameters void* and const char* and returning a pointer to a function.
29954  ** We initialize x by assigning it a pointer to the dlsym() function.
29955  ** (That assignment requires a cast.)  Then we call the function that
29956  ** x points to.
29957  **
29958  ** This work-around is unlikely to work correctly on any system where
29959  ** you really cannot cast a function pointer into void*.  But then, on the
29960  ** other hand, dlsym() will not work on such a system either, so we have
29961  ** not really lost anything.
29962  */
29963  void (*(*x)(void*,const char*))(void);
29964  UNUSED_PARAMETER(NotUsed);
29965  x = (void(*(*)(void*,const char*))(void))dlsym;
29966  return (*x)(p, zSym);
29967}
29968static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
29969  UNUSED_PARAMETER(NotUsed);
29970  dlclose(pHandle);
29971}
29972#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
29973  #define unixDlOpen  0
29974  #define unixDlError 0
29975  #define unixDlSym   0
29976  #define unixDlClose 0
29977#endif
29978
29979/*
29980** Write nBuf bytes of random data to the supplied buffer zBuf.
29981*/
29982static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
29983  UNUSED_PARAMETER(NotUsed);
29984  assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
29985
29986  /* We have to initialize zBuf to prevent valgrind from reporting
29987  ** errors.  The reports issued by valgrind are incorrect - we would
29988  ** prefer that the randomness be increased by making use of the
29989  ** uninitialized space in zBuf - but valgrind errors tend to worry
29990  ** some users.  Rather than argue, it seems easier just to initialize
29991  ** the whole array and silence valgrind, even if that means less randomness
29992  ** in the random seed.
29993  **
29994  ** When testing, initializing zBuf[] to zero is all we do.  That means
29995  ** that we always use the same random number sequence.  This makes the
29996  ** tests repeatable.
29997  */
29998  memset(zBuf, 0, nBuf);
29999  randomnessPid = getpid();
30000#if !defined(SQLITE_TEST)
30001  {
30002    int fd, got;
30003    fd = robust_open("/dev/urandom", O_RDONLY, 0);
30004    if( fd<0 ){
30005      time_t t;
30006      time(&t);
30007      memcpy(zBuf, &t, sizeof(t));
30008      memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
30009      assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
30010      nBuf = sizeof(t) + sizeof(randomnessPid);
30011    }else{
30012      do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
30013      robust_close(0, fd, __LINE__);
30014    }
30015  }
30016#endif
30017  return nBuf;
30018}
30019
30020
30021/*
30022** Sleep for a little while.  Return the amount of time slept.
30023** The argument is the number of microseconds we want to sleep.
30024** The return value is the number of microseconds of sleep actually
30025** requested from the underlying operating system, a number which
30026** might be greater than or equal to the argument, but not less
30027** than the argument.
30028*/
30029static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
30030#if OS_VXWORKS
30031  struct timespec sp;
30032
30033  sp.tv_sec = microseconds / 1000000;
30034  sp.tv_nsec = (microseconds % 1000000) * 1000;
30035  nanosleep(&sp, NULL);
30036  UNUSED_PARAMETER(NotUsed);
30037  return microseconds;
30038#elif defined(HAVE_USLEEP) && HAVE_USLEEP
30039  usleep(microseconds);
30040  UNUSED_PARAMETER(NotUsed);
30041  return microseconds;
30042#else
30043  int seconds = (microseconds+999999)/1000000;
30044  sleep(seconds);
30045  UNUSED_PARAMETER(NotUsed);
30046  return seconds*1000000;
30047#endif
30048}
30049
30050/*
30051** The following variable, if set to a non-zero value, is interpreted as
30052** the number of seconds since 1970 and is used to set the result of
30053** sqlite3OsCurrentTime() during testing.
30054*/
30055#ifdef SQLITE_TEST
30056SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
30057#endif
30058
30059/*
30060** Find the current time (in Universal Coordinated Time).  Write into *piNow
30061** the current time and date as a Julian Day number times 86_400_000.  In
30062** other words, write into *piNow the number of milliseconds since the Julian
30063** epoch of noon in Greenwich on November 24, 4714 B.C according to the
30064** proleptic Gregorian calendar.
30065**
30066** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
30067** cannot be found.
30068*/
30069static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
30070  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
30071  int rc = SQLITE_OK;
30072#if defined(NO_GETTOD)
30073  time_t t;
30074  time(&t);
30075  *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
30076#elif OS_VXWORKS
30077  struct timespec sNow;
30078  clock_gettime(CLOCK_REALTIME, &sNow);
30079  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
30080#else
30081  struct timeval sNow;
30082  if( gettimeofday(&sNow, 0)==0 ){
30083    *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
30084  }else{
30085    rc = SQLITE_ERROR;
30086  }
30087#endif
30088
30089#ifdef SQLITE_TEST
30090  if( sqlite3_current_time ){
30091    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
30092  }
30093#endif
30094  UNUSED_PARAMETER(NotUsed);
30095  return rc;
30096}
30097
30098/*
30099** Find the current time (in Universal Coordinated Time).  Write the
30100** current time and date as a Julian Day number into *prNow and
30101** return 0.  Return 1 if the time and date cannot be found.
30102*/
30103static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
30104  sqlite3_int64 i = 0;
30105  int rc;
30106  UNUSED_PARAMETER(NotUsed);
30107  rc = unixCurrentTimeInt64(0, &i);
30108  *prNow = i/86400000.0;
30109  return rc;
30110}
30111
30112/*
30113** We added the xGetLastError() method with the intention of providing
30114** better low-level error messages when operating-system problems come up
30115** during SQLite operation.  But so far, none of that has been implemented
30116** in the core.  So this routine is never called.  For now, it is merely
30117** a place-holder.
30118*/
30119static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
30120  UNUSED_PARAMETER(NotUsed);
30121  UNUSED_PARAMETER(NotUsed2);
30122  UNUSED_PARAMETER(NotUsed3);
30123  return 0;
30124}
30125
30126
30127/*
30128************************ End of sqlite3_vfs methods ***************************
30129******************************************************************************/
30130
30131/******************************************************************************
30132************************** Begin Proxy Locking ********************************
30133**
30134** Proxy locking is a "uber-locking-method" in this sense:  It uses the
30135** other locking methods on secondary lock files.  Proxy locking is a
30136** meta-layer over top of the primitive locking implemented above.  For
30137** this reason, the division that implements of proxy locking is deferred
30138** until late in the file (here) after all of the other I/O methods have
30139** been defined - so that the primitive locking methods are available
30140** as services to help with the implementation of proxy locking.
30141**
30142****
30143**
30144** The default locking schemes in SQLite use byte-range locks on the
30145** database file to coordinate safe, concurrent access by multiple readers
30146** and writers [http://sqlite.org/lockingv3.html].  The five file locking
30147** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
30148** as POSIX read & write locks over fixed set of locations (via fsctl),
30149** on AFP and SMB only exclusive byte-range locks are available via fsctl
30150** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
30151** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
30152** address in the shared range is taken for a SHARED lock, the entire
30153** shared range is taken for an EXCLUSIVE lock):
30154**
30155**      PENDING_BYTE        0x40000000
30156**      RESERVED_BYTE       0x40000001
30157**      SHARED_RANGE        0x40000002 -> 0x40000200
30158**
30159** This works well on the local file system, but shows a nearly 100x
30160** slowdown in read performance on AFP because the AFP client disables
30161** the read cache when byte-range locks are present.  Enabling the read
30162** cache exposes a cache coherency problem that is present on all OS X
30163** supported network file systems.  NFS and AFP both observe the
30164** close-to-open semantics for ensuring cache coherency
30165** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
30166** address the requirements for concurrent database access by multiple
30167** readers and writers
30168** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
30169**
30170** To address the performance and cache coherency issues, proxy file locking
30171** changes the way database access is controlled by limiting access to a
30172** single host at a time and moving file locks off of the database file
30173** and onto a proxy file on the local file system.
30174**
30175**
30176** Using proxy locks
30177** -----------------
30178**
30179** C APIs
30180**
30181**  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
30182**                       <proxy_path> | ":auto:");
30183**  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
30184**
30185**
30186** SQL pragmas
30187**
30188**  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
30189**  PRAGMA [database.]lock_proxy_file
30190**
30191** Specifying ":auto:" means that if there is a conch file with a matching
30192** host ID in it, the proxy path in the conch file will be used, otherwise
30193** a proxy path based on the user's temp dir
30194** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
30195** actual proxy file name is generated from the name and path of the
30196** database file.  For example:
30197**
30198**       For database path "/Users/me/foo.db"
30199**       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
30200**
30201** Once a lock proxy is configured for a database connection, it can not
30202** be removed, however it may be switched to a different proxy path via
30203** the above APIs (assuming the conch file is not being held by another
30204** connection or process).
30205**
30206**
30207** How proxy locking works
30208** -----------------------
30209**
30210** Proxy file locking relies primarily on two new supporting files:
30211**
30212**   *  conch file to limit access to the database file to a single host
30213**      at a time
30214**
30215**   *  proxy file to act as a proxy for the advisory locks normally
30216**      taken on the database
30217**
30218** The conch file - to use a proxy file, sqlite must first "hold the conch"
30219** by taking an sqlite-style shared lock on the conch file, reading the
30220** contents and comparing the host's unique host ID (see below) and lock
30221** proxy path against the values stored in the conch.  The conch file is
30222** stored in the same directory as the database file and the file name
30223** is patterned after the database file name as ".<databasename>-conch".
30224** If the conch file does not exist, or it's contents do not match the
30225** host ID and/or proxy path, then the lock is escalated to an exclusive
30226** lock and the conch file contents is updated with the host ID and proxy
30227** path and the lock is downgraded to a shared lock again.  If the conch
30228** is held by another process (with a shared lock), the exclusive lock
30229** will fail and SQLITE_BUSY is returned.
30230**
30231** The proxy file - a single-byte file used for all advisory file locks
30232** normally taken on the database file.   This allows for safe sharing
30233** of the database file for multiple readers and writers on the same
30234** host (the conch ensures that they all use the same local lock file).
30235**
30236** Requesting the lock proxy does not immediately take the conch, it is
30237** only taken when the first request to lock database file is made.
30238** This matches the semantics of the traditional locking behavior, where
30239** opening a connection to a database file does not take a lock on it.
30240** The shared lock and an open file descriptor are maintained until
30241** the connection to the database is closed.
30242**
30243** The proxy file and the lock file are never deleted so they only need
30244** to be created the first time they are used.
30245**
30246** Configuration options
30247** ---------------------
30248**
30249**  SQLITE_PREFER_PROXY_LOCKING
30250**
30251**       Database files accessed on non-local file systems are
30252**       automatically configured for proxy locking, lock files are
30253**       named automatically using the same logic as
30254**       PRAGMA lock_proxy_file=":auto:"
30255**
30256**  SQLITE_PROXY_DEBUG
30257**
30258**       Enables the logging of error messages during host id file
30259**       retrieval and creation
30260**
30261**  LOCKPROXYDIR
30262**
30263**       Overrides the default directory used for lock proxy files that
30264**       are named automatically via the ":auto:" setting
30265**
30266**  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
30267**
30268**       Permissions to use when creating a directory for storing the
30269**       lock proxy files, only used when LOCKPROXYDIR is not set.
30270**
30271**
30272** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
30273** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
30274** force proxy locking to be used for every database file opened, and 0
30275** will force automatic proxy locking to be disabled for all database
30276** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
30277** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
30278*/
30279
30280/*
30281** Proxy locking is only available on MacOSX
30282*/
30283#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
30284
30285/*
30286** The proxyLockingContext has the path and file structures for the remote
30287** and local proxy files in it
30288*/
30289typedef struct proxyLockingContext proxyLockingContext;
30290struct proxyLockingContext {
30291  unixFile *conchFile;         /* Open conch file */
30292  char *conchFilePath;         /* Name of the conch file */
30293  unixFile *lockProxy;         /* Open proxy lock file */
30294  char *lockProxyPath;         /* Name of the proxy lock file */
30295  char *dbPath;                /* Name of the open file */
30296  int conchHeld;               /* 1 if the conch is held, -1 if lockless */
30297  void *oldLockingContext;     /* Original lockingcontext to restore on close */
30298  sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
30299};
30300
30301/*
30302** The proxy lock file path for the database at dbPath is written into lPath,
30303** which must point to valid, writable memory large enough for a maxLen length
30304** file path.
30305*/
30306static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
30307  int len;
30308  int dbLen;
30309  int i;
30310
30311#ifdef LOCKPROXYDIR
30312  len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
30313#else
30314# ifdef _CS_DARWIN_USER_TEMP_DIR
30315  {
30316    if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
30317      OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
30318               lPath, errno, getpid()));
30319      return SQLITE_IOERR_LOCK;
30320    }
30321    len = strlcat(lPath, "sqliteplocks", maxLen);
30322  }
30323# else
30324  len = strlcpy(lPath, "/tmp/", maxLen);
30325# endif
30326#endif
30327
30328  if( lPath[len-1]!='/' ){
30329    len = strlcat(lPath, "/", maxLen);
30330  }
30331
30332  /* transform the db path to a unique cache name */
30333  dbLen = (int)strlen(dbPath);
30334  for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
30335    char c = dbPath[i];
30336    lPath[i+len] = (c=='/')?'_':c;
30337  }
30338  lPath[i+len]='\0';
30339  strlcat(lPath, ":auto:", maxLen);
30340  OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
30341  return SQLITE_OK;
30342}
30343
30344/*
30345 ** Creates the lock file and any missing directories in lockPath
30346 */
30347static int proxyCreateLockPath(const char *lockPath){
30348  int i, len;
30349  char buf[MAXPATHLEN];
30350  int start = 0;
30351
30352  assert(lockPath!=NULL);
30353  /* try to create all the intermediate directories */
30354  len = (int)strlen(lockPath);
30355  buf[0] = lockPath[0];
30356  for( i=1; i<len; i++ ){
30357    if( lockPath[i] == '/' && (i - start > 0) ){
30358      /* only mkdir if leaf dir != "." or "/" or ".." */
30359      if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
30360         || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
30361        buf[i]='\0';
30362        if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
30363          int err=errno;
30364          if( err!=EEXIST ) {
30365            OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
30366                     "'%s' proxy lock path=%s pid=%d\n",
30367                     buf, strerror(err), lockPath, getpid()));
30368            return err;
30369          }
30370        }
30371      }
30372      start=i+1;
30373    }
30374    buf[i] = lockPath[i];
30375  }
30376  OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
30377  return 0;
30378}
30379
30380/*
30381** Create a new VFS file descriptor (stored in memory obtained from
30382** sqlite3_malloc) and open the file named "path" in the file descriptor.
30383**
30384** The caller is responsible not only for closing the file descriptor
30385** but also for freeing the memory associated with the file descriptor.
30386*/
30387static int proxyCreateUnixFile(
30388    const char *path,        /* path for the new unixFile */
30389    unixFile **ppFile,       /* unixFile created and returned by ref */
30390    int islockfile           /* if non zero missing dirs will be created */
30391) {
30392  int fd = -1;
30393  unixFile *pNew;
30394  int rc = SQLITE_OK;
30395  int openFlags = O_RDWR | O_CREAT;
30396  sqlite3_vfs dummyVfs;
30397  int terrno = 0;
30398  UnixUnusedFd *pUnused = NULL;
30399
30400  /* 1. first try to open/create the file
30401  ** 2. if that fails, and this is a lock file (not-conch), try creating
30402  ** the parent directories and then try again.
30403  ** 3. if that fails, try to open the file read-only
30404  ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
30405  */
30406  pUnused = findReusableFd(path, openFlags);
30407  if( pUnused ){
30408    fd = pUnused->fd;
30409  }else{
30410    pUnused = sqlite3_malloc(sizeof(*pUnused));
30411    if( !pUnused ){
30412      return SQLITE_NOMEM;
30413    }
30414  }
30415  if( fd<0 ){
30416    fd = robust_open(path, openFlags, 0);
30417    terrno = errno;
30418    if( fd<0 && errno==ENOENT && islockfile ){
30419      if( proxyCreateLockPath(path) == SQLITE_OK ){
30420        fd = robust_open(path, openFlags, 0);
30421      }
30422    }
30423  }
30424  if( fd<0 ){
30425    openFlags = O_RDONLY;
30426    fd = robust_open(path, openFlags, 0);
30427    terrno = errno;
30428  }
30429  if( fd<0 ){
30430    if( islockfile ){
30431      return SQLITE_BUSY;
30432    }
30433    switch (terrno) {
30434      case EACCES:
30435        return SQLITE_PERM;
30436      case EIO:
30437        return SQLITE_IOERR_LOCK; /* even though it is the conch */
30438      default:
30439        return SQLITE_CANTOPEN_BKPT;
30440    }
30441  }
30442
30443  pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
30444  if( pNew==NULL ){
30445    rc = SQLITE_NOMEM;
30446    goto end_create_proxy;
30447  }
30448  memset(pNew, 0, sizeof(unixFile));
30449  pNew->openFlags = openFlags;
30450  memset(&dummyVfs, 0, sizeof(dummyVfs));
30451  dummyVfs.pAppData = (void*)&autolockIoFinder;
30452  dummyVfs.zName = "dummy";
30453  pUnused->fd = fd;
30454  pUnused->flags = openFlags;
30455  pNew->pUnused = pUnused;
30456
30457  rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
30458  if( rc==SQLITE_OK ){
30459    *ppFile = pNew;
30460    return SQLITE_OK;
30461  }
30462end_create_proxy:
30463  robust_close(pNew, fd, __LINE__);
30464  sqlite3_free(pNew);
30465  sqlite3_free(pUnused);
30466  return rc;
30467}
30468
30469#ifdef SQLITE_TEST
30470/* simulate multiple hosts by creating unique hostid file paths */
30471SQLITE_API int sqlite3_hostid_num = 0;
30472#endif
30473
30474#define PROXY_HOSTIDLEN    16  /* conch file host id length */
30475
30476/* Not always defined in the headers as it ought to be */
30477extern int gethostuuid(uuid_t id, const struct timespec *wait);
30478
30479/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
30480** bytes of writable memory.
30481*/
30482static int proxyGetHostID(unsigned char *pHostID, int *pError){
30483  assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
30484  memset(pHostID, 0, PROXY_HOSTIDLEN);
30485#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
30486               && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
30487  {
30488    static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
30489    if( gethostuuid(pHostID, &timeout) ){
30490      int err = errno;
30491      if( pError ){
30492        *pError = err;
30493      }
30494      return SQLITE_IOERR;
30495    }
30496  }
30497#else
30498  UNUSED_PARAMETER(pError);
30499#endif
30500#ifdef SQLITE_TEST
30501  /* simulate multiple hosts by creating unique hostid file paths */
30502  if( sqlite3_hostid_num != 0){
30503    pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
30504  }
30505#endif
30506
30507  return SQLITE_OK;
30508}
30509
30510/* The conch file contains the header, host id and lock file path
30511 */
30512#define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
30513#define PROXY_HEADERLEN    1   /* conch file header length */
30514#define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
30515#define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
30516
30517/*
30518** Takes an open conch file, copies the contents to a new path and then moves
30519** it back.  The newly created file's file descriptor is assigned to the
30520** conch file structure and finally the original conch file descriptor is
30521** closed.  Returns zero if successful.
30522*/
30523static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
30524  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30525  unixFile *conchFile = pCtx->conchFile;
30526  char tPath[MAXPATHLEN];
30527  char buf[PROXY_MAXCONCHLEN];
30528  char *cPath = pCtx->conchFilePath;
30529  size_t readLen = 0;
30530  size_t pathLen = 0;
30531  char errmsg[64] = "";
30532  int fd = -1;
30533  int rc = -1;
30534  UNUSED_PARAMETER(myHostID);
30535
30536  /* create a new path by replace the trailing '-conch' with '-break' */
30537  pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
30538  if( pathLen>MAXPATHLEN || pathLen<6 ||
30539     (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
30540    sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
30541    goto end_breaklock;
30542  }
30543  /* read the conch content */
30544  readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
30545  if( readLen<PROXY_PATHINDEX ){
30546    sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
30547    goto end_breaklock;
30548  }
30549  /* write it out to the temporary break file */
30550  fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
30551  if( fd<0 ){
30552    sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
30553    goto end_breaklock;
30554  }
30555  if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
30556    sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
30557    goto end_breaklock;
30558  }
30559  if( rename(tPath, cPath) ){
30560    sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
30561    goto end_breaklock;
30562  }
30563  rc = 0;
30564  fprintf(stderr, "broke stale lock on %s\n", cPath);
30565  robust_close(pFile, conchFile->h, __LINE__);
30566  conchFile->h = fd;
30567  conchFile->openFlags = O_RDWR | O_CREAT;
30568
30569end_breaklock:
30570  if( rc ){
30571    if( fd>=0 ){
30572      osUnlink(tPath);
30573      robust_close(pFile, fd, __LINE__);
30574    }
30575    fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
30576  }
30577  return rc;
30578}
30579
30580/* Take the requested lock on the conch file and break a stale lock if the
30581** host id matches.
30582*/
30583static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
30584  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30585  unixFile *conchFile = pCtx->conchFile;
30586  int rc = SQLITE_OK;
30587  int nTries = 0;
30588  struct timespec conchModTime;
30589
30590  memset(&conchModTime, 0, sizeof(conchModTime));
30591  do {
30592    rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
30593    nTries ++;
30594    if( rc==SQLITE_BUSY ){
30595      /* If the lock failed (busy):
30596       * 1st try: get the mod time of the conch, wait 0.5s and try again.
30597       * 2nd try: fail if the mod time changed or host id is different, wait
30598       *           10 sec and try again
30599       * 3rd try: break the lock unless the mod time has changed.
30600       */
30601      struct stat buf;
30602      if( osFstat(conchFile->h, &buf) ){
30603        pFile->lastErrno = errno;
30604        return SQLITE_IOERR_LOCK;
30605      }
30606
30607      if( nTries==1 ){
30608        conchModTime = buf.st_mtimespec;
30609        usleep(500000); /* wait 0.5 sec and try the lock again*/
30610        continue;
30611      }
30612
30613      assert( nTries>1 );
30614      if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
30615         conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
30616        return SQLITE_BUSY;
30617      }
30618
30619      if( nTries==2 ){
30620        char tBuf[PROXY_MAXCONCHLEN];
30621        int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
30622        if( len<0 ){
30623          pFile->lastErrno = errno;
30624          return SQLITE_IOERR_LOCK;
30625        }
30626        if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
30627          /* don't break the lock if the host id doesn't match */
30628          if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
30629            return SQLITE_BUSY;
30630          }
30631        }else{
30632          /* don't break the lock on short read or a version mismatch */
30633          return SQLITE_BUSY;
30634        }
30635        usleep(10000000); /* wait 10 sec and try the lock again */
30636        continue;
30637      }
30638
30639      assert( nTries==3 );
30640      if( 0==proxyBreakConchLock(pFile, myHostID) ){
30641        rc = SQLITE_OK;
30642        if( lockType==EXCLUSIVE_LOCK ){
30643          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
30644        }
30645        if( !rc ){
30646          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
30647        }
30648      }
30649    }
30650  } while( rc==SQLITE_BUSY && nTries<3 );
30651
30652  return rc;
30653}
30654
30655/* Takes the conch by taking a shared lock and read the contents conch, if
30656** lockPath is non-NULL, the host ID and lock file path must match.  A NULL
30657** lockPath means that the lockPath in the conch file will be used if the
30658** host IDs match, or a new lock path will be generated automatically
30659** and written to the conch file.
30660*/
30661static int proxyTakeConch(unixFile *pFile){
30662  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30663
30664  if( pCtx->conchHeld!=0 ){
30665    return SQLITE_OK;
30666  }else{
30667    unixFile *conchFile = pCtx->conchFile;
30668    uuid_t myHostID;
30669    int pError = 0;
30670    char readBuf[PROXY_MAXCONCHLEN];
30671    char lockPath[MAXPATHLEN];
30672    char *tempLockPath = NULL;
30673    int rc = SQLITE_OK;
30674    int createConch = 0;
30675    int hostIdMatch = 0;
30676    int readLen = 0;
30677    int tryOldLockPath = 0;
30678    int forceNewLockPath = 0;
30679
30680    OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
30681             (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
30682
30683    rc = proxyGetHostID(myHostID, &pError);
30684    if( (rc&0xff)==SQLITE_IOERR ){
30685      pFile->lastErrno = pError;
30686      goto end_takeconch;
30687    }
30688    rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
30689    if( rc!=SQLITE_OK ){
30690      goto end_takeconch;
30691    }
30692    /* read the existing conch file */
30693    readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
30694    if( readLen<0 ){
30695      /* I/O error: lastErrno set by seekAndRead */
30696      pFile->lastErrno = conchFile->lastErrno;
30697      rc = SQLITE_IOERR_READ;
30698      goto end_takeconch;
30699    }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
30700             readBuf[0]!=(char)PROXY_CONCHVERSION ){
30701      /* a short read or version format mismatch means we need to create a new
30702      ** conch file.
30703      */
30704      createConch = 1;
30705    }
30706    /* if the host id matches and the lock path already exists in the conch
30707    ** we'll try to use the path there, if we can't open that path, we'll
30708    ** retry with a new auto-generated path
30709    */
30710    do { /* in case we need to try again for an :auto: named lock file */
30711
30712      if( !createConch && !forceNewLockPath ){
30713        hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
30714                                  PROXY_HOSTIDLEN);
30715        /* if the conch has data compare the contents */
30716        if( !pCtx->lockProxyPath ){
30717          /* for auto-named local lock file, just check the host ID and we'll
30718           ** use the local lock file path that's already in there
30719           */
30720          if( hostIdMatch ){
30721            size_t pathLen = (readLen - PROXY_PATHINDEX);
30722
30723            if( pathLen>=MAXPATHLEN ){
30724              pathLen=MAXPATHLEN-1;
30725            }
30726            memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
30727            lockPath[pathLen] = 0;
30728            tempLockPath = lockPath;
30729            tryOldLockPath = 1;
30730            /* create a copy of the lock path if the conch is taken */
30731            goto end_takeconch;
30732          }
30733        }else if( hostIdMatch
30734               && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
30735                           readLen-PROXY_PATHINDEX)
30736        ){
30737          /* conch host and lock path match */
30738          goto end_takeconch;
30739        }
30740      }
30741
30742      /* if the conch isn't writable and doesn't match, we can't take it */
30743      if( (conchFile->openFlags&O_RDWR) == 0 ){
30744        rc = SQLITE_BUSY;
30745        goto end_takeconch;
30746      }
30747
30748      /* either the conch didn't match or we need to create a new one */
30749      if( !pCtx->lockProxyPath ){
30750        proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
30751        tempLockPath = lockPath;
30752        /* create a copy of the lock path _only_ if the conch is taken */
30753      }
30754
30755      /* update conch with host and path (this will fail if other process
30756      ** has a shared lock already), if the host id matches, use the big
30757      ** stick.
30758      */
30759      futimes(conchFile->h, NULL);
30760      if( hostIdMatch && !createConch ){
30761        if( conchFile->pInode && conchFile->pInode->nShared>1 ){
30762          /* We are trying for an exclusive lock but another thread in this
30763           ** same process is still holding a shared lock. */
30764          rc = SQLITE_BUSY;
30765        } else {
30766          rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
30767        }
30768      }else{
30769        rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
30770      }
30771      if( rc==SQLITE_OK ){
30772        char writeBuffer[PROXY_MAXCONCHLEN];
30773        int writeSize = 0;
30774
30775        writeBuffer[0] = (char)PROXY_CONCHVERSION;
30776        memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
30777        if( pCtx->lockProxyPath!=NULL ){
30778          strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
30779        }else{
30780          strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
30781        }
30782        writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
30783        robust_ftruncate(conchFile->h, writeSize);
30784        rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
30785        fsync(conchFile->h);
30786        /* If we created a new conch file (not just updated the contents of a
30787         ** valid conch file), try to match the permissions of the database
30788         */
30789        if( rc==SQLITE_OK && createConch ){
30790          struct stat buf;
30791          int err = osFstat(pFile->h, &buf);
30792          if( err==0 ){
30793            mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
30794                                        S_IROTH|S_IWOTH);
30795            /* try to match the database file R/W permissions, ignore failure */
30796#ifndef SQLITE_PROXY_DEBUG
30797            osFchmod(conchFile->h, cmode);
30798#else
30799            do{
30800              rc = osFchmod(conchFile->h, cmode);
30801            }while( rc==(-1) && errno==EINTR );
30802            if( rc!=0 ){
30803              int code = errno;
30804              fprintf(stderr, "fchmod %o FAILED with %d %s\n",
30805                      cmode, code, strerror(code));
30806            } else {
30807              fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
30808            }
30809          }else{
30810            int code = errno;
30811            fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
30812                    err, code, strerror(code));
30813#endif
30814          }
30815        }
30816      }
30817      conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
30818
30819    end_takeconch:
30820      OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
30821      if( rc==SQLITE_OK && pFile->openFlags ){
30822        int fd;
30823        if( pFile->h>=0 ){
30824          robust_close(pFile, pFile->h, __LINE__);
30825        }
30826        pFile->h = -1;
30827        fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
30828        OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
30829        if( fd>=0 ){
30830          pFile->h = fd;
30831        }else{
30832          rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
30833           during locking */
30834        }
30835      }
30836      if( rc==SQLITE_OK && !pCtx->lockProxy ){
30837        char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
30838        rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
30839        if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
30840          /* we couldn't create the proxy lock file with the old lock file path
30841           ** so try again via auto-naming
30842           */
30843          forceNewLockPath = 1;
30844          tryOldLockPath = 0;
30845          continue; /* go back to the do {} while start point, try again */
30846        }
30847      }
30848      if( rc==SQLITE_OK ){
30849        /* Need to make a copy of path if we extracted the value
30850         ** from the conch file or the path was allocated on the stack
30851         */
30852        if( tempLockPath ){
30853          pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
30854          if( !pCtx->lockProxyPath ){
30855            rc = SQLITE_NOMEM;
30856          }
30857        }
30858      }
30859      if( rc==SQLITE_OK ){
30860        pCtx->conchHeld = 1;
30861
30862        if( pCtx->lockProxy->pMethod == &afpIoMethods ){
30863          afpLockingContext *afpCtx;
30864          afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
30865          afpCtx->dbPath = pCtx->lockProxyPath;
30866        }
30867      } else {
30868        conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
30869      }
30870      OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
30871               rc==SQLITE_OK?"ok":"failed"));
30872      return rc;
30873    } while (1); /* in case we need to retry the :auto: lock file -
30874                 ** we should never get here except via the 'continue' call. */
30875  }
30876}
30877
30878/*
30879** If pFile holds a lock on a conch file, then release that lock.
30880*/
30881static int proxyReleaseConch(unixFile *pFile){
30882  int rc = SQLITE_OK;         /* Subroutine return code */
30883  proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
30884  unixFile *conchFile;        /* Name of the conch file */
30885
30886  pCtx = (proxyLockingContext *)pFile->lockingContext;
30887  conchFile = pCtx->conchFile;
30888  OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
30889           (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
30890           getpid()));
30891  if( pCtx->conchHeld>0 ){
30892    rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
30893  }
30894  pCtx->conchHeld = 0;
30895  OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
30896           (rc==SQLITE_OK ? "ok" : "failed")));
30897  return rc;
30898}
30899
30900/*
30901** Given the name of a database file, compute the name of its conch file.
30902** Store the conch filename in memory obtained from sqlite3_malloc().
30903** Make *pConchPath point to the new name.  Return SQLITE_OK on success
30904** or SQLITE_NOMEM if unable to obtain memory.
30905**
30906** The caller is responsible for ensuring that the allocated memory
30907** space is eventually freed.
30908**
30909** *pConchPath is set to NULL if a memory allocation error occurs.
30910*/
30911static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
30912  int i;                        /* Loop counter */
30913  int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
30914  char *conchPath;              /* buffer in which to construct conch name */
30915
30916  /* Allocate space for the conch filename and initialize the name to
30917  ** the name of the original database file. */
30918  *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
30919  if( conchPath==0 ){
30920    return SQLITE_NOMEM;
30921  }
30922  memcpy(conchPath, dbPath, len+1);
30923
30924  /* now insert a "." before the last / character */
30925  for( i=(len-1); i>=0; i-- ){
30926    if( conchPath[i]=='/' ){
30927      i++;
30928      break;
30929    }
30930  }
30931  conchPath[i]='.';
30932  while ( i<len ){
30933    conchPath[i+1]=dbPath[i];
30934    i++;
30935  }
30936
30937  /* append the "-conch" suffix to the file */
30938  memcpy(&conchPath[i+1], "-conch", 7);
30939  assert( (int)strlen(conchPath) == len+7 );
30940
30941  return SQLITE_OK;
30942}
30943
30944
30945/* Takes a fully configured proxy locking-style unix file and switches
30946** the local lock file path
30947*/
30948static int switchLockProxyPath(unixFile *pFile, const char *path) {
30949  proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
30950  char *oldPath = pCtx->lockProxyPath;
30951  int rc = SQLITE_OK;
30952
30953  if( pFile->eFileLock!=NO_LOCK ){
30954    return SQLITE_BUSY;
30955  }
30956
30957  /* nothing to do if the path is NULL, :auto: or matches the existing path */
30958  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
30959    (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
30960    return SQLITE_OK;
30961  }else{
30962    unixFile *lockProxy = pCtx->lockProxy;
30963    pCtx->lockProxy=NULL;
30964    pCtx->conchHeld = 0;
30965    if( lockProxy!=NULL ){
30966      rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
30967      if( rc ) return rc;
30968      sqlite3_free(lockProxy);
30969    }
30970    sqlite3_free(oldPath);
30971    pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
30972  }
30973
30974  return rc;
30975}
30976
30977/*
30978** pFile is a file that has been opened by a prior xOpen call.  dbPath
30979** is a string buffer at least MAXPATHLEN+1 characters in size.
30980**
30981** This routine find the filename associated with pFile and writes it
30982** int dbPath.
30983*/
30984static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
30985#if defined(__APPLE__)
30986  if( pFile->pMethod == &afpIoMethods ){
30987    /* afp style keeps a reference to the db path in the filePath field
30988    ** of the struct */
30989    assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
30990    strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
30991  } else
30992#endif
30993  if( pFile->pMethod == &dotlockIoMethods ){
30994    /* dot lock style uses the locking context to store the dot lock
30995    ** file path */
30996    int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
30997    memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
30998  }else{
30999    /* all other styles use the locking context to store the db file path */
31000    assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
31001    strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
31002  }
31003  return SQLITE_OK;
31004}
31005
31006/*
31007** Takes an already filled in unix file and alters it so all file locking
31008** will be performed on the local proxy lock file.  The following fields
31009** are preserved in the locking context so that they can be restored and
31010** the unix structure properly cleaned up at close time:
31011**  ->lockingContext
31012**  ->pMethod
31013*/
31014static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
31015  proxyLockingContext *pCtx;
31016  char dbPath[MAXPATHLEN+1];       /* Name of the database file */
31017  char *lockPath=NULL;
31018  int rc = SQLITE_OK;
31019
31020  if( pFile->eFileLock!=NO_LOCK ){
31021    return SQLITE_BUSY;
31022  }
31023  proxyGetDbPathForUnixFile(pFile, dbPath);
31024  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
31025    lockPath=NULL;
31026  }else{
31027    lockPath=(char *)path;
31028  }
31029
31030  OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
31031           (lockPath ? lockPath : ":auto:"), getpid()));
31032
31033  pCtx = sqlite3_malloc( sizeof(*pCtx) );
31034  if( pCtx==0 ){
31035    return SQLITE_NOMEM;
31036  }
31037  memset(pCtx, 0, sizeof(*pCtx));
31038
31039  rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
31040  if( rc==SQLITE_OK ){
31041    rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
31042    if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
31043      /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
31044      ** (c) the file system is read-only, then enable no-locking access.
31045      ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
31046      ** that openFlags will have only one of O_RDONLY or O_RDWR.
31047      */
31048      struct statfs fsInfo;
31049      struct stat conchInfo;
31050      int goLockless = 0;
31051
31052      if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
31053        int err = errno;
31054        if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
31055          goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
31056        }
31057      }
31058      if( goLockless ){
31059        pCtx->conchHeld = -1; /* read only FS/ lockless */
31060        rc = SQLITE_OK;
31061      }
31062    }
31063  }
31064  if( rc==SQLITE_OK && lockPath ){
31065    pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
31066  }
31067
31068  if( rc==SQLITE_OK ){
31069    pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
31070    if( pCtx->dbPath==NULL ){
31071      rc = SQLITE_NOMEM;
31072    }
31073  }
31074  if( rc==SQLITE_OK ){
31075    /* all memory is allocated, proxys are created and assigned,
31076    ** switch the locking context and pMethod then return.
31077    */
31078    pCtx->oldLockingContext = pFile->lockingContext;
31079    pFile->lockingContext = pCtx;
31080    pCtx->pOldMethod = pFile->pMethod;
31081    pFile->pMethod = &proxyIoMethods;
31082  }else{
31083    if( pCtx->conchFile ){
31084      pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
31085      sqlite3_free(pCtx->conchFile);
31086    }
31087    sqlite3DbFree(0, pCtx->lockProxyPath);
31088    sqlite3_free(pCtx->conchFilePath);
31089    sqlite3_free(pCtx);
31090  }
31091  OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
31092           (rc==SQLITE_OK ? "ok" : "failed")));
31093  return rc;
31094}
31095
31096
31097/*
31098** This routine handles sqlite3_file_control() calls that are specific
31099** to proxy locking.
31100*/
31101static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
31102  switch( op ){
31103    case SQLITE_GET_LOCKPROXYFILE: {
31104      unixFile *pFile = (unixFile*)id;
31105      if( pFile->pMethod == &proxyIoMethods ){
31106        proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
31107        proxyTakeConch(pFile);
31108        if( pCtx->lockProxyPath ){
31109          *(const char **)pArg = pCtx->lockProxyPath;
31110        }else{
31111          *(const char **)pArg = ":auto: (not held)";
31112        }
31113      } else {
31114        *(const char **)pArg = NULL;
31115      }
31116      return SQLITE_OK;
31117    }
31118    case SQLITE_SET_LOCKPROXYFILE: {
31119      unixFile *pFile = (unixFile*)id;
31120      int rc = SQLITE_OK;
31121      int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
31122      if( pArg==NULL || (const char *)pArg==0 ){
31123        if( isProxyStyle ){
31124          /* turn off proxy locking - not supported */
31125          rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
31126        }else{
31127          /* turn off proxy locking - already off - NOOP */
31128          rc = SQLITE_OK;
31129        }
31130      }else{
31131        const char *proxyPath = (const char *)pArg;
31132        if( isProxyStyle ){
31133          proxyLockingContext *pCtx =
31134            (proxyLockingContext*)pFile->lockingContext;
31135          if( !strcmp(pArg, ":auto:")
31136           || (pCtx->lockProxyPath &&
31137               !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
31138          ){
31139            rc = SQLITE_OK;
31140          }else{
31141            rc = switchLockProxyPath(pFile, proxyPath);
31142          }
31143        }else{
31144          /* turn on proxy file locking */
31145          rc = proxyTransformUnixFile(pFile, proxyPath);
31146        }
31147      }
31148      return rc;
31149    }
31150    default: {
31151      assert( 0 );  /* The call assures that only valid opcodes are sent */
31152    }
31153  }
31154  /*NOTREACHED*/
31155  return SQLITE_ERROR;
31156}
31157
31158/*
31159** Within this division (the proxying locking implementation) the procedures
31160** above this point are all utilities.  The lock-related methods of the
31161** proxy-locking sqlite3_io_method object follow.
31162*/
31163
31164
31165/*
31166** This routine checks if there is a RESERVED lock held on the specified
31167** file by this or any other process. If such a lock is held, set *pResOut
31168** to a non-zero value otherwise *pResOut is set to zero.  The return value
31169** is set to SQLITE_OK unless an I/O error occurs during lock checking.
31170*/
31171static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
31172  unixFile *pFile = (unixFile*)id;
31173  int rc = proxyTakeConch(pFile);
31174  if( rc==SQLITE_OK ){
31175    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31176    if( pCtx->conchHeld>0 ){
31177      unixFile *proxy = pCtx->lockProxy;
31178      return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
31179    }else{ /* conchHeld < 0 is lockless */
31180      pResOut=0;
31181    }
31182  }
31183  return rc;
31184}
31185
31186/*
31187** Lock the file with the lock specified by parameter eFileLock - one
31188** of the following:
31189**
31190**     (1) SHARED_LOCK
31191**     (2) RESERVED_LOCK
31192**     (3) PENDING_LOCK
31193**     (4) EXCLUSIVE_LOCK
31194**
31195** Sometimes when requesting one lock state, additional lock states
31196** are inserted in between.  The locking might fail on one of the later
31197** transitions leaving the lock state different from what it started but
31198** still short of its goal.  The following chart shows the allowed
31199** transitions and the inserted intermediate states:
31200**
31201**    UNLOCKED -> SHARED
31202**    SHARED -> RESERVED
31203**    SHARED -> (PENDING) -> EXCLUSIVE
31204**    RESERVED -> (PENDING) -> EXCLUSIVE
31205**    PENDING -> EXCLUSIVE
31206**
31207** This routine will only increase a lock.  Use the sqlite3OsUnlock()
31208** routine to lower a locking level.
31209*/
31210static int proxyLock(sqlite3_file *id, int eFileLock) {
31211  unixFile *pFile = (unixFile*)id;
31212  int rc = proxyTakeConch(pFile);
31213  if( rc==SQLITE_OK ){
31214    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31215    if( pCtx->conchHeld>0 ){
31216      unixFile *proxy = pCtx->lockProxy;
31217      rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
31218      pFile->eFileLock = proxy->eFileLock;
31219    }else{
31220      /* conchHeld < 0 is lockless */
31221    }
31222  }
31223  return rc;
31224}
31225
31226
31227/*
31228** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
31229** must be either NO_LOCK or SHARED_LOCK.
31230**
31231** If the locking level of the file descriptor is already at or below
31232** the requested locking level, this routine is a no-op.
31233*/
31234static int proxyUnlock(sqlite3_file *id, int eFileLock) {
31235  unixFile *pFile = (unixFile*)id;
31236  int rc = proxyTakeConch(pFile);
31237  if( rc==SQLITE_OK ){
31238    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31239    if( pCtx->conchHeld>0 ){
31240      unixFile *proxy = pCtx->lockProxy;
31241      rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
31242      pFile->eFileLock = proxy->eFileLock;
31243    }else{
31244      /* conchHeld < 0 is lockless */
31245    }
31246  }
31247  return rc;
31248}
31249
31250/*
31251** Close a file that uses proxy locks.
31252*/
31253static int proxyClose(sqlite3_file *id) {
31254  if( id ){
31255    unixFile *pFile = (unixFile*)id;
31256    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31257    unixFile *lockProxy = pCtx->lockProxy;
31258    unixFile *conchFile = pCtx->conchFile;
31259    int rc = SQLITE_OK;
31260
31261    if( lockProxy ){
31262      rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
31263      if( rc ) return rc;
31264      rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
31265      if( rc ) return rc;
31266      sqlite3_free(lockProxy);
31267      pCtx->lockProxy = 0;
31268    }
31269    if( conchFile ){
31270      if( pCtx->conchHeld ){
31271        rc = proxyReleaseConch(pFile);
31272        if( rc ) return rc;
31273      }
31274      rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
31275      if( rc ) return rc;
31276      sqlite3_free(conchFile);
31277    }
31278    sqlite3DbFree(0, pCtx->lockProxyPath);
31279    sqlite3_free(pCtx->conchFilePath);
31280    sqlite3DbFree(0, pCtx->dbPath);
31281    /* restore the original locking context and pMethod then close it */
31282    pFile->lockingContext = pCtx->oldLockingContext;
31283    pFile->pMethod = pCtx->pOldMethod;
31284    sqlite3_free(pCtx);
31285    return pFile->pMethod->xClose(id);
31286  }
31287  return SQLITE_OK;
31288}
31289
31290
31291
31292#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
31293/*
31294** The proxy locking style is intended for use with AFP filesystems.
31295** And since AFP is only supported on MacOSX, the proxy locking is also
31296** restricted to MacOSX.
31297**
31298**
31299******************* End of the proxy lock implementation **********************
31300******************************************************************************/
31301
31302/*
31303** Initialize the operating system interface.
31304**
31305** This routine registers all VFS implementations for unix-like operating
31306** systems.  This routine, and the sqlite3_os_end() routine that follows,
31307** should be the only routines in this file that are visible from other
31308** files.
31309**
31310** This routine is called once during SQLite initialization and by a
31311** single thread.  The memory allocation and mutex subsystems have not
31312** necessarily been initialized when this routine is called, and so they
31313** should not be used.
31314*/
31315SQLITE_API int sqlite3_os_init(void){
31316  /*
31317  ** The following macro defines an initializer for an sqlite3_vfs object.
31318  ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
31319  ** to the "finder" function.  (pAppData is a pointer to a pointer because
31320  ** silly C90 rules prohibit a void* from being cast to a function pointer
31321  ** and so we have to go through the intermediate pointer to avoid problems
31322  ** when compiling with -pedantic-errors on GCC.)
31323  **
31324  ** The FINDER parameter to this macro is the name of the pointer to the
31325  ** finder-function.  The finder-function returns a pointer to the
31326  ** sqlite_io_methods object that implements the desired locking
31327  ** behaviors.  See the division above that contains the IOMETHODS
31328  ** macro for addition information on finder-functions.
31329  **
31330  ** Most finders simply return a pointer to a fixed sqlite3_io_methods
31331  ** object.  But the "autolockIoFinder" available on MacOSX does a little
31332  ** more than that; it looks at the filesystem type that hosts the
31333  ** database file and tries to choose an locking method appropriate for
31334  ** that filesystem time.
31335  */
31336  #define UNIXVFS(VFSNAME, FINDER) {                        \
31337    3,                    /* iVersion */                    \
31338    sizeof(unixFile),     /* szOsFile */                    \
31339    MAX_PATHNAME,         /* mxPathname */                  \
31340    0,                    /* pNext */                       \
31341    VFSNAME,              /* zName */                       \
31342    (void*)&FINDER,       /* pAppData */                    \
31343    unixOpen,             /* xOpen */                       \
31344    unixDelete,           /* xDelete */                     \
31345    unixAccess,           /* xAccess */                     \
31346    unixFullPathname,     /* xFullPathname */               \
31347    unixDlOpen,           /* xDlOpen */                     \
31348    unixDlError,          /* xDlError */                    \
31349    unixDlSym,            /* xDlSym */                      \
31350    unixDlClose,          /* xDlClose */                    \
31351    unixRandomness,       /* xRandomness */                 \
31352    unixSleep,            /* xSleep */                      \
31353    unixCurrentTime,      /* xCurrentTime */                \
31354    unixGetLastError,     /* xGetLastError */               \
31355    unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
31356    unixSetSystemCall,    /* xSetSystemCall */              \
31357    unixGetSystemCall,    /* xGetSystemCall */              \
31358    unixNextSystemCall,   /* xNextSystemCall */             \
31359  }
31360
31361  /*
31362  ** All default VFSes for unix are contained in the following array.
31363  **
31364  ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
31365  ** by the SQLite core when the VFS is registered.  So the following
31366  ** array cannot be const.
31367  */
31368  static sqlite3_vfs aVfs[] = {
31369#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
31370    UNIXVFS("unix",          autolockIoFinder ),
31371#else
31372    UNIXVFS("unix",          posixIoFinder ),
31373#endif
31374    UNIXVFS("unix-none",     nolockIoFinder ),
31375    UNIXVFS("unix-dotfile",  dotlockIoFinder ),
31376    UNIXVFS("unix-excl",     posixIoFinder ),
31377#if OS_VXWORKS
31378    UNIXVFS("unix-namedsem", semIoFinder ),
31379#endif
31380#if SQLITE_ENABLE_LOCKING_STYLE
31381    UNIXVFS("unix-posix",    posixIoFinder ),
31382#if !OS_VXWORKS
31383    UNIXVFS("unix-flock",    flockIoFinder ),
31384#endif
31385#endif
31386#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
31387    UNIXVFS("unix-afp",      afpIoFinder ),
31388    UNIXVFS("unix-nfs",      nfsIoFinder ),
31389    UNIXVFS("unix-proxy",    proxyIoFinder ),
31390#endif
31391  };
31392  unsigned int i;          /* Loop counter */
31393
31394  /* Double-check that the aSyscall[] array has been constructed
31395  ** correctly.  See ticket [bb3a86e890c8e96ab] */
31396  assert( ArraySize(aSyscall)==25 );
31397
31398  /* Register all VFSes defined in the aVfs[] array */
31399  for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
31400    sqlite3_vfs_register(&aVfs[i], i==0);
31401  }
31402  return SQLITE_OK;
31403}
31404
31405/*
31406** Shutdown the operating system interface.
31407**
31408** Some operating systems might need to do some cleanup in this routine,
31409** to release dynamically allocated objects.  But not on unix.
31410** This routine is a no-op for unix.
31411*/
31412SQLITE_API int sqlite3_os_end(void){
31413  return SQLITE_OK;
31414}
31415
31416#endif /* SQLITE_OS_UNIX */
31417
31418/************** End of os_unix.c *********************************************/
31419/************** Begin file os_win.c ******************************************/
31420/*
31421** 2004 May 22
31422**
31423** The author disclaims copyright to this source code.  In place of
31424** a legal notice, here is a blessing:
31425**
31426**    May you do good and not evil.
31427**    May you find forgiveness for yourself and forgive others.
31428**    May you share freely, never taking more than you give.
31429**
31430******************************************************************************
31431**
31432** This file contains code that is specific to Windows.
31433*/
31434#if SQLITE_OS_WIN               /* This file is used for Windows only */
31435
31436/*
31437** Include code that is common to all os_*.c files
31438*/
31439/************** Include os_common.h in the middle of os_win.c ****************/
31440/************** Begin file os_common.h ***************************************/
31441/*
31442** 2004 May 22
31443**
31444** The author disclaims copyright to this source code.  In place of
31445** a legal notice, here is a blessing:
31446**
31447**    May you do good and not evil.
31448**    May you find forgiveness for yourself and forgive others.
31449**    May you share freely, never taking more than you give.
31450**
31451******************************************************************************
31452**
31453** This file contains macros and a little bit of code that is common to
31454** all of the platform-specific files (os_*.c) and is #included into those
31455** files.
31456**
31457** This file should be #included by the os_*.c files only.  It is not a
31458** general purpose header file.
31459*/
31460#ifndef _OS_COMMON_H_
31461#define _OS_COMMON_H_
31462
31463/*
31464** At least two bugs have slipped in because we changed the MEMORY_DEBUG
31465** macro to SQLITE_DEBUG and some older makefiles have not yet made the
31466** switch.  The following code should catch this problem at compile-time.
31467*/
31468#ifdef MEMORY_DEBUG
31469# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
31470#endif
31471
31472#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
31473# ifndef SQLITE_DEBUG_OS_TRACE
31474#   define SQLITE_DEBUG_OS_TRACE 0
31475# endif
31476  int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
31477# define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
31478#else
31479# define OSTRACE(X)
31480#endif
31481
31482/*
31483** Macros for performance tracing.  Normally turned off.  Only works
31484** on i486 hardware.
31485*/
31486#ifdef SQLITE_PERFORMANCE_TRACE
31487
31488/*
31489** hwtime.h contains inline assembler code for implementing
31490** high-performance timing routines.
31491*/
31492/************** Include hwtime.h in the middle of os_common.h ****************/
31493/************** Begin file hwtime.h ******************************************/
31494/*
31495** 2008 May 27
31496**
31497** The author disclaims copyright to this source code.  In place of
31498** a legal notice, here is a blessing:
31499**
31500**    May you do good and not evil.
31501**    May you find forgiveness for yourself and forgive others.
31502**    May you share freely, never taking more than you give.
31503**
31504******************************************************************************
31505**
31506** This file contains inline asm code for retrieving "high-performance"
31507** counters for x86 class CPUs.
31508*/
31509#ifndef _HWTIME_H_
31510#define _HWTIME_H_
31511
31512/*
31513** The following routine only works on pentium-class (or newer) processors.
31514** It uses the RDTSC opcode to read the cycle count value out of the
31515** processor and returns that value.  This can be used for high-res
31516** profiling.
31517*/
31518#if (defined(__GNUC__) || defined(_MSC_VER)) && \
31519      (defined(i386) || defined(__i386__) || defined(_M_IX86))
31520
31521  #if defined(__GNUC__)
31522
31523  __inline__ sqlite_uint64 sqlite3Hwtime(void){
31524     unsigned int lo, hi;
31525     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
31526     return (sqlite_uint64)hi << 32 | lo;
31527  }
31528
31529  #elif defined(_MSC_VER)
31530
31531  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
31532     __asm {
31533        rdtsc
31534        ret       ; return value at EDX:EAX
31535     }
31536  }
31537
31538  #endif
31539
31540#elif (defined(__GNUC__) && defined(__x86_64__))
31541
31542  __inline__ sqlite_uint64 sqlite3Hwtime(void){
31543      unsigned long val;
31544      __asm__ __volatile__ ("rdtsc" : "=A" (val));
31545      return val;
31546  }
31547
31548#elif (defined(__GNUC__) && defined(__ppc__))
31549
31550  __inline__ sqlite_uint64 sqlite3Hwtime(void){
31551      unsigned long long retval;
31552      unsigned long junk;
31553      __asm__ __volatile__ ("\n\
31554          1:      mftbu   %1\n\
31555                  mftb    %L0\n\
31556                  mftbu   %0\n\
31557                  cmpw    %0,%1\n\
31558                  bne     1b"
31559                  : "=r" (retval), "=r" (junk));
31560      return retval;
31561  }
31562
31563#else
31564
31565  #error Need implementation of sqlite3Hwtime() for your platform.
31566
31567  /*
31568  ** To compile without implementing sqlite3Hwtime() for your platform,
31569  ** you can remove the above #error and use the following
31570  ** stub function.  You will lose timing support for many
31571  ** of the debugging and testing utilities, but it should at
31572  ** least compile and run.
31573  */
31574SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
31575
31576#endif
31577
31578#endif /* !defined(_HWTIME_H_) */
31579
31580/************** End of hwtime.h **********************************************/
31581/************** Continuing where we left off in os_common.h ******************/
31582
31583static sqlite_uint64 g_start;
31584static sqlite_uint64 g_elapsed;
31585#define TIMER_START       g_start=sqlite3Hwtime()
31586#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
31587#define TIMER_ELAPSED     g_elapsed
31588#else
31589#define TIMER_START
31590#define TIMER_END
31591#define TIMER_ELAPSED     ((sqlite_uint64)0)
31592#endif
31593
31594/*
31595** If we compile with the SQLITE_TEST macro set, then the following block
31596** of code will give us the ability to simulate a disk I/O error.  This
31597** is used for testing the I/O recovery logic.
31598*/
31599#ifdef SQLITE_TEST
31600SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
31601SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
31602SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
31603SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
31604SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
31605SQLITE_API int sqlite3_diskfull_pending = 0;
31606SQLITE_API int sqlite3_diskfull = 0;
31607#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
31608#define SimulateIOError(CODE)  \
31609  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
31610       || sqlite3_io_error_pending-- == 1 )  \
31611              { local_ioerr(); CODE; }
31612static void local_ioerr(){
31613  IOTRACE(("IOERR\n"));
31614  sqlite3_io_error_hit++;
31615  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
31616}
31617#define SimulateDiskfullError(CODE) \
31618   if( sqlite3_diskfull_pending ){ \
31619     if( sqlite3_diskfull_pending == 1 ){ \
31620       local_ioerr(); \
31621       sqlite3_diskfull = 1; \
31622       sqlite3_io_error_hit = 1; \
31623       CODE; \
31624     }else{ \
31625       sqlite3_diskfull_pending--; \
31626     } \
31627   }
31628#else
31629#define SimulateIOErrorBenign(X)
31630#define SimulateIOError(A)
31631#define SimulateDiskfullError(A)
31632#endif
31633
31634/*
31635** When testing, keep a count of the number of open files.
31636*/
31637#ifdef SQLITE_TEST
31638SQLITE_API int sqlite3_open_file_count = 0;
31639#define OpenCounter(X)  sqlite3_open_file_count+=(X)
31640#else
31641#define OpenCounter(X)
31642#endif
31643
31644#endif /* !defined(_OS_COMMON_H_) */
31645
31646/************** End of os_common.h *******************************************/
31647/************** Continuing where we left off in os_win.c *********************/
31648
31649/*
31650** Include the header file for the Windows VFS.
31651*/
31652
31653/*
31654** Compiling and using WAL mode requires several APIs that are only
31655** available in Windows platforms based on the NT kernel.
31656*/
31657#if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
31658#  error "WAL mode requires support from the Windows NT kernel, compile\
31659 with SQLITE_OMIT_WAL."
31660#endif
31661
31662/*
31663** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
31664** based on the sub-platform)?
31665*/
31666#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
31667#  define SQLITE_WIN32_HAS_ANSI
31668#endif
31669
31670/*
31671** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
31672** based on the sub-platform)?
31673*/
31674#if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
31675    !defined(SQLITE_WIN32_NO_WIDE)
31676#  define SQLITE_WIN32_HAS_WIDE
31677#endif
31678
31679/*
31680** Make sure at least one set of Win32 APIs is available.
31681*/
31682#if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
31683#  error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
31684 must be defined."
31685#endif
31686
31687/*
31688** Define the required Windows SDK version constants if they are not
31689** already available.
31690*/
31691#ifndef NTDDI_WIN8
31692#  define NTDDI_WIN8                        0x06020000
31693#endif
31694
31695#ifndef NTDDI_WINBLUE
31696#  define NTDDI_WINBLUE                     0x06030000
31697#endif
31698
31699/*
31700** Check if the GetVersionEx[AW] functions should be considered deprecated
31701** and avoid using them in that case.  It should be noted here that if the
31702** value of the SQLITE_WIN32_GETVERSIONEX pre-processor macro is zero
31703** (whether via this block or via being manually specified), that implies
31704** the underlying operating system will always be based on the Windows NT
31705** Kernel.
31706*/
31707#ifndef SQLITE_WIN32_GETVERSIONEX
31708#  if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
31709#    define SQLITE_WIN32_GETVERSIONEX   0
31710#  else
31711#    define SQLITE_WIN32_GETVERSIONEX   1
31712#  endif
31713#endif
31714
31715/*
31716** This constant should already be defined (in the "WinDef.h" SDK file).
31717*/
31718#ifndef MAX_PATH
31719#  define MAX_PATH                      (260)
31720#endif
31721
31722/*
31723** Maximum pathname length (in chars) for Win32.  This should normally be
31724** MAX_PATH.
31725*/
31726#ifndef SQLITE_WIN32_MAX_PATH_CHARS
31727#  define SQLITE_WIN32_MAX_PATH_CHARS   (MAX_PATH)
31728#endif
31729
31730/*
31731** This constant should already be defined (in the "WinNT.h" SDK file).
31732*/
31733#ifndef UNICODE_STRING_MAX_CHARS
31734#  define UNICODE_STRING_MAX_CHARS      (32767)
31735#endif
31736
31737/*
31738** Maximum pathname length (in chars) for WinNT.  This should normally be
31739** UNICODE_STRING_MAX_CHARS.
31740*/
31741#ifndef SQLITE_WINNT_MAX_PATH_CHARS
31742#  define SQLITE_WINNT_MAX_PATH_CHARS   (UNICODE_STRING_MAX_CHARS)
31743#endif
31744
31745/*
31746** Maximum pathname length (in bytes) for Win32.  The MAX_PATH macro is in
31747** characters, so we allocate 4 bytes per character assuming worst-case of
31748** 4-bytes-per-character for UTF8.
31749*/
31750#ifndef SQLITE_WIN32_MAX_PATH_BYTES
31751#  define SQLITE_WIN32_MAX_PATH_BYTES   (SQLITE_WIN32_MAX_PATH_CHARS*4)
31752#endif
31753
31754/*
31755** Maximum pathname length (in bytes) for WinNT.  This should normally be
31756** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
31757*/
31758#ifndef SQLITE_WINNT_MAX_PATH_BYTES
31759#  define SQLITE_WINNT_MAX_PATH_BYTES   \
31760                            (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
31761#endif
31762
31763/*
31764** Maximum error message length (in chars) for WinRT.
31765*/
31766#ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
31767#  define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
31768#endif
31769
31770/*
31771** Returns non-zero if the character should be treated as a directory
31772** separator.
31773*/
31774#ifndef winIsDirSep
31775#  define winIsDirSep(a)                (((a) == '/') || ((a) == '\\'))
31776#endif
31777
31778/*
31779** This macro is used when a local variable is set to a value that is
31780** [sometimes] not used by the code (e.g. via conditional compilation).
31781*/
31782#ifndef UNUSED_VARIABLE_VALUE
31783#  define UNUSED_VARIABLE_VALUE(x) (void)(x)
31784#endif
31785
31786/*
31787** Returns the character that should be used as the directory separator.
31788*/
31789#ifndef winGetDirSep
31790#  define winGetDirSep()                '\\'
31791#endif
31792
31793/*
31794** Do we need to manually define the Win32 file mapping APIs for use with WAL
31795** mode (e.g. these APIs are available in the Windows CE SDK; however, they
31796** are not present in the header file)?
31797*/
31798#if SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL)
31799/*
31800** Two of the file mapping APIs are different under WinRT.  Figure out which
31801** set we need.
31802*/
31803#if SQLITE_OS_WINRT
31804WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
31805        LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
31806
31807WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
31808#else
31809#if defined(SQLITE_WIN32_HAS_ANSI)
31810WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
31811        DWORD, DWORD, DWORD, LPCSTR);
31812#endif /* defined(SQLITE_WIN32_HAS_ANSI) */
31813
31814#if defined(SQLITE_WIN32_HAS_WIDE)
31815WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
31816        DWORD, DWORD, DWORD, LPCWSTR);
31817#endif /* defined(SQLITE_WIN32_HAS_WIDE) */
31818
31819WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
31820#endif /* SQLITE_OS_WINRT */
31821
31822/*
31823** This file mapping API is common to both Win32 and WinRT.
31824*/
31825WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
31826#endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */
31827
31828/*
31829** Some Microsoft compilers lack this definition.
31830*/
31831#ifndef INVALID_FILE_ATTRIBUTES
31832# define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
31833#endif
31834
31835#ifndef FILE_FLAG_MASK
31836# define FILE_FLAG_MASK          (0xFF3C0000)
31837#endif
31838
31839#ifndef FILE_ATTRIBUTE_MASK
31840# define FILE_ATTRIBUTE_MASK     (0x0003FFF7)
31841#endif
31842
31843#ifndef SQLITE_OMIT_WAL
31844/* Forward references to structures used for WAL */
31845typedef struct winShm winShm;           /* A connection to shared-memory */
31846typedef struct winShmNode winShmNode;   /* A region of shared-memory */
31847#endif
31848
31849/*
31850** WinCE lacks native support for file locking so we have to fake it
31851** with some code of our own.
31852*/
31853#if SQLITE_OS_WINCE
31854typedef struct winceLock {
31855  int nReaders;       /* Number of reader locks obtained */
31856  BOOL bPending;      /* Indicates a pending lock has been obtained */
31857  BOOL bReserved;     /* Indicates a reserved lock has been obtained */
31858  BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
31859} winceLock;
31860#endif
31861
31862/*
31863** The winFile structure is a subclass of sqlite3_file* specific to the win32
31864** portability layer.
31865*/
31866typedef struct winFile winFile;
31867struct winFile {
31868  const sqlite3_io_methods *pMethod; /*** Must be first ***/
31869  sqlite3_vfs *pVfs;      /* The VFS used to open this file */
31870  HANDLE h;               /* Handle for accessing the file */
31871  u8 locktype;            /* Type of lock currently held on this file */
31872  short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
31873  u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
31874  DWORD lastErrno;        /* The Windows errno from the last I/O error */
31875#ifndef SQLITE_OMIT_WAL
31876  winShm *pShm;           /* Instance of shared memory on this file */
31877#endif
31878  const char *zPath;      /* Full pathname of this file */
31879  int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
31880#if SQLITE_OS_WINCE
31881  LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
31882  HANDLE hMutex;          /* Mutex used to control access to shared lock */
31883  HANDLE hShared;         /* Shared memory segment used for locking */
31884  winceLock local;        /* Locks obtained by this instance of winFile */
31885  winceLock *shared;      /* Global shared lock memory for the file  */
31886#endif
31887#if SQLITE_MAX_MMAP_SIZE>0
31888  int nFetchOut;                /* Number of outstanding xFetch references */
31889  HANDLE hMap;                  /* Handle for accessing memory mapping */
31890  void *pMapRegion;             /* Area memory mapped */
31891  sqlite3_int64 mmapSize;       /* Usable size of mapped region */
31892  sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
31893  sqlite3_int64 mmapSizeMax;    /* Configured FCNTL_MMAP_SIZE value */
31894#endif
31895};
31896
31897/*
31898** Allowed values for winFile.ctrlFlags
31899*/
31900#define WINFILE_RDONLY          0x02   /* Connection is read only */
31901#define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
31902#define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
31903
31904/*
31905 * The size of the buffer used by sqlite3_win32_write_debug().
31906 */
31907#ifndef SQLITE_WIN32_DBG_BUF_SIZE
31908#  define SQLITE_WIN32_DBG_BUF_SIZE   ((int)(4096-sizeof(DWORD)))
31909#endif
31910
31911/*
31912 * The value used with sqlite3_win32_set_directory() to specify that
31913 * the data directory should be changed.
31914 */
31915#ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
31916#  define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
31917#endif
31918
31919/*
31920 * The value used with sqlite3_win32_set_directory() to specify that
31921 * the temporary directory should be changed.
31922 */
31923#ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
31924#  define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
31925#endif
31926
31927/*
31928 * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
31929 * various Win32 API heap functions instead of our own.
31930 */
31931#ifdef SQLITE_WIN32_MALLOC
31932
31933/*
31934 * If this is non-zero, an isolated heap will be created by the native Win32
31935 * allocator subsystem; otherwise, the default process heap will be used.  This
31936 * setting has no effect when compiling for WinRT.  By default, this is enabled
31937 * and an isolated heap will be created to store all allocated data.
31938 *
31939 ******************************************************************************
31940 * WARNING: It is important to note that when this setting is non-zero and the
31941 *          winMemShutdown function is called (e.g. by the sqlite3_shutdown
31942 *          function), all data that was allocated using the isolated heap will
31943 *          be freed immediately and any attempt to access any of that freed
31944 *          data will almost certainly result in an immediate access violation.
31945 ******************************************************************************
31946 */
31947#ifndef SQLITE_WIN32_HEAP_CREATE
31948#  define SQLITE_WIN32_HEAP_CREATE    (TRUE)
31949#endif
31950
31951/*
31952 * The initial size of the Win32-specific heap.  This value may be zero.
31953 */
31954#ifndef SQLITE_WIN32_HEAP_INIT_SIZE
31955#  define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
31956                                       (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
31957#endif
31958
31959/*
31960 * The maximum size of the Win32-specific heap.  This value may be zero.
31961 */
31962#ifndef SQLITE_WIN32_HEAP_MAX_SIZE
31963#  define SQLITE_WIN32_HEAP_MAX_SIZE  (0)
31964#endif
31965
31966/*
31967 * The extra flags to use in calls to the Win32 heap APIs.  This value may be
31968 * zero for the default behavior.
31969 */
31970#ifndef SQLITE_WIN32_HEAP_FLAGS
31971#  define SQLITE_WIN32_HEAP_FLAGS     (0)
31972#endif
31973
31974
31975/*
31976** The winMemData structure stores information required by the Win32-specific
31977** sqlite3_mem_methods implementation.
31978*/
31979typedef struct winMemData winMemData;
31980struct winMemData {
31981#ifndef NDEBUG
31982  u32 magic1;   /* Magic number to detect structure corruption. */
31983#endif
31984  HANDLE hHeap; /* The handle to our heap. */
31985  BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
31986#ifndef NDEBUG
31987  u32 magic2;   /* Magic number to detect structure corruption. */
31988#endif
31989};
31990
31991#ifndef NDEBUG
31992#define WINMEM_MAGIC1     0x42b2830b
31993#define WINMEM_MAGIC2     0xbd4d7cf4
31994#endif
31995
31996static struct winMemData win_mem_data = {
31997#ifndef NDEBUG
31998  WINMEM_MAGIC1,
31999#endif
32000  NULL, FALSE
32001#ifndef NDEBUG
32002  ,WINMEM_MAGIC2
32003#endif
32004};
32005
32006#ifndef NDEBUG
32007#define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
32008#define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
32009#define winMemAssertMagic()  winMemAssertMagic1(); winMemAssertMagic2();
32010#else
32011#define winMemAssertMagic()
32012#endif
32013
32014#define winMemGetDataPtr()  &win_mem_data
32015#define winMemGetHeap()     win_mem_data.hHeap
32016#define winMemGetOwned()    win_mem_data.bOwned
32017
32018static void *winMemMalloc(int nBytes);
32019static void winMemFree(void *pPrior);
32020static void *winMemRealloc(void *pPrior, int nBytes);
32021static int winMemSize(void *p);
32022static int winMemRoundup(int n);
32023static int winMemInit(void *pAppData);
32024static void winMemShutdown(void *pAppData);
32025
32026SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
32027#endif /* SQLITE_WIN32_MALLOC */
32028
32029/*
32030** The following variable is (normally) set once and never changes
32031** thereafter.  It records whether the operating system is Win9x
32032** or WinNT.
32033**
32034** 0:   Operating system unknown.
32035** 1:   Operating system is Win9x.
32036** 2:   Operating system is WinNT.
32037**
32038** In order to facilitate testing on a WinNT system, the test fixture
32039** can manually set this value to 1 to emulate Win98 behavior.
32040*/
32041#ifdef SQLITE_TEST
32042SQLITE_API int sqlite3_os_type = 0;
32043#elif !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
32044      defined(SQLITE_WIN32_HAS_ANSI) && defined(SQLITE_WIN32_HAS_WIDE)
32045static int sqlite3_os_type = 0;
32046#endif
32047
32048#ifndef SYSCALL
32049#  define SYSCALL sqlite3_syscall_ptr
32050#endif
32051
32052/*
32053** This function is not available on Windows CE or WinRT.
32054 */
32055
32056#if SQLITE_OS_WINCE || SQLITE_OS_WINRT
32057#  define osAreFileApisANSI()       1
32058#endif
32059
32060/*
32061** Many system calls are accessed through pointer-to-functions so that
32062** they may be overridden at runtime to facilitate fault injection during
32063** testing and sandboxing.  The following array holds the names and pointers
32064** to all overrideable system calls.
32065*/
32066static struct win_syscall {
32067  const char *zName;            /* Name of the system call */
32068  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
32069  sqlite3_syscall_ptr pDefault; /* Default value */
32070} aSyscall[] = {
32071#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
32072  { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
32073#else
32074  { "AreFileApisANSI",         (SYSCALL)0,                       0 },
32075#endif
32076
32077#ifndef osAreFileApisANSI
32078#define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
32079#endif
32080
32081#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
32082  { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
32083#else
32084  { "CharLowerW",              (SYSCALL)0,                       0 },
32085#endif
32086
32087#define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
32088
32089#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
32090  { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
32091#else
32092  { "CharUpperW",              (SYSCALL)0,                       0 },
32093#endif
32094
32095#define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
32096
32097  { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
32098
32099#define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
32100
32101#if defined(SQLITE_WIN32_HAS_ANSI)
32102  { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
32103#else
32104  { "CreateFileA",             (SYSCALL)0,                       0 },
32105#endif
32106
32107#define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
32108        LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
32109
32110#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
32111  { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
32112#else
32113  { "CreateFileW",             (SYSCALL)0,                       0 },
32114#endif
32115
32116#define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
32117        LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
32118
32119#if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
32120        !defined(SQLITE_OMIT_WAL))
32121  { "CreateFileMappingA",      (SYSCALL)CreateFileMappingA,      0 },
32122#else
32123  { "CreateFileMappingA",      (SYSCALL)0,                       0 },
32124#endif
32125
32126#define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
32127        DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
32128
32129#if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
32130        !defined(SQLITE_OMIT_WAL))
32131  { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
32132#else
32133  { "CreateFileMappingW",      (SYSCALL)0,                       0 },
32134#endif
32135
32136#define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
32137        DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
32138
32139#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
32140  { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
32141#else
32142  { "CreateMutexW",            (SYSCALL)0,                       0 },
32143#endif
32144
32145#define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
32146        LPCWSTR))aSyscall[8].pCurrent)
32147
32148#if defined(SQLITE_WIN32_HAS_ANSI)
32149  { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
32150#else
32151  { "DeleteFileA",             (SYSCALL)0,                       0 },
32152#endif
32153
32154#define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
32155
32156#if defined(SQLITE_WIN32_HAS_WIDE)
32157  { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
32158#else
32159  { "DeleteFileW",             (SYSCALL)0,                       0 },
32160#endif
32161
32162#define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
32163
32164#if SQLITE_OS_WINCE
32165  { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
32166#else
32167  { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
32168#endif
32169
32170#define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
32171        LPFILETIME))aSyscall[11].pCurrent)
32172
32173#if SQLITE_OS_WINCE
32174  { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
32175#else
32176  { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
32177#endif
32178
32179#define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
32180        LPSYSTEMTIME))aSyscall[12].pCurrent)
32181
32182  { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
32183
32184#define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
32185
32186#if defined(SQLITE_WIN32_HAS_ANSI)
32187  { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
32188#else
32189  { "FormatMessageA",          (SYSCALL)0,                       0 },
32190#endif
32191
32192#define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
32193        DWORD,va_list*))aSyscall[14].pCurrent)
32194
32195#if defined(SQLITE_WIN32_HAS_WIDE)
32196  { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
32197#else
32198  { "FormatMessageW",          (SYSCALL)0,                       0 },
32199#endif
32200
32201#define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
32202        DWORD,va_list*))aSyscall[15].pCurrent)
32203
32204#if !defined(SQLITE_OMIT_LOAD_EXTENSION)
32205  { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
32206#else
32207  { "FreeLibrary",             (SYSCALL)0,                       0 },
32208#endif
32209
32210#define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
32211
32212  { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
32213
32214#define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
32215
32216#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
32217  { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
32218#else
32219  { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
32220#endif
32221
32222#define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
32223        LPDWORD))aSyscall[18].pCurrent)
32224
32225#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
32226  { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
32227#else
32228  { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
32229#endif
32230
32231#define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
32232        LPDWORD))aSyscall[19].pCurrent)
32233
32234#if defined(SQLITE_WIN32_HAS_ANSI)
32235  { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
32236#else
32237  { "GetFileAttributesA",      (SYSCALL)0,                       0 },
32238#endif
32239
32240#define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
32241
32242#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
32243  { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
32244#else
32245  { "GetFileAttributesW",      (SYSCALL)0,                       0 },
32246#endif
32247
32248#define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
32249
32250#if defined(SQLITE_WIN32_HAS_WIDE)
32251  { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
32252#else
32253  { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
32254#endif
32255
32256#define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
32257        LPVOID))aSyscall[22].pCurrent)
32258
32259#if !SQLITE_OS_WINRT
32260  { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
32261#else
32262  { "GetFileSize",             (SYSCALL)0,                       0 },
32263#endif
32264
32265#define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
32266
32267#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
32268  { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
32269#else
32270  { "GetFullPathNameA",        (SYSCALL)0,                       0 },
32271#endif
32272
32273#define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
32274        LPSTR*))aSyscall[24].pCurrent)
32275
32276#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
32277  { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
32278#else
32279  { "GetFullPathNameW",        (SYSCALL)0,                       0 },
32280#endif
32281
32282#define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
32283        LPWSTR*))aSyscall[25].pCurrent)
32284
32285  { "GetLastError",            (SYSCALL)GetLastError,            0 },
32286
32287#define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
32288
32289#if !defined(SQLITE_OMIT_LOAD_EXTENSION)
32290#if SQLITE_OS_WINCE
32291  /* The GetProcAddressA() routine is only available on Windows CE. */
32292  { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
32293#else
32294  /* All other Windows platforms expect GetProcAddress() to take
32295  ** an ANSI string regardless of the _UNICODE setting */
32296  { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
32297#endif
32298#else
32299  { "GetProcAddressA",         (SYSCALL)0,                       0 },
32300#endif
32301
32302#define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
32303        LPCSTR))aSyscall[27].pCurrent)
32304
32305#if !SQLITE_OS_WINRT
32306  { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
32307#else
32308  { "GetSystemInfo",           (SYSCALL)0,                       0 },
32309#endif
32310
32311#define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
32312
32313  { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
32314
32315#define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
32316
32317#if !SQLITE_OS_WINCE
32318  { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
32319#else
32320  { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
32321#endif
32322
32323#define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
32324        LPFILETIME))aSyscall[30].pCurrent)
32325
32326#if defined(SQLITE_WIN32_HAS_ANSI)
32327  { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
32328#else
32329  { "GetTempPathA",            (SYSCALL)0,                       0 },
32330#endif
32331
32332#define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
32333
32334#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
32335  { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
32336#else
32337  { "GetTempPathW",            (SYSCALL)0,                       0 },
32338#endif
32339
32340#define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
32341
32342#if !SQLITE_OS_WINRT
32343  { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
32344#else
32345  { "GetTickCount",            (SYSCALL)0,                       0 },
32346#endif
32347
32348#define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
32349
32350#if defined(SQLITE_WIN32_HAS_ANSI) && defined(SQLITE_WIN32_GETVERSIONEX) && \
32351        SQLITE_WIN32_GETVERSIONEX
32352  { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
32353#else
32354  { "GetVersionExA",           (SYSCALL)0,                       0 },
32355#endif
32356
32357#define osGetVersionExA ((BOOL(WINAPI*)( \
32358        LPOSVERSIONINFOA))aSyscall[34].pCurrent)
32359
32360#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
32361        defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
32362  { "GetVersionExW",           (SYSCALL)GetVersionExW,           0 },
32363#else
32364  { "GetVersionExW",           (SYSCALL)0,                       0 },
32365#endif
32366
32367#define osGetVersionExW ((BOOL(WINAPI*)( \
32368        LPOSVERSIONINFOW))aSyscall[35].pCurrent)
32369
32370  { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
32371
32372#define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
32373        SIZE_T))aSyscall[36].pCurrent)
32374
32375#if !SQLITE_OS_WINRT
32376  { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
32377#else
32378  { "HeapCreate",              (SYSCALL)0,                       0 },
32379#endif
32380
32381#define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
32382        SIZE_T))aSyscall[37].pCurrent)
32383
32384#if !SQLITE_OS_WINRT
32385  { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
32386#else
32387  { "HeapDestroy",             (SYSCALL)0,                       0 },
32388#endif
32389
32390#define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
32391
32392  { "HeapFree",                (SYSCALL)HeapFree,                0 },
32393
32394#define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
32395
32396  { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
32397
32398#define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
32399        SIZE_T))aSyscall[40].pCurrent)
32400
32401  { "HeapSize",                (SYSCALL)HeapSize,                0 },
32402
32403#define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
32404        LPCVOID))aSyscall[41].pCurrent)
32405
32406#if !SQLITE_OS_WINRT
32407  { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
32408#else
32409  { "HeapValidate",            (SYSCALL)0,                       0 },
32410#endif
32411
32412#define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
32413        LPCVOID))aSyscall[42].pCurrent)
32414
32415#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
32416  { "HeapCompact",             (SYSCALL)HeapCompact,             0 },
32417#else
32418  { "HeapCompact",             (SYSCALL)0,                       0 },
32419#endif
32420
32421#define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
32422
32423#if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
32424  { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
32425#else
32426  { "LoadLibraryA",            (SYSCALL)0,                       0 },
32427#endif
32428
32429#define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
32430
32431#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
32432        !defined(SQLITE_OMIT_LOAD_EXTENSION)
32433  { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
32434#else
32435  { "LoadLibraryW",            (SYSCALL)0,                       0 },
32436#endif
32437
32438#define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
32439
32440#if !SQLITE_OS_WINRT
32441  { "LocalFree",               (SYSCALL)LocalFree,               0 },
32442#else
32443  { "LocalFree",               (SYSCALL)0,                       0 },
32444#endif
32445
32446#define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
32447
32448#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
32449  { "LockFile",                (SYSCALL)LockFile,                0 },
32450#else
32451  { "LockFile",                (SYSCALL)0,                       0 },
32452#endif
32453
32454#ifndef osLockFile
32455#define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
32456        DWORD))aSyscall[47].pCurrent)
32457#endif
32458
32459#if !SQLITE_OS_WINCE
32460  { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
32461#else
32462  { "LockFileEx",              (SYSCALL)0,                       0 },
32463#endif
32464
32465#ifndef osLockFileEx
32466#define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
32467        LPOVERLAPPED))aSyscall[48].pCurrent)
32468#endif
32469
32470#if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL))
32471  { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
32472#else
32473  { "MapViewOfFile",           (SYSCALL)0,                       0 },
32474#endif
32475
32476#define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
32477        SIZE_T))aSyscall[49].pCurrent)
32478
32479  { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
32480
32481#define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
32482        int))aSyscall[50].pCurrent)
32483
32484  { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
32485
32486#define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
32487        LARGE_INTEGER*))aSyscall[51].pCurrent)
32488
32489  { "ReadFile",                (SYSCALL)ReadFile,                0 },
32490
32491#define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
32492        LPOVERLAPPED))aSyscall[52].pCurrent)
32493
32494  { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
32495
32496#define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
32497
32498#if !SQLITE_OS_WINRT
32499  { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
32500#else
32501  { "SetFilePointer",          (SYSCALL)0,                       0 },
32502#endif
32503
32504#define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
32505        DWORD))aSyscall[54].pCurrent)
32506
32507#if !SQLITE_OS_WINRT
32508  { "Sleep",                   (SYSCALL)Sleep,                   0 },
32509#else
32510  { "Sleep",                   (SYSCALL)0,                       0 },
32511#endif
32512
32513#define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
32514
32515  { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
32516
32517#define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
32518        LPFILETIME))aSyscall[56].pCurrent)
32519
32520#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
32521  { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
32522#else
32523  { "UnlockFile",              (SYSCALL)0,                       0 },
32524#endif
32525
32526#ifndef osUnlockFile
32527#define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
32528        DWORD))aSyscall[57].pCurrent)
32529#endif
32530
32531#if !SQLITE_OS_WINCE
32532  { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
32533#else
32534  { "UnlockFileEx",            (SYSCALL)0,                       0 },
32535#endif
32536
32537#define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
32538        LPOVERLAPPED))aSyscall[58].pCurrent)
32539
32540#if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL)
32541  { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
32542#else
32543  { "UnmapViewOfFile",         (SYSCALL)0,                       0 },
32544#endif
32545
32546#define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
32547
32548  { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
32549
32550#define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
32551        LPCSTR,LPBOOL))aSyscall[60].pCurrent)
32552
32553  { "WriteFile",               (SYSCALL)WriteFile,               0 },
32554
32555#define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
32556        LPOVERLAPPED))aSyscall[61].pCurrent)
32557
32558#if SQLITE_OS_WINRT
32559  { "CreateEventExW",          (SYSCALL)CreateEventExW,          0 },
32560#else
32561  { "CreateEventExW",          (SYSCALL)0,                       0 },
32562#endif
32563
32564#define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
32565        DWORD,DWORD))aSyscall[62].pCurrent)
32566
32567#if !SQLITE_OS_WINRT
32568  { "WaitForSingleObject",     (SYSCALL)WaitForSingleObject,     0 },
32569#else
32570  { "WaitForSingleObject",     (SYSCALL)0,                       0 },
32571#endif
32572
32573#define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
32574        DWORD))aSyscall[63].pCurrent)
32575
32576#if SQLITE_OS_WINRT
32577  { "WaitForSingleObjectEx",   (SYSCALL)WaitForSingleObjectEx,   0 },
32578#else
32579  { "WaitForSingleObjectEx",   (SYSCALL)0,                       0 },
32580#endif
32581
32582#define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
32583        BOOL))aSyscall[64].pCurrent)
32584
32585#if SQLITE_OS_WINRT
32586  { "SetFilePointerEx",        (SYSCALL)SetFilePointerEx,        0 },
32587#else
32588  { "SetFilePointerEx",        (SYSCALL)0,                       0 },
32589#endif
32590
32591#define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
32592        PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
32593
32594#if SQLITE_OS_WINRT
32595  { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
32596#else
32597  { "GetFileInformationByHandleEx", (SYSCALL)0,                  0 },
32598#endif
32599
32600#define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
32601        FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
32602
32603#if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
32604  { "MapViewOfFileFromApp",    (SYSCALL)MapViewOfFileFromApp,    0 },
32605#else
32606  { "MapViewOfFileFromApp",    (SYSCALL)0,                       0 },
32607#endif
32608
32609#define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
32610        SIZE_T))aSyscall[67].pCurrent)
32611
32612#if SQLITE_OS_WINRT
32613  { "CreateFile2",             (SYSCALL)CreateFile2,             0 },
32614#else
32615  { "CreateFile2",             (SYSCALL)0,                       0 },
32616#endif
32617
32618#define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
32619        LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
32620
32621#if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
32622  { "LoadPackagedLibrary",     (SYSCALL)LoadPackagedLibrary,     0 },
32623#else
32624  { "LoadPackagedLibrary",     (SYSCALL)0,                       0 },
32625#endif
32626
32627#define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
32628        DWORD))aSyscall[69].pCurrent)
32629
32630#if SQLITE_OS_WINRT
32631  { "GetTickCount64",          (SYSCALL)GetTickCount64,          0 },
32632#else
32633  { "GetTickCount64",          (SYSCALL)0,                       0 },
32634#endif
32635
32636#define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
32637
32638#if SQLITE_OS_WINRT
32639  { "GetNativeSystemInfo",     (SYSCALL)GetNativeSystemInfo,     0 },
32640#else
32641  { "GetNativeSystemInfo",     (SYSCALL)0,                       0 },
32642#endif
32643
32644#define osGetNativeSystemInfo ((VOID(WINAPI*)( \
32645        LPSYSTEM_INFO))aSyscall[71].pCurrent)
32646
32647#if defined(SQLITE_WIN32_HAS_ANSI)
32648  { "OutputDebugStringA",      (SYSCALL)OutputDebugStringA,      0 },
32649#else
32650  { "OutputDebugStringA",      (SYSCALL)0,                       0 },
32651#endif
32652
32653#define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
32654
32655#if defined(SQLITE_WIN32_HAS_WIDE)
32656  { "OutputDebugStringW",      (SYSCALL)OutputDebugStringW,      0 },
32657#else
32658  { "OutputDebugStringW",      (SYSCALL)0,                       0 },
32659#endif
32660
32661#define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
32662
32663  { "GetProcessHeap",          (SYSCALL)GetProcessHeap,          0 },
32664
32665#define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
32666
32667#if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
32668  { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
32669#else
32670  { "CreateFileMappingFromApp", (SYSCALL)0,                      0 },
32671#endif
32672
32673#define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
32674        LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
32675
32676}; /* End of the overrideable system calls */
32677
32678/*
32679** This is the xSetSystemCall() method of sqlite3_vfs for all of the
32680** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
32681** system call pointer, or SQLITE_NOTFOUND if there is no configurable
32682** system call named zName.
32683*/
32684static int winSetSystemCall(
32685  sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
32686  const char *zName,            /* Name of system call to override */
32687  sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
32688){
32689  unsigned int i;
32690  int rc = SQLITE_NOTFOUND;
32691
32692  UNUSED_PARAMETER(pNotUsed);
32693  if( zName==0 ){
32694    /* If no zName is given, restore all system calls to their default
32695    ** settings and return NULL
32696    */
32697    rc = SQLITE_OK;
32698    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
32699      if( aSyscall[i].pDefault ){
32700        aSyscall[i].pCurrent = aSyscall[i].pDefault;
32701      }
32702    }
32703  }else{
32704    /* If zName is specified, operate on only the one system call
32705    ** specified.
32706    */
32707    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
32708      if( strcmp(zName, aSyscall[i].zName)==0 ){
32709        if( aSyscall[i].pDefault==0 ){
32710          aSyscall[i].pDefault = aSyscall[i].pCurrent;
32711        }
32712        rc = SQLITE_OK;
32713        if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
32714        aSyscall[i].pCurrent = pNewFunc;
32715        break;
32716      }
32717    }
32718  }
32719  return rc;
32720}
32721
32722/*
32723** Return the value of a system call.  Return NULL if zName is not a
32724** recognized system call name.  NULL is also returned if the system call
32725** is currently undefined.
32726*/
32727static sqlite3_syscall_ptr winGetSystemCall(
32728  sqlite3_vfs *pNotUsed,
32729  const char *zName
32730){
32731  unsigned int i;
32732
32733  UNUSED_PARAMETER(pNotUsed);
32734  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
32735    if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
32736  }
32737  return 0;
32738}
32739
32740/*
32741** Return the name of the first system call after zName.  If zName==NULL
32742** then return the name of the first system call.  Return NULL if zName
32743** is the last system call or if zName is not the name of a valid
32744** system call.
32745*/
32746static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
32747  int i = -1;
32748
32749  UNUSED_PARAMETER(p);
32750  if( zName ){
32751    for(i=0; i<ArraySize(aSyscall)-1; i++){
32752      if( strcmp(zName, aSyscall[i].zName)==0 ) break;
32753    }
32754  }
32755  for(i++; i<ArraySize(aSyscall); i++){
32756    if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
32757  }
32758  return 0;
32759}
32760
32761#ifdef SQLITE_WIN32_MALLOC
32762/*
32763** If a Win32 native heap has been configured, this function will attempt to
32764** compact it.  Upon success, SQLITE_OK will be returned.  Upon failure, one
32765** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned.  The
32766** "pnLargest" argument, if non-zero, will be used to return the size of the
32767** largest committed free block in the heap, in bytes.
32768*/
32769SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
32770  int rc = SQLITE_OK;
32771  UINT nLargest = 0;
32772  HANDLE hHeap;
32773
32774  winMemAssertMagic();
32775  hHeap = winMemGetHeap();
32776  assert( hHeap!=0 );
32777  assert( hHeap!=INVALID_HANDLE_VALUE );
32778#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
32779  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
32780#endif
32781#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
32782  if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
32783    DWORD lastErrno = osGetLastError();
32784    if( lastErrno==NO_ERROR ){
32785      sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
32786                  (void*)hHeap);
32787      rc = SQLITE_NOMEM;
32788    }else{
32789      sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
32790                  osGetLastError(), (void*)hHeap);
32791      rc = SQLITE_ERROR;
32792    }
32793  }
32794#else
32795  sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
32796              (void*)hHeap);
32797  rc = SQLITE_NOTFOUND;
32798#endif
32799  if( pnLargest ) *pnLargest = nLargest;
32800  return rc;
32801}
32802
32803/*
32804** If a Win32 native heap has been configured, this function will attempt to
32805** destroy and recreate it.  If the Win32 native heap is not isolated and/or
32806** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
32807** be returned and no changes will be made to the Win32 native heap.
32808*/
32809SQLITE_API int sqlite3_win32_reset_heap(){
32810  int rc;
32811  MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
32812  MUTEX_LOGIC( sqlite3_mutex *pMem; )    /* The memsys static mutex */
32813  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
32814  MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
32815  sqlite3_mutex_enter(pMaster);
32816  sqlite3_mutex_enter(pMem);
32817  winMemAssertMagic();
32818  if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
32819    /*
32820    ** At this point, there should be no outstanding memory allocations on
32821    ** the heap.  Also, since both the master and memsys locks are currently
32822    ** being held by us, no other function (i.e. from another thread) should
32823    ** be able to even access the heap.  Attempt to destroy and recreate our
32824    ** isolated Win32 native heap now.
32825    */
32826    assert( winMemGetHeap()!=NULL );
32827    assert( winMemGetOwned() );
32828    assert( sqlite3_memory_used()==0 );
32829    winMemShutdown(winMemGetDataPtr());
32830    assert( winMemGetHeap()==NULL );
32831    assert( !winMemGetOwned() );
32832    assert( sqlite3_memory_used()==0 );
32833    rc = winMemInit(winMemGetDataPtr());
32834    assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
32835    assert( rc!=SQLITE_OK || winMemGetOwned() );
32836    assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
32837  }else{
32838    /*
32839    ** The Win32 native heap cannot be modified because it may be in use.
32840    */
32841    rc = SQLITE_BUSY;
32842  }
32843  sqlite3_mutex_leave(pMem);
32844  sqlite3_mutex_leave(pMaster);
32845  return rc;
32846}
32847#endif /* SQLITE_WIN32_MALLOC */
32848
32849/*
32850** This function outputs the specified (ANSI) string to the Win32 debugger
32851** (if available).
32852*/
32853
32854SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
32855  char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
32856  int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
32857  if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
32858  assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
32859#if defined(SQLITE_WIN32_HAS_ANSI)
32860  if( nMin>0 ){
32861    memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
32862    memcpy(zDbgBuf, zBuf, nMin);
32863    osOutputDebugStringA(zDbgBuf);
32864  }else{
32865    osOutputDebugStringA(zBuf);
32866  }
32867#elif defined(SQLITE_WIN32_HAS_WIDE)
32868  memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
32869  if ( osMultiByteToWideChar(
32870          osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
32871          nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
32872    return;
32873  }
32874  osOutputDebugStringW((LPCWSTR)zDbgBuf);
32875#else
32876  if( nMin>0 ){
32877    memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
32878    memcpy(zDbgBuf, zBuf, nMin);
32879    fprintf(stderr, "%s", zDbgBuf);
32880  }else{
32881    fprintf(stderr, "%s", zBuf);
32882  }
32883#endif
32884}
32885
32886/*
32887** The following routine suspends the current thread for at least ms
32888** milliseconds.  This is equivalent to the Win32 Sleep() interface.
32889*/
32890#if SQLITE_OS_WINRT
32891static HANDLE sleepObj = NULL;
32892#endif
32893
32894SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
32895#if SQLITE_OS_WINRT
32896  if ( sleepObj==NULL ){
32897    sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
32898                                SYNCHRONIZE);
32899  }
32900  assert( sleepObj!=NULL );
32901  osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
32902#else
32903  osSleep(milliseconds);
32904#endif
32905}
32906
32907/*
32908** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
32909** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
32910**
32911** Here is an interesting observation:  Win95, Win98, and WinME lack
32912** the LockFileEx() API.  But we can still statically link against that
32913** API as long as we don't call it when running Win95/98/ME.  A call to
32914** this routine is used to determine if the host is Win95/98/ME or
32915** WinNT/2K/XP so that we will know whether or not we can safely call
32916** the LockFileEx() API.
32917*/
32918
32919#if !defined(SQLITE_WIN32_GETVERSIONEX) || !SQLITE_WIN32_GETVERSIONEX
32920# define osIsNT()  (1)
32921#elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
32922# define osIsNT()  (1)
32923#elif !defined(SQLITE_WIN32_HAS_WIDE)
32924# define osIsNT()  (0)
32925#else
32926  static int osIsNT(void){
32927    if( sqlite3_os_type==0 ){
32928#if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WIN8
32929      OSVERSIONINFOW sInfo;
32930      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
32931      osGetVersionExW(&sInfo);
32932#else
32933      OSVERSIONINFOA sInfo;
32934      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
32935      osGetVersionExA(&sInfo);
32936#endif
32937      sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
32938    }
32939    return sqlite3_os_type==2;
32940  }
32941#endif
32942
32943#ifdef SQLITE_WIN32_MALLOC
32944/*
32945** Allocate nBytes of memory.
32946*/
32947static void *winMemMalloc(int nBytes){
32948  HANDLE hHeap;
32949  void *p;
32950
32951  winMemAssertMagic();
32952  hHeap = winMemGetHeap();
32953  assert( hHeap!=0 );
32954  assert( hHeap!=INVALID_HANDLE_VALUE );
32955#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
32956  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
32957#endif
32958  assert( nBytes>=0 );
32959  p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
32960  if( !p ){
32961    sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
32962                nBytes, osGetLastError(), (void*)hHeap);
32963  }
32964  return p;
32965}
32966
32967/*
32968** Free memory.
32969*/
32970static void winMemFree(void *pPrior){
32971  HANDLE hHeap;
32972
32973  winMemAssertMagic();
32974  hHeap = winMemGetHeap();
32975  assert( hHeap!=0 );
32976  assert( hHeap!=INVALID_HANDLE_VALUE );
32977#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
32978  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
32979#endif
32980  if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
32981  if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
32982    sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
32983                pPrior, osGetLastError(), (void*)hHeap);
32984  }
32985}
32986
32987/*
32988** Change the size of an existing memory allocation
32989*/
32990static void *winMemRealloc(void *pPrior, int nBytes){
32991  HANDLE hHeap;
32992  void *p;
32993
32994  winMemAssertMagic();
32995  hHeap = winMemGetHeap();
32996  assert( hHeap!=0 );
32997  assert( hHeap!=INVALID_HANDLE_VALUE );
32998#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
32999  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
33000#endif
33001  assert( nBytes>=0 );
33002  if( !pPrior ){
33003    p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
33004  }else{
33005    p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
33006  }
33007  if( !p ){
33008    sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
33009                pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
33010                (void*)hHeap);
33011  }
33012  return p;
33013}
33014
33015/*
33016** Return the size of an outstanding allocation, in bytes.
33017*/
33018static int winMemSize(void *p){
33019  HANDLE hHeap;
33020  SIZE_T n;
33021
33022  winMemAssertMagic();
33023  hHeap = winMemGetHeap();
33024  assert( hHeap!=0 );
33025  assert( hHeap!=INVALID_HANDLE_VALUE );
33026#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
33027  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
33028#endif
33029  if( !p ) return 0;
33030  n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
33031  if( n==(SIZE_T)-1 ){
33032    sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
33033                p, osGetLastError(), (void*)hHeap);
33034    return 0;
33035  }
33036  return (int)n;
33037}
33038
33039/*
33040** Round up a request size to the next valid allocation size.
33041*/
33042static int winMemRoundup(int n){
33043  return n;
33044}
33045
33046/*
33047** Initialize this module.
33048*/
33049static int winMemInit(void *pAppData){
33050  winMemData *pWinMemData = (winMemData *)pAppData;
33051
33052  if( !pWinMemData ) return SQLITE_ERROR;
33053  assert( pWinMemData->magic1==WINMEM_MAGIC1 );
33054  assert( pWinMemData->magic2==WINMEM_MAGIC2 );
33055
33056#if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
33057  if( !pWinMemData->hHeap ){
33058    DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
33059    DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
33060    if( dwMaximumSize==0 ){
33061      dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
33062    }else if( dwInitialSize>dwMaximumSize ){
33063      dwInitialSize = dwMaximumSize;
33064    }
33065    pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
33066                                      dwInitialSize, dwMaximumSize);
33067    if( !pWinMemData->hHeap ){
33068      sqlite3_log(SQLITE_NOMEM,
33069          "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
33070          osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
33071          dwMaximumSize);
33072      return SQLITE_NOMEM;
33073    }
33074    pWinMemData->bOwned = TRUE;
33075    assert( pWinMemData->bOwned );
33076  }
33077#else
33078  pWinMemData->hHeap = osGetProcessHeap();
33079  if( !pWinMemData->hHeap ){
33080    sqlite3_log(SQLITE_NOMEM,
33081        "failed to GetProcessHeap (%lu)", osGetLastError());
33082    return SQLITE_NOMEM;
33083  }
33084  pWinMemData->bOwned = FALSE;
33085  assert( !pWinMemData->bOwned );
33086#endif
33087  assert( pWinMemData->hHeap!=0 );
33088  assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
33089#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
33090  assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
33091#endif
33092  return SQLITE_OK;
33093}
33094
33095/*
33096** Deinitialize this module.
33097*/
33098static void winMemShutdown(void *pAppData){
33099  winMemData *pWinMemData = (winMemData *)pAppData;
33100
33101  if( !pWinMemData ) return;
33102  assert( pWinMemData->magic1==WINMEM_MAGIC1 );
33103  assert( pWinMemData->magic2==WINMEM_MAGIC2 );
33104
33105  if( pWinMemData->hHeap ){
33106    assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
33107#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
33108    assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
33109#endif
33110    if( pWinMemData->bOwned ){
33111      if( !osHeapDestroy(pWinMemData->hHeap) ){
33112        sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
33113                    osGetLastError(), (void*)pWinMemData->hHeap);
33114      }
33115      pWinMemData->bOwned = FALSE;
33116    }
33117    pWinMemData->hHeap = NULL;
33118  }
33119}
33120
33121/*
33122** Populate the low-level memory allocation function pointers in
33123** sqlite3GlobalConfig.m with pointers to the routines in this file. The
33124** arguments specify the block of memory to manage.
33125**
33126** This routine is only called by sqlite3_config(), and therefore
33127** is not required to be threadsafe (it is not).
33128*/
33129SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
33130  static const sqlite3_mem_methods winMemMethods = {
33131    winMemMalloc,
33132    winMemFree,
33133    winMemRealloc,
33134    winMemSize,
33135    winMemRoundup,
33136    winMemInit,
33137    winMemShutdown,
33138    &win_mem_data
33139  };
33140  return &winMemMethods;
33141}
33142
33143SQLITE_PRIVATE void sqlite3MemSetDefault(void){
33144  sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
33145}
33146#endif /* SQLITE_WIN32_MALLOC */
33147
33148/*
33149** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
33150**
33151** Space to hold the returned string is obtained from malloc.
33152*/
33153static LPWSTR winUtf8ToUnicode(const char *zFilename){
33154  int nChar;
33155  LPWSTR zWideFilename;
33156
33157  nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
33158  if( nChar==0 ){
33159    return 0;
33160  }
33161  zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
33162  if( zWideFilename==0 ){
33163    return 0;
33164  }
33165  nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
33166                                nChar);
33167  if( nChar==0 ){
33168    sqlite3_free(zWideFilename);
33169    zWideFilename = 0;
33170  }
33171  return zWideFilename;
33172}
33173
33174/*
33175** Convert Microsoft Unicode to UTF-8.  Space to hold the returned string is
33176** obtained from sqlite3_malloc().
33177*/
33178static char *winUnicodeToUtf8(LPCWSTR zWideFilename){
33179  int nByte;
33180  char *zFilename;
33181
33182  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
33183  if( nByte == 0 ){
33184    return 0;
33185  }
33186  zFilename = sqlite3MallocZero( nByte );
33187  if( zFilename==0 ){
33188    return 0;
33189  }
33190  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
33191                                0, 0);
33192  if( nByte == 0 ){
33193    sqlite3_free(zFilename);
33194    zFilename = 0;
33195  }
33196  return zFilename;
33197}
33198
33199/*
33200** Convert an ANSI string to Microsoft Unicode, based on the
33201** current codepage settings for file apis.
33202**
33203** Space to hold the returned string is obtained
33204** from sqlite3_malloc.
33205*/
33206static LPWSTR winMbcsToUnicode(const char *zFilename){
33207  int nByte;
33208  LPWSTR zMbcsFilename;
33209  int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
33210
33211  nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
33212                                0)*sizeof(WCHAR);
33213  if( nByte==0 ){
33214    return 0;
33215  }
33216  zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
33217  if( zMbcsFilename==0 ){
33218    return 0;
33219  }
33220  nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
33221                                nByte);
33222  if( nByte==0 ){
33223    sqlite3_free(zMbcsFilename);
33224    zMbcsFilename = 0;
33225  }
33226  return zMbcsFilename;
33227}
33228
33229/*
33230** Convert Microsoft Unicode to multi-byte character string, based on the
33231** user's ANSI codepage.
33232**
33233** Space to hold the returned string is obtained from
33234** sqlite3_malloc().
33235*/
33236static char *winUnicodeToMbcs(LPCWSTR zWideFilename){
33237  int nByte;
33238  char *zFilename;
33239  int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
33240
33241  nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
33242  if( nByte == 0 ){
33243    return 0;
33244  }
33245  zFilename = sqlite3MallocZero( nByte );
33246  if( zFilename==0 ){
33247    return 0;
33248  }
33249  nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
33250                                nByte, 0, 0);
33251  if( nByte == 0 ){
33252    sqlite3_free(zFilename);
33253    zFilename = 0;
33254  }
33255  return zFilename;
33256}
33257
33258/*
33259** Convert multibyte character string to UTF-8.  Space to hold the
33260** returned string is obtained from sqlite3_malloc().
33261*/
33262SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
33263  char *zFilenameUtf8;
33264  LPWSTR zTmpWide;
33265
33266  zTmpWide = winMbcsToUnicode(zFilename);
33267  if( zTmpWide==0 ){
33268    return 0;
33269  }
33270  zFilenameUtf8 = winUnicodeToUtf8(zTmpWide);
33271  sqlite3_free(zTmpWide);
33272  return zFilenameUtf8;
33273}
33274
33275/*
33276** Convert UTF-8 to multibyte character string.  Space to hold the
33277** returned string is obtained from sqlite3_malloc().
33278*/
33279SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
33280  char *zFilenameMbcs;
33281  LPWSTR zTmpWide;
33282
33283  zTmpWide = winUtf8ToUnicode(zFilename);
33284  if( zTmpWide==0 ){
33285    return 0;
33286  }
33287  zFilenameMbcs = winUnicodeToMbcs(zTmpWide);
33288  sqlite3_free(zTmpWide);
33289  return zFilenameMbcs;
33290}
33291
33292/*
33293** This function sets the data directory or the temporary directory based on
33294** the provided arguments.  The type argument must be 1 in order to set the
33295** data directory or 2 in order to set the temporary directory.  The zValue
33296** argument is the name of the directory to use.  The return value will be
33297** SQLITE_OK if successful.
33298*/
33299SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
33300  char **ppDirectory = 0;
33301#ifndef SQLITE_OMIT_AUTOINIT
33302  int rc = sqlite3_initialize();
33303  if( rc ) return rc;
33304#endif
33305  if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
33306    ppDirectory = &sqlite3_data_directory;
33307  }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
33308    ppDirectory = &sqlite3_temp_directory;
33309  }
33310  assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
33311          || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
33312  );
33313  assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
33314  if( ppDirectory ){
33315    char *zValueUtf8 = 0;
33316    if( zValue && zValue[0] ){
33317      zValueUtf8 = winUnicodeToUtf8(zValue);
33318      if ( zValueUtf8==0 ){
33319        return SQLITE_NOMEM;
33320      }
33321    }
33322    sqlite3_free(*ppDirectory);
33323    *ppDirectory = zValueUtf8;
33324    return SQLITE_OK;
33325  }
33326  return SQLITE_ERROR;
33327}
33328
33329/*
33330** The return value of winGetLastErrorMsg
33331** is zero if the error message fits in the buffer, or non-zero
33332** otherwise (if the message was truncated).
33333*/
33334static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
33335  /* FormatMessage returns 0 on failure.  Otherwise it
33336  ** returns the number of TCHARs written to the output
33337  ** buffer, excluding the terminating null char.
33338  */
33339  DWORD dwLen = 0;
33340  char *zOut = 0;
33341
33342  if( osIsNT() ){
33343#if SQLITE_OS_WINRT
33344    WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
33345    dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
33346                             FORMAT_MESSAGE_IGNORE_INSERTS,
33347                             NULL,
33348                             lastErrno,
33349                             0,
33350                             zTempWide,
33351                             SQLITE_WIN32_MAX_ERRMSG_CHARS,
33352                             0);
33353#else
33354    LPWSTR zTempWide = NULL;
33355    dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
33356                             FORMAT_MESSAGE_FROM_SYSTEM |
33357                             FORMAT_MESSAGE_IGNORE_INSERTS,
33358                             NULL,
33359                             lastErrno,
33360                             0,
33361                             (LPWSTR) &zTempWide,
33362                             0,
33363                             0);
33364#endif
33365    if( dwLen > 0 ){
33366      /* allocate a buffer and convert to UTF8 */
33367      sqlite3BeginBenignMalloc();
33368      zOut = winUnicodeToUtf8(zTempWide);
33369      sqlite3EndBenignMalloc();
33370#if !SQLITE_OS_WINRT
33371      /* free the system buffer allocated by FormatMessage */
33372      osLocalFree(zTempWide);
33373#endif
33374    }
33375  }
33376#ifdef SQLITE_WIN32_HAS_ANSI
33377  else{
33378    char *zTemp = NULL;
33379    dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
33380                             FORMAT_MESSAGE_FROM_SYSTEM |
33381                             FORMAT_MESSAGE_IGNORE_INSERTS,
33382                             NULL,
33383                             lastErrno,
33384                             0,
33385                             (LPSTR) &zTemp,
33386                             0,
33387                             0);
33388    if( dwLen > 0 ){
33389      /* allocate a buffer and convert to UTF8 */
33390      sqlite3BeginBenignMalloc();
33391      zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
33392      sqlite3EndBenignMalloc();
33393      /* free the system buffer allocated by FormatMessage */
33394      osLocalFree(zTemp);
33395    }
33396  }
33397#endif
33398  if( 0 == dwLen ){
33399    sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
33400  }else{
33401    /* copy a maximum of nBuf chars to output buffer */
33402    sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
33403    /* free the UTF8 buffer */
33404    sqlite3_free(zOut);
33405  }
33406  return 0;
33407}
33408
33409/*
33410**
33411** This function - winLogErrorAtLine() - is only ever called via the macro
33412** winLogError().
33413**
33414** This routine is invoked after an error occurs in an OS function.
33415** It logs a message using sqlite3_log() containing the current value of
33416** error code and, if possible, the human-readable equivalent from
33417** FormatMessage.
33418**
33419** The first argument passed to the macro should be the error code that
33420** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
33421** The two subsequent arguments should be the name of the OS function that
33422** failed and the associated file-system path, if any.
33423*/
33424#define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
33425static int winLogErrorAtLine(
33426  int errcode,                    /* SQLite error code */
33427  DWORD lastErrno,                /* Win32 last error */
33428  const char *zFunc,              /* Name of OS function that failed */
33429  const char *zPath,              /* File path associated with error */
33430  int iLine                       /* Source line number where error occurred */
33431){
33432  char zMsg[500];                 /* Human readable error text */
33433  int i;                          /* Loop counter */
33434
33435  zMsg[0] = 0;
33436  winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
33437  assert( errcode!=SQLITE_OK );
33438  if( zPath==0 ) zPath = "";
33439  for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
33440  zMsg[i] = 0;
33441  sqlite3_log(errcode,
33442      "os_win.c:%d: (%lu) %s(%s) - %s",
33443      iLine, lastErrno, zFunc, zPath, zMsg
33444  );
33445
33446  return errcode;
33447}
33448
33449/*
33450** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
33451** will be retried following a locking error - probably caused by
33452** antivirus software.  Also the initial delay before the first retry.
33453** The delay increases linearly with each retry.
33454*/
33455#ifndef SQLITE_WIN32_IOERR_RETRY
33456# define SQLITE_WIN32_IOERR_RETRY 10
33457#endif
33458#ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
33459# define SQLITE_WIN32_IOERR_RETRY_DELAY 25
33460#endif
33461static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
33462static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
33463
33464/*
33465** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
33466** error code obtained via GetLastError() is eligible to be retried.  It
33467** must accept the error code DWORD as its only argument and should return
33468** non-zero if the error code is transient in nature and the operation
33469** responsible for generating the original error might succeed upon being
33470** retried.  The argument to this macro should be a variable.
33471**
33472** Additionally, a macro named "winIoerrCanRetry2" may be defined.  If it
33473** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
33474** returns zero.  The "winIoerrCanRetry2" macro is completely optional and
33475** may be used to include additional error codes in the set that should
33476** result in the failing I/O operation being retried by the caller.  If
33477** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
33478** identical to those of the "winIoerrCanRetry1" macro.
33479*/
33480#if !defined(winIoerrCanRetry1)
33481#define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED)        || \
33482                              ((a)==ERROR_SHARING_VIOLATION)    || \
33483                              ((a)==ERROR_LOCK_VIOLATION)       || \
33484                              ((a)==ERROR_DEV_NOT_EXIST)        || \
33485                              ((a)==ERROR_NETNAME_DELETED)      || \
33486                              ((a)==ERROR_SEM_TIMEOUT)          || \
33487                              ((a)==ERROR_NETWORK_UNREACHABLE))
33488#endif
33489
33490/*
33491** If a ReadFile() or WriteFile() error occurs, invoke this routine
33492** to see if it should be retried.  Return TRUE to retry.  Return FALSE
33493** to give up with an error.
33494*/
33495static int winRetryIoerr(int *pnRetry, DWORD *pError){
33496  DWORD e = osGetLastError();
33497  if( *pnRetry>=winIoerrRetry ){
33498    if( pError ){
33499      *pError = e;
33500    }
33501    return 0;
33502  }
33503  if( winIoerrCanRetry1(e) ){
33504    sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
33505    ++*pnRetry;
33506    return 1;
33507  }
33508#if defined(winIoerrCanRetry2)
33509  else if( winIoerrCanRetry2(e) ){
33510    sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
33511    ++*pnRetry;
33512    return 1;
33513  }
33514#endif
33515  if( pError ){
33516    *pError = e;
33517  }
33518  return 0;
33519}
33520
33521/*
33522** Log a I/O error retry episode.
33523*/
33524static void winLogIoerr(int nRetry){
33525  if( nRetry ){
33526    sqlite3_log(SQLITE_IOERR,
33527      "delayed %dms for lock/sharing conflict",
33528      winIoerrRetryDelay*nRetry*(nRetry+1)/2
33529    );
33530  }
33531}
33532
33533#if SQLITE_OS_WINCE
33534/*************************************************************************
33535** This section contains code for WinCE only.
33536*/
33537#if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
33538/*
33539** The MSVC CRT on Windows CE may not have a localtime() function.  So
33540** create a substitute.
33541*/
33542/* #include <time.h> */
33543struct tm *__cdecl localtime(const time_t *t)
33544{
33545  static struct tm y;
33546  FILETIME uTm, lTm;
33547  SYSTEMTIME pTm;
33548  sqlite3_int64 t64;
33549  t64 = *t;
33550  t64 = (t64 + 11644473600)*10000000;
33551  uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
33552  uTm.dwHighDateTime= (DWORD)(t64 >> 32);
33553  osFileTimeToLocalFileTime(&uTm,&lTm);
33554  osFileTimeToSystemTime(&lTm,&pTm);
33555  y.tm_year = pTm.wYear - 1900;
33556  y.tm_mon = pTm.wMonth - 1;
33557  y.tm_wday = pTm.wDayOfWeek;
33558  y.tm_mday = pTm.wDay;
33559  y.tm_hour = pTm.wHour;
33560  y.tm_min = pTm.wMinute;
33561  y.tm_sec = pTm.wSecond;
33562  return &y;
33563}
33564#endif
33565
33566#define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
33567
33568/*
33569** Acquire a lock on the handle h
33570*/
33571static void winceMutexAcquire(HANDLE h){
33572   DWORD dwErr;
33573   do {
33574     dwErr = osWaitForSingleObject(h, INFINITE);
33575   } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
33576}
33577/*
33578** Release a lock acquired by winceMutexAcquire()
33579*/
33580#define winceMutexRelease(h) ReleaseMutex(h)
33581
33582/*
33583** Create the mutex and shared memory used for locking in the file
33584** descriptor pFile
33585*/
33586static int winceCreateLock(const char *zFilename, winFile *pFile){
33587  LPWSTR zTok;
33588  LPWSTR zName;
33589  DWORD lastErrno;
33590  BOOL bLogged = FALSE;
33591  BOOL bInit = TRUE;
33592
33593  zName = winUtf8ToUnicode(zFilename);
33594  if( zName==0 ){
33595    /* out of memory */
33596    return SQLITE_IOERR_NOMEM;
33597  }
33598
33599  /* Initialize the local lockdata */
33600  memset(&pFile->local, 0, sizeof(pFile->local));
33601
33602  /* Replace the backslashes from the filename and lowercase it
33603  ** to derive a mutex name. */
33604  zTok = osCharLowerW(zName);
33605  for (;*zTok;zTok++){
33606    if (*zTok == '\\') *zTok = '_';
33607  }
33608
33609  /* Create/open the named mutex */
33610  pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
33611  if (!pFile->hMutex){
33612    pFile->lastErrno = osGetLastError();
33613    sqlite3_free(zName);
33614    return winLogError(SQLITE_IOERR, pFile->lastErrno,
33615                       "winceCreateLock1", zFilename);
33616  }
33617
33618  /* Acquire the mutex before continuing */
33619  winceMutexAcquire(pFile->hMutex);
33620
33621  /* Since the names of named mutexes, semaphores, file mappings etc are
33622  ** case-sensitive, take advantage of that by uppercasing the mutex name
33623  ** and using that as the shared filemapping name.
33624  */
33625  osCharUpperW(zName);
33626  pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
33627                                        PAGE_READWRITE, 0, sizeof(winceLock),
33628                                        zName);
33629
33630  /* Set a flag that indicates we're the first to create the memory so it
33631  ** must be zero-initialized */
33632  lastErrno = osGetLastError();
33633  if (lastErrno == ERROR_ALREADY_EXISTS){
33634    bInit = FALSE;
33635  }
33636
33637  sqlite3_free(zName);
33638
33639  /* If we succeeded in making the shared memory handle, map it. */
33640  if( pFile->hShared ){
33641    pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
33642             FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
33643    /* If mapping failed, close the shared memory handle and erase it */
33644    if( !pFile->shared ){
33645      pFile->lastErrno = osGetLastError();
33646      winLogError(SQLITE_IOERR, pFile->lastErrno,
33647                  "winceCreateLock2", zFilename);
33648      bLogged = TRUE;
33649      osCloseHandle(pFile->hShared);
33650      pFile->hShared = NULL;
33651    }
33652  }
33653
33654  /* If shared memory could not be created, then close the mutex and fail */
33655  if( pFile->hShared==NULL ){
33656    if( !bLogged ){
33657      pFile->lastErrno = lastErrno;
33658      winLogError(SQLITE_IOERR, pFile->lastErrno,
33659                  "winceCreateLock3", zFilename);
33660      bLogged = TRUE;
33661    }
33662    winceMutexRelease(pFile->hMutex);
33663    osCloseHandle(pFile->hMutex);
33664    pFile->hMutex = NULL;
33665    return SQLITE_IOERR;
33666  }
33667
33668  /* Initialize the shared memory if we're supposed to */
33669  if( bInit ){
33670    memset(pFile->shared, 0, sizeof(winceLock));
33671  }
33672
33673  winceMutexRelease(pFile->hMutex);
33674  return SQLITE_OK;
33675}
33676
33677/*
33678** Destroy the part of winFile that deals with wince locks
33679*/
33680static void winceDestroyLock(winFile *pFile){
33681  if (pFile->hMutex){
33682    /* Acquire the mutex */
33683    winceMutexAcquire(pFile->hMutex);
33684
33685    /* The following blocks should probably assert in debug mode, but they
33686       are to cleanup in case any locks remained open */
33687    if (pFile->local.nReaders){
33688      pFile->shared->nReaders --;
33689    }
33690    if (pFile->local.bReserved){
33691      pFile->shared->bReserved = FALSE;
33692    }
33693    if (pFile->local.bPending){
33694      pFile->shared->bPending = FALSE;
33695    }
33696    if (pFile->local.bExclusive){
33697      pFile->shared->bExclusive = FALSE;
33698    }
33699
33700    /* De-reference and close our copy of the shared memory handle */
33701    osUnmapViewOfFile(pFile->shared);
33702    osCloseHandle(pFile->hShared);
33703
33704    /* Done with the mutex */
33705    winceMutexRelease(pFile->hMutex);
33706    osCloseHandle(pFile->hMutex);
33707    pFile->hMutex = NULL;
33708  }
33709}
33710
33711/*
33712** An implementation of the LockFile() API of Windows for CE
33713*/
33714static BOOL winceLockFile(
33715  LPHANDLE phFile,
33716  DWORD dwFileOffsetLow,
33717  DWORD dwFileOffsetHigh,
33718  DWORD nNumberOfBytesToLockLow,
33719  DWORD nNumberOfBytesToLockHigh
33720){
33721  winFile *pFile = HANDLE_TO_WINFILE(phFile);
33722  BOOL bReturn = FALSE;
33723
33724  UNUSED_PARAMETER(dwFileOffsetHigh);
33725  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
33726
33727  if (!pFile->hMutex) return TRUE;
33728  winceMutexAcquire(pFile->hMutex);
33729
33730  /* Wanting an exclusive lock? */
33731  if (dwFileOffsetLow == (DWORD)SHARED_FIRST
33732       && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
33733    if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
33734       pFile->shared->bExclusive = TRUE;
33735       pFile->local.bExclusive = TRUE;
33736       bReturn = TRUE;
33737    }
33738  }
33739
33740  /* Want a read-only lock? */
33741  else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
33742           nNumberOfBytesToLockLow == 1){
33743    if (pFile->shared->bExclusive == 0){
33744      pFile->local.nReaders ++;
33745      if (pFile->local.nReaders == 1){
33746        pFile->shared->nReaders ++;
33747      }
33748      bReturn = TRUE;
33749    }
33750  }
33751
33752  /* Want a pending lock? */
33753  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
33754           && nNumberOfBytesToLockLow == 1){
33755    /* If no pending lock has been acquired, then acquire it */
33756    if (pFile->shared->bPending == 0) {
33757      pFile->shared->bPending = TRUE;
33758      pFile->local.bPending = TRUE;
33759      bReturn = TRUE;
33760    }
33761  }
33762
33763  /* Want a reserved lock? */
33764  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
33765           && nNumberOfBytesToLockLow == 1){
33766    if (pFile->shared->bReserved == 0) {
33767      pFile->shared->bReserved = TRUE;
33768      pFile->local.bReserved = TRUE;
33769      bReturn = TRUE;
33770    }
33771  }
33772
33773  winceMutexRelease(pFile->hMutex);
33774  return bReturn;
33775}
33776
33777/*
33778** An implementation of the UnlockFile API of Windows for CE
33779*/
33780static BOOL winceUnlockFile(
33781  LPHANDLE phFile,
33782  DWORD dwFileOffsetLow,
33783  DWORD dwFileOffsetHigh,
33784  DWORD nNumberOfBytesToUnlockLow,
33785  DWORD nNumberOfBytesToUnlockHigh
33786){
33787  winFile *pFile = HANDLE_TO_WINFILE(phFile);
33788  BOOL bReturn = FALSE;
33789
33790  UNUSED_PARAMETER(dwFileOffsetHigh);
33791  UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
33792
33793  if (!pFile->hMutex) return TRUE;
33794  winceMutexAcquire(pFile->hMutex);
33795
33796  /* Releasing a reader lock or an exclusive lock */
33797  if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
33798    /* Did we have an exclusive lock? */
33799    if (pFile->local.bExclusive){
33800      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
33801      pFile->local.bExclusive = FALSE;
33802      pFile->shared->bExclusive = FALSE;
33803      bReturn = TRUE;
33804    }
33805
33806    /* Did we just have a reader lock? */
33807    else if (pFile->local.nReaders){
33808      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
33809             || nNumberOfBytesToUnlockLow == 1);
33810      pFile->local.nReaders --;
33811      if (pFile->local.nReaders == 0)
33812      {
33813        pFile->shared->nReaders --;
33814      }
33815      bReturn = TRUE;
33816    }
33817  }
33818
33819  /* Releasing a pending lock */
33820  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
33821           && nNumberOfBytesToUnlockLow == 1){
33822    if (pFile->local.bPending){
33823      pFile->local.bPending = FALSE;
33824      pFile->shared->bPending = FALSE;
33825      bReturn = TRUE;
33826    }
33827  }
33828  /* Releasing a reserved lock */
33829  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
33830           && nNumberOfBytesToUnlockLow == 1){
33831    if (pFile->local.bReserved) {
33832      pFile->local.bReserved = FALSE;
33833      pFile->shared->bReserved = FALSE;
33834      bReturn = TRUE;
33835    }
33836  }
33837
33838  winceMutexRelease(pFile->hMutex);
33839  return bReturn;
33840}
33841/*
33842** End of the special code for wince
33843*****************************************************************************/
33844#endif /* SQLITE_OS_WINCE */
33845
33846/*
33847** Lock a file region.
33848*/
33849static BOOL winLockFile(
33850  LPHANDLE phFile,
33851  DWORD flags,
33852  DWORD offsetLow,
33853  DWORD offsetHigh,
33854  DWORD numBytesLow,
33855  DWORD numBytesHigh
33856){
33857#if SQLITE_OS_WINCE
33858  /*
33859  ** NOTE: Windows CE is handled differently here due its lack of the Win32
33860  **       API LockFile.
33861  */
33862  return winceLockFile(phFile, offsetLow, offsetHigh,
33863                       numBytesLow, numBytesHigh);
33864#else
33865  if( osIsNT() ){
33866    OVERLAPPED ovlp;
33867    memset(&ovlp, 0, sizeof(OVERLAPPED));
33868    ovlp.Offset = offsetLow;
33869    ovlp.OffsetHigh = offsetHigh;
33870    return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
33871  }else{
33872    return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
33873                      numBytesHigh);
33874  }
33875#endif
33876}
33877
33878/*
33879** Unlock a file region.
33880 */
33881static BOOL winUnlockFile(
33882  LPHANDLE phFile,
33883  DWORD offsetLow,
33884  DWORD offsetHigh,
33885  DWORD numBytesLow,
33886  DWORD numBytesHigh
33887){
33888#if SQLITE_OS_WINCE
33889  /*
33890  ** NOTE: Windows CE is handled differently here due its lack of the Win32
33891  **       API UnlockFile.
33892  */
33893  return winceUnlockFile(phFile, offsetLow, offsetHigh,
33894                         numBytesLow, numBytesHigh);
33895#else
33896  if( osIsNT() ){
33897    OVERLAPPED ovlp;
33898    memset(&ovlp, 0, sizeof(OVERLAPPED));
33899    ovlp.Offset = offsetLow;
33900    ovlp.OffsetHigh = offsetHigh;
33901    return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
33902  }else{
33903    return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
33904                        numBytesHigh);
33905  }
33906#endif
33907}
33908
33909/*****************************************************************************
33910** The next group of routines implement the I/O methods specified
33911** by the sqlite3_io_methods object.
33912******************************************************************************/
33913
33914/*
33915** Some Microsoft compilers lack this definition.
33916*/
33917#ifndef INVALID_SET_FILE_POINTER
33918# define INVALID_SET_FILE_POINTER ((DWORD)-1)
33919#endif
33920
33921/*
33922** Move the current position of the file handle passed as the first
33923** argument to offset iOffset within the file. If successful, return 0.
33924** Otherwise, set pFile->lastErrno and return non-zero.
33925*/
33926static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
33927#if !SQLITE_OS_WINRT
33928  LONG upperBits;                 /* Most sig. 32 bits of new offset */
33929  LONG lowerBits;                 /* Least sig. 32 bits of new offset */
33930  DWORD dwRet;                    /* Value returned by SetFilePointer() */
33931  DWORD lastErrno;                /* Value returned by GetLastError() */
33932
33933  OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
33934
33935  upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
33936  lowerBits = (LONG)(iOffset & 0xffffffff);
33937
33938  /* API oddity: If successful, SetFilePointer() returns a dword
33939  ** containing the lower 32-bits of the new file-offset. Or, if it fails,
33940  ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
33941  ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
33942  ** whether an error has actually occurred, it is also necessary to call
33943  ** GetLastError().
33944  */
33945  dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
33946
33947  if( (dwRet==INVALID_SET_FILE_POINTER
33948      && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
33949    pFile->lastErrno = lastErrno;
33950    winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
33951                "winSeekFile", pFile->zPath);
33952    OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
33953    return 1;
33954  }
33955
33956  OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
33957  return 0;
33958#else
33959  /*
33960  ** Same as above, except that this implementation works for WinRT.
33961  */
33962
33963  LARGE_INTEGER x;                /* The new offset */
33964  BOOL bRet;                      /* Value returned by SetFilePointerEx() */
33965
33966  x.QuadPart = iOffset;
33967  bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
33968
33969  if(!bRet){
33970    pFile->lastErrno = osGetLastError();
33971    winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
33972                "winSeekFile", pFile->zPath);
33973    OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
33974    return 1;
33975  }
33976
33977  OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
33978  return 0;
33979#endif
33980}
33981
33982#if SQLITE_MAX_MMAP_SIZE>0
33983/* Forward references to VFS helper methods used for memory mapped files */
33984static int winMapfile(winFile*, sqlite3_int64);
33985static int winUnmapfile(winFile*);
33986#endif
33987
33988/*
33989** Close a file.
33990**
33991** It is reported that an attempt to close a handle might sometimes
33992** fail.  This is a very unreasonable result, but Windows is notorious
33993** for being unreasonable so I do not doubt that it might happen.  If
33994** the close fails, we pause for 100 milliseconds and try again.  As
33995** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
33996** giving up and returning an error.
33997*/
33998#define MX_CLOSE_ATTEMPT 3
33999static int winClose(sqlite3_file *id){
34000  int rc, cnt = 0;
34001  winFile *pFile = (winFile*)id;
34002
34003  assert( id!=0 );
34004#ifndef SQLITE_OMIT_WAL
34005  assert( pFile->pShm==0 );
34006#endif
34007  assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
34008  OSTRACE(("CLOSE file=%p\n", pFile->h));
34009
34010#if SQLITE_MAX_MMAP_SIZE>0
34011  winUnmapfile(pFile);
34012#endif
34013
34014  do{
34015    rc = osCloseHandle(pFile->h);
34016    /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
34017  }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
34018#if SQLITE_OS_WINCE
34019#define WINCE_DELETION_ATTEMPTS 3
34020  winceDestroyLock(pFile);
34021  if( pFile->zDeleteOnClose ){
34022    int cnt = 0;
34023    while(
34024           osDeleteFileW(pFile->zDeleteOnClose)==0
34025        && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
34026        && cnt++ < WINCE_DELETION_ATTEMPTS
34027    ){
34028       sqlite3_win32_sleep(100);  /* Wait a little before trying again */
34029    }
34030    sqlite3_free(pFile->zDeleteOnClose);
34031  }
34032#endif
34033  if( rc ){
34034    pFile->h = NULL;
34035  }
34036  OpenCounter(-1);
34037  OSTRACE(("CLOSE file=%p, rc=%s\n", pFile->h, rc ? "ok" : "failed"));
34038  return rc ? SQLITE_OK
34039            : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
34040                          "winClose", pFile->zPath);
34041}
34042
34043/*
34044** Read data from a file into a buffer.  Return SQLITE_OK if all
34045** bytes were read successfully and SQLITE_IOERR if anything goes
34046** wrong.
34047*/
34048static int winRead(
34049  sqlite3_file *id,          /* File to read from */
34050  void *pBuf,                /* Write content into this buffer */
34051  int amt,                   /* Number of bytes to read */
34052  sqlite3_int64 offset       /* Begin reading at this offset */
34053){
34054#if !SQLITE_OS_WINCE
34055  OVERLAPPED overlapped;          /* The offset for ReadFile. */
34056#endif
34057  winFile *pFile = (winFile*)id;  /* file handle */
34058  DWORD nRead;                    /* Number of bytes actually read from file */
34059  int nRetry = 0;                 /* Number of retrys */
34060
34061  assert( id!=0 );
34062  assert( amt>0 );
34063  assert( offset>=0 );
34064  SimulateIOError(return SQLITE_IOERR_READ);
34065  OSTRACE(("READ file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
34066           pFile->h, pBuf, amt, offset, pFile->locktype));
34067
34068#if SQLITE_MAX_MMAP_SIZE>0
34069  /* Deal with as much of this read request as possible by transfering
34070  ** data from the memory mapping using memcpy().  */
34071  if( offset<pFile->mmapSize ){
34072    if( offset+amt <= pFile->mmapSize ){
34073      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
34074      OSTRACE(("READ-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
34075      return SQLITE_OK;
34076    }else{
34077      int nCopy = (int)(pFile->mmapSize - offset);
34078      memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
34079      pBuf = &((u8 *)pBuf)[nCopy];
34080      amt -= nCopy;
34081      offset += nCopy;
34082    }
34083  }
34084#endif
34085
34086#if SQLITE_OS_WINCE
34087  if( winSeekFile(pFile, offset) ){
34088    OSTRACE(("READ file=%p, rc=SQLITE_FULL\n", pFile->h));
34089    return SQLITE_FULL;
34090  }
34091  while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
34092#else
34093  memset(&overlapped, 0, sizeof(OVERLAPPED));
34094  overlapped.Offset = (LONG)(offset & 0xffffffff);
34095  overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
34096  while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
34097         osGetLastError()!=ERROR_HANDLE_EOF ){
34098#endif
34099    DWORD lastErrno;
34100    if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
34101    pFile->lastErrno = lastErrno;
34102    OSTRACE(("READ file=%p, rc=SQLITE_IOERR_READ\n", pFile->h));
34103    return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
34104                       "winRead", pFile->zPath);
34105  }
34106  winLogIoerr(nRetry);
34107  if( nRead<(DWORD)amt ){
34108    /* Unread parts of the buffer must be zero-filled */
34109    memset(&((char*)pBuf)[nRead], 0, amt-nRead);
34110    OSTRACE(("READ file=%p, rc=SQLITE_IOERR_SHORT_READ\n", pFile->h));
34111    return SQLITE_IOERR_SHORT_READ;
34112  }
34113
34114  OSTRACE(("READ file=%p, rc=SQLITE_OK\n", pFile->h));
34115  return SQLITE_OK;
34116}
34117
34118/*
34119** Write data from a buffer into a file.  Return SQLITE_OK on success
34120** or some other error code on failure.
34121*/
34122static int winWrite(
34123  sqlite3_file *id,               /* File to write into */
34124  const void *pBuf,               /* The bytes to be written */
34125  int amt,                        /* Number of bytes to write */
34126  sqlite3_int64 offset            /* Offset into the file to begin writing at */
34127){
34128  int rc = 0;                     /* True if error has occurred, else false */
34129  winFile *pFile = (winFile*)id;  /* File handle */
34130  int nRetry = 0;                 /* Number of retries */
34131
34132  assert( amt>0 );
34133  assert( pFile );
34134  SimulateIOError(return SQLITE_IOERR_WRITE);
34135  SimulateDiskfullError(return SQLITE_FULL);
34136
34137  OSTRACE(("WRITE file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
34138           pFile->h, pBuf, amt, offset, pFile->locktype));
34139
34140#if SQLITE_MAX_MMAP_SIZE>0
34141  /* Deal with as much of this write request as possible by transfering
34142  ** data from the memory mapping using memcpy().  */
34143  if( offset<pFile->mmapSize ){
34144    if( offset+amt <= pFile->mmapSize ){
34145      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
34146      OSTRACE(("WRITE-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
34147      return SQLITE_OK;
34148    }else{
34149      int nCopy = (int)(pFile->mmapSize - offset);
34150      memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
34151      pBuf = &((u8 *)pBuf)[nCopy];
34152      amt -= nCopy;
34153      offset += nCopy;
34154    }
34155  }
34156#endif
34157
34158#if SQLITE_OS_WINCE
34159  rc = winSeekFile(pFile, offset);
34160  if( rc==0 ){
34161#else
34162  {
34163#endif
34164#if !SQLITE_OS_WINCE
34165    OVERLAPPED overlapped;        /* The offset for WriteFile. */
34166#endif
34167    u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
34168    int nRem = amt;               /* Number of bytes yet to be written */
34169    DWORD nWrite;                 /* Bytes written by each WriteFile() call */
34170    DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
34171
34172#if !SQLITE_OS_WINCE
34173    memset(&overlapped, 0, sizeof(OVERLAPPED));
34174    overlapped.Offset = (LONG)(offset & 0xffffffff);
34175    overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
34176#endif
34177
34178    while( nRem>0 ){
34179#if SQLITE_OS_WINCE
34180      if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
34181#else
34182      if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
34183#endif
34184        if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
34185        break;
34186      }
34187      assert( nWrite==0 || nWrite<=(DWORD)nRem );
34188      if( nWrite==0 || nWrite>(DWORD)nRem ){
34189        lastErrno = osGetLastError();
34190        break;
34191      }
34192#if !SQLITE_OS_WINCE
34193      offset += nWrite;
34194      overlapped.Offset = (LONG)(offset & 0xffffffff);
34195      overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
34196#endif
34197      aRem += nWrite;
34198      nRem -= nWrite;
34199    }
34200    if( nRem>0 ){
34201      pFile->lastErrno = lastErrno;
34202      rc = 1;
34203    }
34204  }
34205
34206  if( rc ){
34207    if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
34208       || ( pFile->lastErrno==ERROR_DISK_FULL )){
34209      OSTRACE(("WRITE file=%p, rc=SQLITE_FULL\n", pFile->h));
34210      return winLogError(SQLITE_FULL, pFile->lastErrno,
34211                         "winWrite1", pFile->zPath);
34212    }
34213    OSTRACE(("WRITE file=%p, rc=SQLITE_IOERR_WRITE\n", pFile->h));
34214    return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
34215                       "winWrite2", pFile->zPath);
34216  }else{
34217    winLogIoerr(nRetry);
34218  }
34219  OSTRACE(("WRITE file=%p, rc=SQLITE_OK\n", pFile->h));
34220  return SQLITE_OK;
34221}
34222
34223/*
34224** Truncate an open file to a specified size
34225*/
34226static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
34227  winFile *pFile = (winFile*)id;  /* File handle object */
34228  int rc = SQLITE_OK;             /* Return code for this function */
34229  DWORD lastErrno;
34230
34231  assert( pFile );
34232  SimulateIOError(return SQLITE_IOERR_TRUNCATE);
34233  OSTRACE(("TRUNCATE file=%p, size=%lld, lock=%d\n",
34234           pFile->h, nByte, pFile->locktype));
34235
34236  /* If the user has configured a chunk-size for this file, truncate the
34237  ** file so that it consists of an integer number of chunks (i.e. the
34238  ** actual file size after the operation may be larger than the requested
34239  ** size).
34240  */
34241  if( pFile->szChunk>0 ){
34242    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
34243  }
34244
34245  /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
34246  if( winSeekFile(pFile, nByte) ){
34247    rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
34248                     "winTruncate1", pFile->zPath);
34249  }else if( 0==osSetEndOfFile(pFile->h) &&
34250            ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
34251    pFile->lastErrno = lastErrno;
34252    rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
34253                     "winTruncate2", pFile->zPath);
34254  }
34255
34256#if SQLITE_MAX_MMAP_SIZE>0
34257  /* If the file was truncated to a size smaller than the currently
34258  ** mapped region, reduce the effective mapping size as well. SQLite will
34259  ** use read() and write() to access data beyond this point from now on.
34260  */
34261  if( pFile->pMapRegion && nByte<pFile->mmapSize ){
34262    pFile->mmapSize = nByte;
34263  }
34264#endif
34265
34266  OSTRACE(("TRUNCATE file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
34267  return rc;
34268}
34269
34270#ifdef SQLITE_TEST
34271/*
34272** Count the number of fullsyncs and normal syncs.  This is used to test
34273** that syncs and fullsyncs are occuring at the right times.
34274*/
34275SQLITE_API int sqlite3_sync_count = 0;
34276SQLITE_API int sqlite3_fullsync_count = 0;
34277#endif
34278
34279/*
34280** Make sure all writes to a particular file are committed to disk.
34281*/
34282static int winSync(sqlite3_file *id, int flags){
34283#ifndef SQLITE_NO_SYNC
34284  /*
34285  ** Used only when SQLITE_NO_SYNC is not defined.
34286   */
34287  BOOL rc;
34288#endif
34289#if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
34290    (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
34291  /*
34292  ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
34293  ** OSTRACE() macros.
34294   */
34295  winFile *pFile = (winFile*)id;
34296#else
34297  UNUSED_PARAMETER(id);
34298#endif
34299
34300  assert( pFile );
34301  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
34302  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
34303      || (flags&0x0F)==SQLITE_SYNC_FULL
34304  );
34305
34306  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
34307  ** line is to test that doing so does not cause any problems.
34308  */
34309  SimulateDiskfullError( return SQLITE_FULL );
34310
34311  OSTRACE(("SYNC file=%p, flags=%x, lock=%d\n",
34312           pFile->h, flags, pFile->locktype));
34313
34314#ifndef SQLITE_TEST
34315  UNUSED_PARAMETER(flags);
34316#else
34317  if( (flags&0x0F)==SQLITE_SYNC_FULL ){
34318    sqlite3_fullsync_count++;
34319  }
34320  sqlite3_sync_count++;
34321#endif
34322
34323  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
34324  ** no-op
34325  */
34326#ifdef SQLITE_NO_SYNC
34327  OSTRACE(("SYNC-NOP file=%p, rc=SQLITE_OK\n", pFile->h));
34328  return SQLITE_OK;
34329#else
34330  rc = osFlushFileBuffers(pFile->h);
34331  SimulateIOError( rc=FALSE );
34332  if( rc ){
34333    OSTRACE(("SYNC file=%p, rc=SQLITE_OK\n", pFile->h));
34334    return SQLITE_OK;
34335  }else{
34336    pFile->lastErrno = osGetLastError();
34337    OSTRACE(("SYNC file=%p, rc=SQLITE_IOERR_FSYNC\n", pFile->h));
34338    return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
34339                       "winSync", pFile->zPath);
34340  }
34341#endif
34342}
34343
34344/*
34345** Determine the current size of a file in bytes
34346*/
34347static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
34348  winFile *pFile = (winFile*)id;
34349  int rc = SQLITE_OK;
34350
34351  assert( id!=0 );
34352  assert( pSize!=0 );
34353  SimulateIOError(return SQLITE_IOERR_FSTAT);
34354  OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
34355
34356#if SQLITE_OS_WINRT
34357  {
34358    FILE_STANDARD_INFO info;
34359    if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
34360                                     &info, sizeof(info)) ){
34361      *pSize = info.EndOfFile.QuadPart;
34362    }else{
34363      pFile->lastErrno = osGetLastError();
34364      rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
34365                       "winFileSize", pFile->zPath);
34366    }
34367  }
34368#else
34369  {
34370    DWORD upperBits;
34371    DWORD lowerBits;
34372    DWORD lastErrno;
34373
34374    lowerBits = osGetFileSize(pFile->h, &upperBits);
34375    *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
34376    if(   (lowerBits == INVALID_FILE_SIZE)
34377       && ((lastErrno = osGetLastError())!=NO_ERROR) ){
34378      pFile->lastErrno = lastErrno;
34379      rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
34380                       "winFileSize", pFile->zPath);
34381    }
34382  }
34383#endif
34384  OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
34385           pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
34386  return rc;
34387}
34388
34389/*
34390** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
34391*/
34392#ifndef LOCKFILE_FAIL_IMMEDIATELY
34393# define LOCKFILE_FAIL_IMMEDIATELY 1
34394#endif
34395
34396#ifndef LOCKFILE_EXCLUSIVE_LOCK
34397# define LOCKFILE_EXCLUSIVE_LOCK 2
34398#endif
34399
34400/*
34401** Historically, SQLite has used both the LockFile and LockFileEx functions.
34402** When the LockFile function was used, it was always expected to fail
34403** immediately if the lock could not be obtained.  Also, it always expected to
34404** obtain an exclusive lock.  These flags are used with the LockFileEx function
34405** and reflect those expectations; therefore, they should not be changed.
34406*/
34407#ifndef SQLITE_LOCKFILE_FLAGS
34408# define SQLITE_LOCKFILE_FLAGS   (LOCKFILE_FAIL_IMMEDIATELY | \
34409                                  LOCKFILE_EXCLUSIVE_LOCK)
34410#endif
34411
34412/*
34413** Currently, SQLite never calls the LockFileEx function without wanting the
34414** call to fail immediately if the lock cannot be obtained.
34415*/
34416#ifndef SQLITE_LOCKFILEEX_FLAGS
34417# define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
34418#endif
34419
34420/*
34421** Acquire a reader lock.
34422** Different API routines are called depending on whether or not this
34423** is Win9x or WinNT.
34424*/
34425static int winGetReadLock(winFile *pFile){
34426  int res;
34427  OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
34428  if( osIsNT() ){
34429#if SQLITE_OS_WINCE
34430    /*
34431    ** NOTE: Windows CE is handled differently here due its lack of the Win32
34432    **       API LockFileEx.
34433    */
34434    res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
34435#else
34436    res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
34437                      SHARED_SIZE, 0);
34438#endif
34439  }
34440#ifdef SQLITE_WIN32_HAS_ANSI
34441  else{
34442    int lk;
34443    sqlite3_randomness(sizeof(lk), &lk);
34444    pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
34445    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
34446                      SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
34447  }
34448#endif
34449  if( res == 0 ){
34450    pFile->lastErrno = osGetLastError();
34451    /* No need to log a failure to lock */
34452  }
34453  OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
34454  return res;
34455}
34456
34457/*
34458** Undo a readlock
34459*/
34460static int winUnlockReadLock(winFile *pFile){
34461  int res;
34462  DWORD lastErrno;
34463  OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
34464  if( osIsNT() ){
34465    res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
34466  }
34467#ifdef SQLITE_WIN32_HAS_ANSI
34468  else{
34469    res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
34470  }
34471#endif
34472  if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
34473    pFile->lastErrno = lastErrno;
34474    winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
34475                "winUnlockReadLock", pFile->zPath);
34476  }
34477  OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
34478  return res;
34479}
34480
34481/*
34482** Lock the file with the lock specified by parameter locktype - one
34483** of the following:
34484**
34485**     (1) SHARED_LOCK
34486**     (2) RESERVED_LOCK
34487**     (3) PENDING_LOCK
34488**     (4) EXCLUSIVE_LOCK
34489**
34490** Sometimes when requesting one lock state, additional lock states
34491** are inserted in between.  The locking might fail on one of the later
34492** transitions leaving the lock state different from what it started but
34493** still short of its goal.  The following chart shows the allowed
34494** transitions and the inserted intermediate states:
34495**
34496**    UNLOCKED -> SHARED
34497**    SHARED -> RESERVED
34498**    SHARED -> (PENDING) -> EXCLUSIVE
34499**    RESERVED -> (PENDING) -> EXCLUSIVE
34500**    PENDING -> EXCLUSIVE
34501**
34502** This routine will only increase a lock.  The winUnlock() routine
34503** erases all locks at once and returns us immediately to locking level 0.
34504** It is not possible to lower the locking level one step at a time.  You
34505** must go straight to locking level 0.
34506*/
34507static int winLock(sqlite3_file *id, int locktype){
34508  int rc = SQLITE_OK;    /* Return code from subroutines */
34509  int res = 1;           /* Result of a Windows lock call */
34510  int newLocktype;       /* Set pFile->locktype to this value before exiting */
34511  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
34512  winFile *pFile = (winFile*)id;
34513  DWORD lastErrno = NO_ERROR;
34514
34515  assert( id!=0 );
34516  OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
34517           pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
34518
34519  /* If there is already a lock of this type or more restrictive on the
34520  ** OsFile, do nothing. Don't use the end_lock: exit path, as
34521  ** sqlite3OsEnterMutex() hasn't been called yet.
34522  */
34523  if( pFile->locktype>=locktype ){
34524    OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
34525    return SQLITE_OK;
34526  }
34527
34528  /* Make sure the locking sequence is correct
34529  */
34530  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
34531  assert( locktype!=PENDING_LOCK );
34532  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
34533
34534  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
34535  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
34536  ** the PENDING_LOCK byte is temporary.
34537  */
34538  newLocktype = pFile->locktype;
34539  if(   (pFile->locktype==NO_LOCK)
34540     || (   (locktype==EXCLUSIVE_LOCK)
34541         && (pFile->locktype==RESERVED_LOCK))
34542  ){
34543    int cnt = 3;
34544    while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
34545                                         PENDING_BYTE, 0, 1, 0))==0 ){
34546      /* Try 3 times to get the pending lock.  This is needed to work
34547      ** around problems caused by indexing and/or anti-virus software on
34548      ** Windows systems.
34549      ** If you are using this code as a model for alternative VFSes, do not
34550      ** copy this retry logic.  It is a hack intended for Windows only.
34551      */
34552      lastErrno = osGetLastError();
34553      OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
34554               pFile->h, cnt, res));
34555      if( lastErrno==ERROR_INVALID_HANDLE ){
34556        pFile->lastErrno = lastErrno;
34557        rc = SQLITE_IOERR_LOCK;
34558        OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
34559                 pFile->h, cnt, sqlite3ErrName(rc)));
34560        return rc;
34561      }
34562      if( cnt ) sqlite3_win32_sleep(1);
34563    }
34564    gotPendingLock = res;
34565    if( !res ){
34566      lastErrno = osGetLastError();
34567    }
34568  }
34569
34570  /* Acquire a shared lock
34571  */
34572  if( locktype==SHARED_LOCK && res ){
34573    assert( pFile->locktype==NO_LOCK );
34574    res = winGetReadLock(pFile);
34575    if( res ){
34576      newLocktype = SHARED_LOCK;
34577    }else{
34578      lastErrno = osGetLastError();
34579    }
34580  }
34581
34582  /* Acquire a RESERVED lock
34583  */
34584  if( locktype==RESERVED_LOCK && res ){
34585    assert( pFile->locktype==SHARED_LOCK );
34586    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
34587    if( res ){
34588      newLocktype = RESERVED_LOCK;
34589    }else{
34590      lastErrno = osGetLastError();
34591    }
34592  }
34593
34594  /* Acquire a PENDING lock
34595  */
34596  if( locktype==EXCLUSIVE_LOCK && res ){
34597    newLocktype = PENDING_LOCK;
34598    gotPendingLock = 0;
34599  }
34600
34601  /* Acquire an EXCLUSIVE lock
34602  */
34603  if( locktype==EXCLUSIVE_LOCK && res ){
34604    assert( pFile->locktype>=SHARED_LOCK );
34605    res = winUnlockReadLock(pFile);
34606    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
34607                      SHARED_SIZE, 0);
34608    if( res ){
34609      newLocktype = EXCLUSIVE_LOCK;
34610    }else{
34611      lastErrno = osGetLastError();
34612      winGetReadLock(pFile);
34613    }
34614  }
34615
34616  /* If we are holding a PENDING lock that ought to be released, then
34617  ** release it now.
34618  */
34619  if( gotPendingLock && locktype==SHARED_LOCK ){
34620    winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
34621  }
34622
34623  /* Update the state of the lock has held in the file descriptor then
34624  ** return the appropriate result code.
34625  */
34626  if( res ){
34627    rc = SQLITE_OK;
34628  }else{
34629    pFile->lastErrno = lastErrno;
34630    rc = SQLITE_BUSY;
34631    OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
34632             pFile->h, locktype, newLocktype));
34633  }
34634  pFile->locktype = (u8)newLocktype;
34635  OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
34636           pFile->h, pFile->locktype, sqlite3ErrName(rc)));
34637  return rc;
34638}
34639
34640/*
34641** This routine checks if there is a RESERVED lock held on the specified
34642** file by this or any other process. If such a lock is held, return
34643** non-zero, otherwise zero.
34644*/
34645static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
34646  int res;
34647  winFile *pFile = (winFile*)id;
34648
34649  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
34650  OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
34651
34652  assert( id!=0 );
34653  if( pFile->locktype>=RESERVED_LOCK ){
34654    res = 1;
34655    OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
34656  }else{
34657    res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE, 0, 1, 0);
34658    if( res ){
34659      winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
34660    }
34661    res = !res;
34662    OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
34663  }
34664  *pResOut = res;
34665  OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
34666           pFile->h, pResOut, *pResOut));
34667  return SQLITE_OK;
34668}
34669
34670/*
34671** Lower the locking level on file descriptor id to locktype.  locktype
34672** must be either NO_LOCK or SHARED_LOCK.
34673**
34674** If the locking level of the file descriptor is already at or below
34675** the requested locking level, this routine is a no-op.
34676**
34677** It is not possible for this routine to fail if the second argument
34678** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
34679** might return SQLITE_IOERR;
34680*/
34681static int winUnlock(sqlite3_file *id, int locktype){
34682  int type;
34683  winFile *pFile = (winFile*)id;
34684  int rc = SQLITE_OK;
34685  assert( pFile!=0 );
34686  assert( locktype<=SHARED_LOCK );
34687  OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
34688           pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
34689  type = pFile->locktype;
34690  if( type>=EXCLUSIVE_LOCK ){
34691    winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
34692    if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
34693      /* This should never happen.  We should always be able to
34694      ** reacquire the read lock */
34695      rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
34696                       "winUnlock", pFile->zPath);
34697    }
34698  }
34699  if( type>=RESERVED_LOCK ){
34700    winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
34701  }
34702  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
34703    winUnlockReadLock(pFile);
34704  }
34705  if( type>=PENDING_LOCK ){
34706    winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
34707  }
34708  pFile->locktype = (u8)locktype;
34709  OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
34710           pFile->h, pFile->locktype, sqlite3ErrName(rc)));
34711  return rc;
34712}
34713
34714/*
34715** If *pArg is inititially negative then this is a query.  Set *pArg to
34716** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
34717**
34718** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
34719*/
34720static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
34721  if( *pArg<0 ){
34722    *pArg = (pFile->ctrlFlags & mask)!=0;
34723  }else if( (*pArg)==0 ){
34724    pFile->ctrlFlags &= ~mask;
34725  }else{
34726    pFile->ctrlFlags |= mask;
34727  }
34728}
34729
34730/* Forward references to VFS helper methods used for temporary files */
34731static int winGetTempname(sqlite3_vfs *, char **);
34732static int winIsDir(const void *);
34733static BOOL winIsDriveLetterAndColon(const char *);
34734
34735/*
34736** Control and query of the open file handle.
34737*/
34738static int winFileControl(sqlite3_file *id, int op, void *pArg){
34739  winFile *pFile = (winFile*)id;
34740  OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
34741  switch( op ){
34742    case SQLITE_FCNTL_LOCKSTATE: {
34743      *(int*)pArg = pFile->locktype;
34744      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
34745      return SQLITE_OK;
34746    }
34747    case SQLITE_LAST_ERRNO: {
34748      *(int*)pArg = (int)pFile->lastErrno;
34749      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
34750      return SQLITE_OK;
34751    }
34752    case SQLITE_FCNTL_CHUNK_SIZE: {
34753      pFile->szChunk = *(int *)pArg;
34754      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
34755      return SQLITE_OK;
34756    }
34757    case SQLITE_FCNTL_SIZE_HINT: {
34758      if( pFile->szChunk>0 ){
34759        sqlite3_int64 oldSz;
34760        int rc = winFileSize(id, &oldSz);
34761        if( rc==SQLITE_OK ){
34762          sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
34763          if( newSz>oldSz ){
34764            SimulateIOErrorBenign(1);
34765            rc = winTruncate(id, newSz);
34766            SimulateIOErrorBenign(0);
34767          }
34768        }
34769        OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
34770        return rc;
34771      }
34772      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
34773      return SQLITE_OK;
34774    }
34775    case SQLITE_FCNTL_PERSIST_WAL: {
34776      winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
34777      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
34778      return SQLITE_OK;
34779    }
34780    case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
34781      winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
34782      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
34783      return SQLITE_OK;
34784    }
34785    case SQLITE_FCNTL_VFSNAME: {
34786      *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
34787      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
34788      return SQLITE_OK;
34789    }
34790    case SQLITE_FCNTL_WIN32_AV_RETRY: {
34791      int *a = (int*)pArg;
34792      if( a[0]>0 ){
34793        winIoerrRetry = a[0];
34794      }else{
34795        a[0] = winIoerrRetry;
34796      }
34797      if( a[1]>0 ){
34798        winIoerrRetryDelay = a[1];
34799      }else{
34800        a[1] = winIoerrRetryDelay;
34801      }
34802      OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
34803      return SQLITE_OK;
34804    }
34805#ifdef SQLITE_TEST
34806    case SQLITE_FCNTL_WIN32_SET_HANDLE: {
34807      LPHANDLE phFile = (LPHANDLE)pArg;
34808      HANDLE hOldFile = pFile->h;
34809      pFile->h = *phFile;
34810      *phFile = hOldFile;
34811      OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
34812               hOldFile, pFile->h));
34813      return SQLITE_OK;
34814    }
34815#endif
34816    case SQLITE_FCNTL_TEMPFILENAME: {
34817      char *zTFile = 0;
34818      int rc = winGetTempname(pFile->pVfs, &zTFile);
34819      if( rc==SQLITE_OK ){
34820        *(char**)pArg = zTFile;
34821      }
34822      OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
34823      return rc;
34824    }
34825#if SQLITE_MAX_MMAP_SIZE>0
34826    case SQLITE_FCNTL_MMAP_SIZE: {
34827      i64 newLimit = *(i64*)pArg;
34828      int rc = SQLITE_OK;
34829      if( newLimit>sqlite3GlobalConfig.mxMmap ){
34830        newLimit = sqlite3GlobalConfig.mxMmap;
34831      }
34832      *(i64*)pArg = pFile->mmapSizeMax;
34833      if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
34834        pFile->mmapSizeMax = newLimit;
34835        if( pFile->mmapSize>0 ){
34836          winUnmapfile(pFile);
34837          rc = winMapfile(pFile, -1);
34838        }
34839      }
34840      OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
34841      return rc;
34842    }
34843#endif
34844  }
34845  OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
34846  return SQLITE_NOTFOUND;
34847}
34848
34849/*
34850** Return the sector size in bytes of the underlying block device for
34851** the specified file. This is almost always 512 bytes, but may be
34852** larger for some devices.
34853**
34854** SQLite code assumes this function cannot fail. It also assumes that
34855** if two files are created in the same file-system directory (i.e.
34856** a database and its journal file) that the sector size will be the
34857** same for both.
34858*/
34859static int winSectorSize(sqlite3_file *id){
34860  (void)id;
34861  return SQLITE_DEFAULT_SECTOR_SIZE;
34862}
34863
34864/*
34865** Return a vector of device characteristics.
34866*/
34867static int winDeviceCharacteristics(sqlite3_file *id){
34868  winFile *p = (winFile*)id;
34869  return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
34870         ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
34871}
34872
34873/*
34874** Windows will only let you create file view mappings
34875** on allocation size granularity boundaries.
34876** During sqlite3_os_init() we do a GetSystemInfo()
34877** to get the granularity size.
34878*/
34879static SYSTEM_INFO winSysInfo;
34880
34881#ifndef SQLITE_OMIT_WAL
34882
34883/*
34884** Helper functions to obtain and relinquish the global mutex. The
34885** global mutex is used to protect the winLockInfo objects used by
34886** this file, all of which may be shared by multiple threads.
34887**
34888** Function winShmMutexHeld() is used to assert() that the global mutex
34889** is held when required. This function is only used as part of assert()
34890** statements. e.g.
34891**
34892**   winShmEnterMutex()
34893**     assert( winShmMutexHeld() );
34894**   winShmLeaveMutex()
34895*/
34896static void winShmEnterMutex(void){
34897  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
34898}
34899static void winShmLeaveMutex(void){
34900  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
34901}
34902#ifndef NDEBUG
34903static int winShmMutexHeld(void) {
34904  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
34905}
34906#endif
34907
34908/*
34909** Object used to represent a single file opened and mmapped to provide
34910** shared memory.  When multiple threads all reference the same
34911** log-summary, each thread has its own winFile object, but they all
34912** point to a single instance of this object.  In other words, each
34913** log-summary is opened only once per process.
34914**
34915** winShmMutexHeld() must be true when creating or destroying
34916** this object or while reading or writing the following fields:
34917**
34918**      nRef
34919**      pNext
34920**
34921** The following fields are read-only after the object is created:
34922**
34923**      fid
34924**      zFilename
34925**
34926** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
34927** winShmMutexHeld() is true when reading or writing any other field
34928** in this structure.
34929**
34930*/
34931struct winShmNode {
34932  sqlite3_mutex *mutex;      /* Mutex to access this object */
34933  char *zFilename;           /* Name of the file */
34934  winFile hFile;             /* File handle from winOpen */
34935
34936  int szRegion;              /* Size of shared-memory regions */
34937  int nRegion;               /* Size of array apRegion */
34938  struct ShmRegion {
34939    HANDLE hMap;             /* File handle from CreateFileMapping */
34940    void *pMap;
34941  } *aRegion;
34942  DWORD lastErrno;           /* The Windows errno from the last I/O error */
34943
34944  int nRef;                  /* Number of winShm objects pointing to this */
34945  winShm *pFirst;            /* All winShm objects pointing to this */
34946  winShmNode *pNext;         /* Next in list of all winShmNode objects */
34947#ifdef SQLITE_DEBUG
34948  u8 nextShmId;              /* Next available winShm.id value */
34949#endif
34950};
34951
34952/*
34953** A global array of all winShmNode objects.
34954**
34955** The winShmMutexHeld() must be true while reading or writing this list.
34956*/
34957static winShmNode *winShmNodeList = 0;
34958
34959/*
34960** Structure used internally by this VFS to record the state of an
34961** open shared memory connection.
34962**
34963** The following fields are initialized when this object is created and
34964** are read-only thereafter:
34965**
34966**    winShm.pShmNode
34967**    winShm.id
34968**
34969** All other fields are read/write.  The winShm.pShmNode->mutex must be held
34970** while accessing any read/write fields.
34971*/
34972struct winShm {
34973  winShmNode *pShmNode;      /* The underlying winShmNode object */
34974  winShm *pNext;             /* Next winShm with the same winShmNode */
34975  u8 hasMutex;               /* True if holding the winShmNode mutex */
34976  u16 sharedMask;            /* Mask of shared locks held */
34977  u16 exclMask;              /* Mask of exclusive locks held */
34978#ifdef SQLITE_DEBUG
34979  u8 id;                     /* Id of this connection with its winShmNode */
34980#endif
34981};
34982
34983/*
34984** Constants used for locking
34985*/
34986#define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
34987#define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
34988
34989/*
34990** Apply advisory locks for all n bytes beginning at ofst.
34991*/
34992#define _SHM_UNLCK  1
34993#define _SHM_RDLCK  2
34994#define _SHM_WRLCK  3
34995static int winShmSystemLock(
34996  winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
34997  int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
34998  int ofst,             /* Offset to first byte to be locked/unlocked */
34999  int nByte             /* Number of bytes to lock or unlock */
35000){
35001  int rc = 0;           /* Result code form Lock/UnlockFileEx() */
35002
35003  /* Access to the winShmNode object is serialized by the caller */
35004  assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
35005
35006  OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
35007           pFile->hFile.h, lockType, ofst, nByte));
35008
35009  /* Release/Acquire the system-level lock */
35010  if( lockType==_SHM_UNLCK ){
35011    rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
35012  }else{
35013    /* Initialize the locking parameters */
35014    DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
35015    if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
35016    rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
35017  }
35018
35019  if( rc!= 0 ){
35020    rc = SQLITE_OK;
35021  }else{
35022    pFile->lastErrno =  osGetLastError();
35023    rc = SQLITE_BUSY;
35024  }
35025
35026  OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
35027           pFile->hFile.h, (lockType == _SHM_UNLCK) ? "winUnlockFile" :
35028           "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
35029
35030  return rc;
35031}
35032
35033/* Forward references to VFS methods */
35034static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
35035static int winDelete(sqlite3_vfs *,const char*,int);
35036
35037/*
35038** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
35039**
35040** This is not a VFS shared-memory method; it is a utility function called
35041** by VFS shared-memory methods.
35042*/
35043static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
35044  winShmNode **pp;
35045  winShmNode *p;
35046  assert( winShmMutexHeld() );
35047  OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
35048           osGetCurrentProcessId(), deleteFlag));
35049  pp = &winShmNodeList;
35050  while( (p = *pp)!=0 ){
35051    if( p->nRef==0 ){
35052      int i;
35053      if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
35054      for(i=0; i<p->nRegion; i++){
35055        BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
35056        OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
35057                 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
35058        UNUSED_VARIABLE_VALUE(bRc);
35059        bRc = osCloseHandle(p->aRegion[i].hMap);
35060        OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
35061                 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
35062        UNUSED_VARIABLE_VALUE(bRc);
35063      }
35064      if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
35065        SimulateIOErrorBenign(1);
35066        winClose((sqlite3_file *)&p->hFile);
35067        SimulateIOErrorBenign(0);
35068      }
35069      if( deleteFlag ){
35070        SimulateIOErrorBenign(1);
35071        sqlite3BeginBenignMalloc();
35072        winDelete(pVfs, p->zFilename, 0);
35073        sqlite3EndBenignMalloc();
35074        SimulateIOErrorBenign(0);
35075      }
35076      *pp = p->pNext;
35077      sqlite3_free(p->aRegion);
35078      sqlite3_free(p);
35079    }else{
35080      pp = &p->pNext;
35081    }
35082  }
35083}
35084
35085/*
35086** Open the shared-memory area associated with database file pDbFd.
35087**
35088** When opening a new shared-memory file, if no other instances of that
35089** file are currently open, in this process or in other processes, then
35090** the file must be truncated to zero length or have its header cleared.
35091*/
35092static int winOpenSharedMemory(winFile *pDbFd){
35093  struct winShm *p;                  /* The connection to be opened */
35094  struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
35095  int rc;                            /* Result code */
35096  struct winShmNode *pNew;           /* Newly allocated winShmNode */
35097  int nName;                         /* Size of zName in bytes */
35098
35099  assert( pDbFd->pShm==0 );    /* Not previously opened */
35100
35101  /* Allocate space for the new sqlite3_shm object.  Also speculatively
35102  ** allocate space for a new winShmNode and filename.
35103  */
35104  p = sqlite3MallocZero( sizeof(*p) );
35105  if( p==0 ) return SQLITE_IOERR_NOMEM;
35106  nName = sqlite3Strlen30(pDbFd->zPath);
35107  pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
35108  if( pNew==0 ){
35109    sqlite3_free(p);
35110    return SQLITE_IOERR_NOMEM;
35111  }
35112  pNew->zFilename = (char*)&pNew[1];
35113  sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
35114  sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
35115
35116  /* Look to see if there is an existing winShmNode that can be used.
35117  ** If no matching winShmNode currently exists, create a new one.
35118  */
35119  winShmEnterMutex();
35120  for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
35121    /* TBD need to come up with better match here.  Perhaps
35122    ** use FILE_ID_BOTH_DIR_INFO Structure.
35123    */
35124    if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
35125  }
35126  if( pShmNode ){
35127    sqlite3_free(pNew);
35128  }else{
35129    pShmNode = pNew;
35130    pNew = 0;
35131    ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
35132    pShmNode->pNext = winShmNodeList;
35133    winShmNodeList = pShmNode;
35134
35135    pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
35136    if( pShmNode->mutex==0 ){
35137      rc = SQLITE_IOERR_NOMEM;
35138      goto shm_open_err;
35139    }
35140
35141    rc = winOpen(pDbFd->pVfs,
35142                 pShmNode->zFilename,             /* Name of the file (UTF-8) */
35143                 (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
35144                 SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
35145                 0);
35146    if( SQLITE_OK!=rc ){
35147      goto shm_open_err;
35148    }
35149
35150    /* Check to see if another process is holding the dead-man switch.
35151    ** If not, truncate the file to zero length.
35152    */
35153    if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
35154      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
35155      if( rc!=SQLITE_OK ){
35156        rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
35157                         "winOpenShm", pDbFd->zPath);
35158      }
35159    }
35160    if( rc==SQLITE_OK ){
35161      winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
35162      rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
35163    }
35164    if( rc ) goto shm_open_err;
35165  }
35166
35167  /* Make the new connection a child of the winShmNode */
35168  p->pShmNode = pShmNode;
35169#ifdef SQLITE_DEBUG
35170  p->id = pShmNode->nextShmId++;
35171#endif
35172  pShmNode->nRef++;
35173  pDbFd->pShm = p;
35174  winShmLeaveMutex();
35175
35176  /* The reference count on pShmNode has already been incremented under
35177  ** the cover of the winShmEnterMutex() mutex and the pointer from the
35178  ** new (struct winShm) object to the pShmNode has been set. All that is
35179  ** left to do is to link the new object into the linked list starting
35180  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
35181  ** mutex.
35182  */
35183  sqlite3_mutex_enter(pShmNode->mutex);
35184  p->pNext = pShmNode->pFirst;
35185  pShmNode->pFirst = p;
35186  sqlite3_mutex_leave(pShmNode->mutex);
35187  return SQLITE_OK;
35188
35189  /* Jump here on any error */
35190shm_open_err:
35191  winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
35192  winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
35193  sqlite3_free(p);
35194  sqlite3_free(pNew);
35195  winShmLeaveMutex();
35196  return rc;
35197}
35198
35199/*
35200** Close a connection to shared-memory.  Delete the underlying
35201** storage if deleteFlag is true.
35202*/
35203static int winShmUnmap(
35204  sqlite3_file *fd,          /* Database holding shared memory */
35205  int deleteFlag             /* Delete after closing if true */
35206){
35207  winFile *pDbFd;       /* Database holding shared-memory */
35208  winShm *p;            /* The connection to be closed */
35209  winShmNode *pShmNode; /* The underlying shared-memory file */
35210  winShm **pp;          /* For looping over sibling connections */
35211
35212  pDbFd = (winFile*)fd;
35213  p = pDbFd->pShm;
35214  if( p==0 ) return SQLITE_OK;
35215  pShmNode = p->pShmNode;
35216
35217  /* Remove connection p from the set of connections associated
35218  ** with pShmNode */
35219  sqlite3_mutex_enter(pShmNode->mutex);
35220  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
35221  *pp = p->pNext;
35222
35223  /* Free the connection p */
35224  sqlite3_free(p);
35225  pDbFd->pShm = 0;
35226  sqlite3_mutex_leave(pShmNode->mutex);
35227
35228  /* If pShmNode->nRef has reached 0, then close the underlying
35229  ** shared-memory file, too */
35230  winShmEnterMutex();
35231  assert( pShmNode->nRef>0 );
35232  pShmNode->nRef--;
35233  if( pShmNode->nRef==0 ){
35234    winShmPurge(pDbFd->pVfs, deleteFlag);
35235  }
35236  winShmLeaveMutex();
35237
35238  return SQLITE_OK;
35239}
35240
35241/*
35242** Change the lock state for a shared-memory segment.
35243*/
35244static int winShmLock(
35245  sqlite3_file *fd,          /* Database file holding the shared memory */
35246  int ofst,                  /* First lock to acquire or release */
35247  int n,                     /* Number of locks to acquire or release */
35248  int flags                  /* What to do with the lock */
35249){
35250  winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
35251  winShm *p = pDbFd->pShm;              /* The shared memory being locked */
35252  winShm *pX;                           /* For looping over all siblings */
35253  winShmNode *pShmNode = p->pShmNode;
35254  int rc = SQLITE_OK;                   /* Result code */
35255  u16 mask;                             /* Mask of locks to take or release */
35256
35257  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
35258  assert( n>=1 );
35259  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
35260       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
35261       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
35262       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
35263  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
35264
35265  mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
35266  assert( n>1 || mask==(1<<ofst) );
35267  sqlite3_mutex_enter(pShmNode->mutex);
35268  if( flags & SQLITE_SHM_UNLOCK ){
35269    u16 allMask = 0; /* Mask of locks held by siblings */
35270
35271    /* See if any siblings hold this same lock */
35272    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
35273      if( pX==p ) continue;
35274      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
35275      allMask |= pX->sharedMask;
35276    }
35277
35278    /* Unlock the system-level locks */
35279    if( (mask & allMask)==0 ){
35280      rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
35281    }else{
35282      rc = SQLITE_OK;
35283    }
35284
35285    /* Undo the local locks */
35286    if( rc==SQLITE_OK ){
35287      p->exclMask &= ~mask;
35288      p->sharedMask &= ~mask;
35289    }
35290  }else if( flags & SQLITE_SHM_SHARED ){
35291    u16 allShared = 0;  /* Union of locks held by connections other than "p" */
35292
35293    /* Find out which shared locks are already held by sibling connections.
35294    ** If any sibling already holds an exclusive lock, go ahead and return
35295    ** SQLITE_BUSY.
35296    */
35297    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
35298      if( (pX->exclMask & mask)!=0 ){
35299        rc = SQLITE_BUSY;
35300        break;
35301      }
35302      allShared |= pX->sharedMask;
35303    }
35304
35305    /* Get shared locks at the system level, if necessary */
35306    if( rc==SQLITE_OK ){
35307      if( (allShared & mask)==0 ){
35308        rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
35309      }else{
35310        rc = SQLITE_OK;
35311      }
35312    }
35313
35314    /* Get the local shared locks */
35315    if( rc==SQLITE_OK ){
35316      p->sharedMask |= mask;
35317    }
35318  }else{
35319    /* Make sure no sibling connections hold locks that will block this
35320    ** lock.  If any do, return SQLITE_BUSY right away.
35321    */
35322    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
35323      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
35324        rc = SQLITE_BUSY;
35325        break;
35326      }
35327    }
35328
35329    /* Get the exclusive locks at the system level.  Then if successful
35330    ** also mark the local connection as being locked.
35331    */
35332    if( rc==SQLITE_OK ){
35333      rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
35334      if( rc==SQLITE_OK ){
35335        assert( (p->sharedMask & mask)==0 );
35336        p->exclMask |= mask;
35337      }
35338    }
35339  }
35340  sqlite3_mutex_leave(pShmNode->mutex);
35341  OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
35342           osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
35343           sqlite3ErrName(rc)));
35344  return rc;
35345}
35346
35347/*
35348** Implement a memory barrier or memory fence on shared memory.
35349**
35350** All loads and stores begun before the barrier must complete before
35351** any load or store begun after the barrier.
35352*/
35353static void winShmBarrier(
35354  sqlite3_file *fd          /* Database holding the shared memory */
35355){
35356  UNUSED_PARAMETER(fd);
35357  /* MemoryBarrier(); // does not work -- do not know why not */
35358  winShmEnterMutex();
35359  winShmLeaveMutex();
35360}
35361
35362/*
35363** This function is called to obtain a pointer to region iRegion of the
35364** shared-memory associated with the database file fd. Shared-memory regions
35365** are numbered starting from zero. Each shared-memory region is szRegion
35366** bytes in size.
35367**
35368** If an error occurs, an error code is returned and *pp is set to NULL.
35369**
35370** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
35371** region has not been allocated (by any client, including one running in a
35372** separate process), then *pp is set to NULL and SQLITE_OK returned. If
35373** isWrite is non-zero and the requested shared-memory region has not yet
35374** been allocated, it is allocated by this function.
35375**
35376** If the shared-memory region has already been allocated or is allocated by
35377** this call as described above, then it is mapped into this processes
35378** address space (if it is not already), *pp is set to point to the mapped
35379** memory and SQLITE_OK returned.
35380*/
35381static int winShmMap(
35382  sqlite3_file *fd,               /* Handle open on database file */
35383  int iRegion,                    /* Region to retrieve */
35384  int szRegion,                   /* Size of regions */
35385  int isWrite,                    /* True to extend file if necessary */
35386  void volatile **pp              /* OUT: Mapped memory */
35387){
35388  winFile *pDbFd = (winFile*)fd;
35389  winShm *p = pDbFd->pShm;
35390  winShmNode *pShmNode;
35391  int rc = SQLITE_OK;
35392
35393  if( !p ){
35394    rc = winOpenSharedMemory(pDbFd);
35395    if( rc!=SQLITE_OK ) return rc;
35396    p = pDbFd->pShm;
35397  }
35398  pShmNode = p->pShmNode;
35399
35400  sqlite3_mutex_enter(pShmNode->mutex);
35401  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
35402
35403  if( pShmNode->nRegion<=iRegion ){
35404    struct ShmRegion *apNew;           /* New aRegion[] array */
35405    int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
35406    sqlite3_int64 sz;                  /* Current size of wal-index file */
35407
35408    pShmNode->szRegion = szRegion;
35409
35410    /* The requested region is not mapped into this processes address space.
35411    ** Check to see if it has been allocated (i.e. if the wal-index file is
35412    ** large enough to contain the requested region).
35413    */
35414    rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
35415    if( rc!=SQLITE_OK ){
35416      rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
35417                       "winShmMap1", pDbFd->zPath);
35418      goto shmpage_out;
35419    }
35420
35421    if( sz<nByte ){
35422      /* The requested memory region does not exist. If isWrite is set to
35423      ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
35424      **
35425      ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
35426      ** the requested memory region.
35427      */
35428      if( !isWrite ) goto shmpage_out;
35429      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
35430      if( rc!=SQLITE_OK ){
35431        rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
35432                         "winShmMap2", pDbFd->zPath);
35433        goto shmpage_out;
35434      }
35435    }
35436
35437    /* Map the requested memory region into this processes address space. */
35438    apNew = (struct ShmRegion *)sqlite3_realloc(
35439        pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
35440    );
35441    if( !apNew ){
35442      rc = SQLITE_IOERR_NOMEM;
35443      goto shmpage_out;
35444    }
35445    pShmNode->aRegion = apNew;
35446
35447    while( pShmNode->nRegion<=iRegion ){
35448      HANDLE hMap = NULL;         /* file-mapping handle */
35449      void *pMap = 0;             /* Mapped memory region */
35450
35451#if SQLITE_OS_WINRT
35452      hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
35453          NULL, PAGE_READWRITE, nByte, NULL
35454      );
35455#elif defined(SQLITE_WIN32_HAS_WIDE)
35456      hMap = osCreateFileMappingW(pShmNode->hFile.h,
35457          NULL, PAGE_READWRITE, 0, nByte, NULL
35458      );
35459#elif defined(SQLITE_WIN32_HAS_ANSI)
35460      hMap = osCreateFileMappingA(pShmNode->hFile.h,
35461          NULL, PAGE_READWRITE, 0, nByte, NULL
35462      );
35463#endif
35464      OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
35465               osGetCurrentProcessId(), pShmNode->nRegion, nByte,
35466               hMap ? "ok" : "failed"));
35467      if( hMap ){
35468        int iOffset = pShmNode->nRegion*szRegion;
35469        int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
35470#if SQLITE_OS_WINRT
35471        pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
35472            iOffset - iOffsetShift, szRegion + iOffsetShift
35473        );
35474#else
35475        pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
35476            0, iOffset - iOffsetShift, szRegion + iOffsetShift
35477        );
35478#endif
35479        OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
35480                 osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
35481                 szRegion, pMap ? "ok" : "failed"));
35482      }
35483      if( !pMap ){
35484        pShmNode->lastErrno = osGetLastError();
35485        rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
35486                         "winShmMap3", pDbFd->zPath);
35487        if( hMap ) osCloseHandle(hMap);
35488        goto shmpage_out;
35489      }
35490
35491      pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
35492      pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
35493      pShmNode->nRegion++;
35494    }
35495  }
35496
35497shmpage_out:
35498  if( pShmNode->nRegion>iRegion ){
35499    int iOffset = iRegion*szRegion;
35500    int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
35501    char *p = (char *)pShmNode->aRegion[iRegion].pMap;
35502    *pp = (void *)&p[iOffsetShift];
35503  }else{
35504    *pp = 0;
35505  }
35506  sqlite3_mutex_leave(pShmNode->mutex);
35507  return rc;
35508}
35509
35510#else
35511# define winShmMap     0
35512# define winShmLock    0
35513# define winShmBarrier 0
35514# define winShmUnmap   0
35515#endif /* #ifndef SQLITE_OMIT_WAL */
35516
35517/*
35518** Cleans up the mapped region of the specified file, if any.
35519*/
35520#if SQLITE_MAX_MMAP_SIZE>0
35521static int winUnmapfile(winFile *pFile){
35522  assert( pFile!=0 );
35523  OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
35524           "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
35525           osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
35526           pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
35527  if( pFile->pMapRegion ){
35528    if( !osUnmapViewOfFile(pFile->pMapRegion) ){
35529      pFile->lastErrno = osGetLastError();
35530      OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
35531               "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
35532               pFile->pMapRegion));
35533      return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
35534                         "winUnmapfile1", pFile->zPath);
35535    }
35536    pFile->pMapRegion = 0;
35537    pFile->mmapSize = 0;
35538    pFile->mmapSizeActual = 0;
35539  }
35540  if( pFile->hMap!=NULL ){
35541    if( !osCloseHandle(pFile->hMap) ){
35542      pFile->lastErrno = osGetLastError();
35543      OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
35544               osGetCurrentProcessId(), pFile, pFile->hMap));
35545      return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
35546                         "winUnmapfile2", pFile->zPath);
35547    }
35548    pFile->hMap = NULL;
35549  }
35550  OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
35551           osGetCurrentProcessId(), pFile));
35552  return SQLITE_OK;
35553}
35554
35555/*
35556** Memory map or remap the file opened by file-descriptor pFd (if the file
35557** is already mapped, the existing mapping is replaced by the new). Or, if
35558** there already exists a mapping for this file, and there are still
35559** outstanding xFetch() references to it, this function is a no-op.
35560**
35561** If parameter nByte is non-negative, then it is the requested size of
35562** the mapping to create. Otherwise, if nByte is less than zero, then the
35563** requested size is the size of the file on disk. The actual size of the
35564** created mapping is either the requested size or the value configured
35565** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
35566**
35567** SQLITE_OK is returned if no error occurs (even if the mapping is not
35568** recreated as a result of outstanding references) or an SQLite error
35569** code otherwise.
35570*/
35571static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
35572  sqlite3_int64 nMap = nByte;
35573  int rc;
35574
35575  assert( nMap>=0 || pFd->nFetchOut==0 );
35576  OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
35577           osGetCurrentProcessId(), pFd, nByte));
35578
35579  if( pFd->nFetchOut>0 ) return SQLITE_OK;
35580
35581  if( nMap<0 ){
35582    rc = winFileSize((sqlite3_file*)pFd, &nMap);
35583    if( rc ){
35584      OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
35585               osGetCurrentProcessId(), pFd));
35586      return SQLITE_IOERR_FSTAT;
35587    }
35588  }
35589  if( nMap>pFd->mmapSizeMax ){
35590    nMap = pFd->mmapSizeMax;
35591  }
35592  nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
35593
35594  if( nMap==0 && pFd->mmapSize>0 ){
35595    winUnmapfile(pFd);
35596  }
35597  if( nMap!=pFd->mmapSize ){
35598    void *pNew = 0;
35599    DWORD protect = PAGE_READONLY;
35600    DWORD flags = FILE_MAP_READ;
35601
35602    winUnmapfile(pFd);
35603    if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
35604      protect = PAGE_READWRITE;
35605      flags |= FILE_MAP_WRITE;
35606    }
35607#if SQLITE_OS_WINRT
35608    pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
35609#elif defined(SQLITE_WIN32_HAS_WIDE)
35610    pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
35611                                (DWORD)((nMap>>32) & 0xffffffff),
35612                                (DWORD)(nMap & 0xffffffff), NULL);
35613#elif defined(SQLITE_WIN32_HAS_ANSI)
35614    pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
35615                                (DWORD)((nMap>>32) & 0xffffffff),
35616                                (DWORD)(nMap & 0xffffffff), NULL);
35617#endif
35618    if( pFd->hMap==NULL ){
35619      pFd->lastErrno = osGetLastError();
35620      rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
35621                       "winMapfile1", pFd->zPath);
35622      /* Log the error, but continue normal operation using xRead/xWrite */
35623      OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
35624               osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
35625      return SQLITE_OK;
35626    }
35627    assert( (nMap % winSysInfo.dwPageSize)==0 );
35628    assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
35629#if SQLITE_OS_WINRT
35630    pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
35631#else
35632    pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
35633#endif
35634    if( pNew==NULL ){
35635      osCloseHandle(pFd->hMap);
35636      pFd->hMap = NULL;
35637      pFd->lastErrno = osGetLastError();
35638      rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
35639                       "winMapfile2", pFd->zPath);
35640      /* Log the error, but continue normal operation using xRead/xWrite */
35641      OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
35642               osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
35643      return SQLITE_OK;
35644    }
35645    pFd->pMapRegion = pNew;
35646    pFd->mmapSize = nMap;
35647    pFd->mmapSizeActual = nMap;
35648  }
35649
35650  OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
35651           osGetCurrentProcessId(), pFd));
35652  return SQLITE_OK;
35653}
35654#endif /* SQLITE_MAX_MMAP_SIZE>0 */
35655
35656/*
35657** If possible, return a pointer to a mapping of file fd starting at offset
35658** iOff. The mapping must be valid for at least nAmt bytes.
35659**
35660** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
35661** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
35662** Finally, if an error does occur, return an SQLite error code. The final
35663** value of *pp is undefined in this case.
35664**
35665** If this function does return a pointer, the caller must eventually
35666** release the reference by calling winUnfetch().
35667*/
35668static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
35669#if SQLITE_MAX_MMAP_SIZE>0
35670  winFile *pFd = (winFile*)fd;   /* The underlying database file */
35671#endif
35672  *pp = 0;
35673
35674  OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
35675           osGetCurrentProcessId(), fd, iOff, nAmt, pp));
35676
35677#if SQLITE_MAX_MMAP_SIZE>0
35678  if( pFd->mmapSizeMax>0 ){
35679    if( pFd->pMapRegion==0 ){
35680      int rc = winMapfile(pFd, -1);
35681      if( rc!=SQLITE_OK ){
35682        OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
35683                 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
35684        return rc;
35685      }
35686    }
35687    if( pFd->mmapSize >= iOff+nAmt ){
35688      *pp = &((u8 *)pFd->pMapRegion)[iOff];
35689      pFd->nFetchOut++;
35690    }
35691  }
35692#endif
35693
35694  OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
35695           osGetCurrentProcessId(), fd, pp, *pp));
35696  return SQLITE_OK;
35697}
35698
35699/*
35700** If the third argument is non-NULL, then this function releases a
35701** reference obtained by an earlier call to winFetch(). The second
35702** argument passed to this function must be the same as the corresponding
35703** argument that was passed to the winFetch() invocation.
35704**
35705** Or, if the third argument is NULL, then this function is being called
35706** to inform the VFS layer that, according to POSIX, any existing mapping
35707** may now be invalid and should be unmapped.
35708*/
35709static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
35710#if SQLITE_MAX_MMAP_SIZE>0
35711  winFile *pFd = (winFile*)fd;   /* The underlying database file */
35712
35713  /* If p==0 (unmap the entire file) then there must be no outstanding
35714  ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
35715  ** then there must be at least one outstanding.  */
35716  assert( (p==0)==(pFd->nFetchOut==0) );
35717
35718  /* If p!=0, it must match the iOff value. */
35719  assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
35720
35721  OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
35722           osGetCurrentProcessId(), pFd, iOff, p));
35723
35724  if( p ){
35725    pFd->nFetchOut--;
35726  }else{
35727    /* FIXME:  If Windows truly always prevents truncating or deleting a
35728    ** file while a mapping is held, then the following winUnmapfile() call
35729    ** is unnecessary can can be omitted - potentially improving
35730    ** performance.  */
35731    winUnmapfile(pFd);
35732  }
35733
35734  assert( pFd->nFetchOut>=0 );
35735#endif
35736
35737  OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
35738           osGetCurrentProcessId(), fd));
35739  return SQLITE_OK;
35740}
35741
35742/*
35743** Here ends the implementation of all sqlite3_file methods.
35744**
35745********************** End sqlite3_file Methods *******************************
35746******************************************************************************/
35747
35748/*
35749** This vector defines all the methods that can operate on an
35750** sqlite3_file for win32.
35751*/
35752static const sqlite3_io_methods winIoMethod = {
35753  3,                              /* iVersion */
35754  winClose,                       /* xClose */
35755  winRead,                        /* xRead */
35756  winWrite,                       /* xWrite */
35757  winTruncate,                    /* xTruncate */
35758  winSync,                        /* xSync */
35759  winFileSize,                    /* xFileSize */
35760  winLock,                        /* xLock */
35761  winUnlock,                      /* xUnlock */
35762  winCheckReservedLock,           /* xCheckReservedLock */
35763  winFileControl,                 /* xFileControl */
35764  winSectorSize,                  /* xSectorSize */
35765  winDeviceCharacteristics,       /* xDeviceCharacteristics */
35766  winShmMap,                      /* xShmMap */
35767  winShmLock,                     /* xShmLock */
35768  winShmBarrier,                  /* xShmBarrier */
35769  winShmUnmap,                    /* xShmUnmap */
35770  winFetch,                       /* xFetch */
35771  winUnfetch                      /* xUnfetch */
35772};
35773
35774/****************************************************************************
35775**************************** sqlite3_vfs methods ****************************
35776**
35777** This division contains the implementation of methods on the
35778** sqlite3_vfs object.
35779*/
35780
35781#if defined(__CYGWIN__)
35782/*
35783** Convert a filename from whatever the underlying operating system
35784** supports for filenames into UTF-8.  Space to hold the result is
35785** obtained from malloc and must be freed by the calling function.
35786*/
35787static char *winConvertToUtf8Filename(const void *zFilename){
35788  char *zConverted = 0;
35789  if( osIsNT() ){
35790    zConverted = winUnicodeToUtf8(zFilename);
35791  }
35792#ifdef SQLITE_WIN32_HAS_ANSI
35793  else{
35794    zConverted = sqlite3_win32_mbcs_to_utf8(zFilename);
35795  }
35796#endif
35797  /* caller will handle out of memory */
35798  return zConverted;
35799}
35800#endif
35801
35802/*
35803** Convert a UTF-8 filename into whatever form the underlying
35804** operating system wants filenames in.  Space to hold the result
35805** is obtained from malloc and must be freed by the calling
35806** function.
35807*/
35808static void *winConvertFromUtf8Filename(const char *zFilename){
35809  void *zConverted = 0;
35810  if( osIsNT() ){
35811    zConverted = winUtf8ToUnicode(zFilename);
35812  }
35813#ifdef SQLITE_WIN32_HAS_ANSI
35814  else{
35815    zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
35816  }
35817#endif
35818  /* caller will handle out of memory */
35819  return zConverted;
35820}
35821
35822/*
35823** This function returns non-zero if the specified UTF-8 string buffer
35824** ends with a directory separator character or one was successfully
35825** added to it.
35826*/
35827static int winMakeEndInDirSep(int nBuf, char *zBuf){
35828  if( zBuf ){
35829    int nLen = sqlite3Strlen30(zBuf);
35830    if( nLen>0 ){
35831      if( winIsDirSep(zBuf[nLen-1]) ){
35832        return 1;
35833      }else if( nLen+1<nBuf ){
35834        zBuf[nLen] = winGetDirSep();
35835        zBuf[nLen+1] = '\0';
35836        return 1;
35837      }
35838    }
35839  }
35840  return 0;
35841}
35842
35843/*
35844** Create a temporary file name and store the resulting pointer into pzBuf.
35845** The pointer returned in pzBuf must be freed via sqlite3_free().
35846*/
35847static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
35848  static char zChars[] =
35849    "abcdefghijklmnopqrstuvwxyz"
35850    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
35851    "0123456789";
35852  size_t i, j;
35853  int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
35854  int nMax, nBuf, nDir, nLen;
35855  char *zBuf;
35856
35857  /* It's odd to simulate an io-error here, but really this is just
35858  ** using the io-error infrastructure to test that SQLite handles this
35859  ** function failing.
35860  */
35861  SimulateIOError( return SQLITE_IOERR );
35862
35863  /* Allocate a temporary buffer to store the fully qualified file
35864  ** name for the temporary file.  If this fails, we cannot continue.
35865  */
35866  nMax = pVfs->mxPathname; nBuf = nMax + 2;
35867  zBuf = sqlite3MallocZero( nBuf );
35868  if( !zBuf ){
35869    OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
35870    return SQLITE_IOERR_NOMEM;
35871  }
35872
35873  /* Figure out the effective temporary directory.  First, check if one
35874  ** has been explicitly set by the application; otherwise, use the one
35875  ** configured by the operating system.
35876  */
35877  nDir = nMax - (nPre + 15);
35878  assert( nDir>0 );
35879  if( sqlite3_temp_directory ){
35880    int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
35881    if( nDirLen>0 ){
35882      if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
35883        nDirLen++;
35884      }
35885      if( nDirLen>nDir ){
35886        sqlite3_free(zBuf);
35887        OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
35888        return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
35889      }
35890      sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
35891    }
35892  }
35893#if defined(__CYGWIN__)
35894  else{
35895    static const char *azDirs[] = {
35896       0, /* getenv("SQLITE_TMPDIR") */
35897       0, /* getenv("TMPDIR") */
35898       0, /* getenv("TMP") */
35899       0, /* getenv("TEMP") */
35900       0, /* getenv("USERPROFILE") */
35901       "/var/tmp",
35902       "/usr/tmp",
35903       "/tmp",
35904       ".",
35905       0        /* List terminator */
35906    };
35907    unsigned int i;
35908    const char *zDir = 0;
35909
35910    if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
35911    if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
35912    if( !azDirs[2] ) azDirs[2] = getenv("TMP");
35913    if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
35914    if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
35915    for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
35916      void *zConverted;
35917      if( zDir==0 ) continue;
35918      /* If the path starts with a drive letter followed by the colon
35919      ** character, assume it is already a native Win32 path; otherwise,
35920      ** it must be converted to a native Win32 path via the Cygwin API
35921      ** prior to using it.
35922      */
35923      if( winIsDriveLetterAndColon(zDir) ){
35924        zConverted = winConvertFromUtf8Filename(zDir);
35925        if( !zConverted ){
35926          sqlite3_free(zBuf);
35927          OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
35928          return SQLITE_IOERR_NOMEM;
35929        }
35930        if( winIsDir(zConverted) ){
35931          sqlite3_snprintf(nMax, zBuf, "%s", zDir);
35932          sqlite3_free(zConverted);
35933          break;
35934        }
35935        sqlite3_free(zConverted);
35936      }else{
35937        zConverted = sqlite3MallocZero( nMax+1 );
35938        if( !zConverted ){
35939          sqlite3_free(zBuf);
35940          OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
35941          return SQLITE_IOERR_NOMEM;
35942        }
35943        if( cygwin_conv_path(
35944                osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
35945                zConverted, nMax+1)<0 ){
35946          sqlite3_free(zConverted);
35947          sqlite3_free(zBuf);
35948          OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
35949          return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
35950                             "winGetTempname2", zDir);
35951        }
35952        if( winIsDir(zConverted) ){
35953          /* At this point, we know the candidate directory exists and should
35954          ** be used.  However, we may need to convert the string containing
35955          ** its name into UTF-8 (i.e. if it is UTF-16 right now).
35956          */
35957          char *zUtf8 = winConvertToUtf8Filename(zConverted);
35958          if( !zUtf8 ){
35959            sqlite3_free(zConverted);
35960            sqlite3_free(zBuf);
35961            OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
35962            return SQLITE_IOERR_NOMEM;
35963          }
35964          sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
35965          sqlite3_free(zUtf8);
35966          sqlite3_free(zConverted);
35967          break;
35968        }
35969        sqlite3_free(zConverted);
35970      }
35971    }
35972  }
35973#elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
35974  else if( osIsNT() ){
35975    char *zMulti;
35976    LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
35977    if( !zWidePath ){
35978      sqlite3_free(zBuf);
35979      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
35980      return SQLITE_IOERR_NOMEM;
35981    }
35982    if( osGetTempPathW(nMax, zWidePath)==0 ){
35983      sqlite3_free(zWidePath);
35984      sqlite3_free(zBuf);
35985      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
35986      return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
35987                         "winGetTempname2", 0);
35988    }
35989    zMulti = winUnicodeToUtf8(zWidePath);
35990    if( zMulti ){
35991      sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
35992      sqlite3_free(zMulti);
35993      sqlite3_free(zWidePath);
35994    }else{
35995      sqlite3_free(zWidePath);
35996      sqlite3_free(zBuf);
35997      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
35998      return SQLITE_IOERR_NOMEM;
35999    }
36000  }
36001#ifdef SQLITE_WIN32_HAS_ANSI
36002  else{
36003    char *zUtf8;
36004    char *zMbcsPath = sqlite3MallocZero( nMax );
36005    if( !zMbcsPath ){
36006      sqlite3_free(zBuf);
36007      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
36008      return SQLITE_IOERR_NOMEM;
36009    }
36010    if( osGetTempPathA(nMax, zMbcsPath)==0 ){
36011      sqlite3_free(zBuf);
36012      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
36013      return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
36014                         "winGetTempname3", 0);
36015    }
36016    zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
36017    if( zUtf8 ){
36018      sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
36019      sqlite3_free(zUtf8);
36020    }else{
36021      sqlite3_free(zBuf);
36022      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
36023      return SQLITE_IOERR_NOMEM;
36024    }
36025  }
36026#endif /* SQLITE_WIN32_HAS_ANSI */
36027#endif /* !SQLITE_OS_WINRT */
36028
36029  /*
36030  ** Check to make sure the temporary directory ends with an appropriate
36031  ** separator.  If it does not and there is not enough space left to add
36032  ** one, fail.
36033  */
36034  if( !winMakeEndInDirSep(nDir+1, zBuf) ){
36035    sqlite3_free(zBuf);
36036    OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
36037    return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
36038  }
36039
36040  /*
36041  ** Check that the output buffer is large enough for the temporary file
36042  ** name in the following format:
36043  **
36044  **   "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
36045  **
36046  ** If not, return SQLITE_ERROR.  The number 17 is used here in order to
36047  ** account for the space used by the 15 character random suffix and the
36048  ** two trailing NUL characters.  The final directory separator character
36049  ** has already added if it was not already present.
36050  */
36051  nLen = sqlite3Strlen30(zBuf);
36052  if( (nLen + nPre + 17) > nBuf ){
36053    sqlite3_free(zBuf);
36054    OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
36055    return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
36056  }
36057
36058  sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
36059
36060  j = sqlite3Strlen30(zBuf);
36061  sqlite3_randomness(15, &zBuf[j]);
36062  for(i=0; i<15; i++, j++){
36063    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
36064  }
36065  zBuf[j] = 0;
36066  zBuf[j+1] = 0;
36067  *pzBuf = zBuf;
36068
36069  OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
36070  return SQLITE_OK;
36071}
36072
36073/*
36074** Return TRUE if the named file is really a directory.  Return false if
36075** it is something other than a directory, or if there is any kind of memory
36076** allocation failure.
36077*/
36078static int winIsDir(const void *zConverted){
36079  DWORD attr;
36080  int rc = 0;
36081  DWORD lastErrno;
36082
36083  if( osIsNT() ){
36084    int cnt = 0;
36085    WIN32_FILE_ATTRIBUTE_DATA sAttrData;
36086    memset(&sAttrData, 0, sizeof(sAttrData));
36087    while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
36088                             GetFileExInfoStandard,
36089                             &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
36090    if( !rc ){
36091      return 0; /* Invalid name? */
36092    }
36093    attr = sAttrData.dwFileAttributes;
36094#if SQLITE_OS_WINCE==0
36095  }else{
36096    attr = osGetFileAttributesA((char*)zConverted);
36097#endif
36098  }
36099  return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
36100}
36101
36102/*
36103** Open a file.
36104*/
36105static int winOpen(
36106  sqlite3_vfs *pVfs,        /* Used to get maximum path name length */
36107  const char *zName,        /* Name of the file (UTF-8) */
36108  sqlite3_file *id,         /* Write the SQLite file handle here */
36109  int flags,                /* Open mode flags */
36110  int *pOutFlags            /* Status return flags */
36111){
36112  HANDLE h;
36113  DWORD lastErrno = 0;
36114  DWORD dwDesiredAccess;
36115  DWORD dwShareMode;
36116  DWORD dwCreationDisposition;
36117  DWORD dwFlagsAndAttributes = 0;
36118#if SQLITE_OS_WINCE
36119  int isTemp = 0;
36120#endif
36121  winFile *pFile = (winFile*)id;
36122  void *zConverted;              /* Filename in OS encoding */
36123  const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
36124  int cnt = 0;
36125
36126  /* If argument zPath is a NULL pointer, this function is required to open
36127  ** a temporary file. Use this buffer to store the file name in.
36128  */
36129  char *zTmpname = 0; /* For temporary filename, if necessary. */
36130
36131  int rc = SQLITE_OK;            /* Function Return Code */
36132#if !defined(NDEBUG) || SQLITE_OS_WINCE
36133  int eType = flags&0xFFFFFF00;  /* Type of file to open */
36134#endif
36135
36136  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
36137  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
36138  int isCreate     = (flags & SQLITE_OPEN_CREATE);
36139  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
36140  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
36141
36142#ifndef NDEBUG
36143  int isOpenJournal = (isCreate && (
36144        eType==SQLITE_OPEN_MASTER_JOURNAL
36145     || eType==SQLITE_OPEN_MAIN_JOURNAL
36146     || eType==SQLITE_OPEN_WAL
36147  ));
36148#endif
36149
36150  OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
36151           zUtf8Name, id, flags, pOutFlags));
36152
36153  /* Check the following statements are true:
36154  **
36155  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
36156  **   (b) if CREATE is set, then READWRITE must also be set, and
36157  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
36158  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
36159  */
36160  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
36161  assert(isCreate==0 || isReadWrite);
36162  assert(isExclusive==0 || isCreate);
36163  assert(isDelete==0 || isCreate);
36164
36165  /* The main DB, main journal, WAL file and master journal are never
36166  ** automatically deleted. Nor are they ever temporary files.  */
36167  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
36168  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
36169  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
36170  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
36171
36172  /* Assert that the upper layer has set one of the "file-type" flags. */
36173  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
36174       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
36175       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
36176       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
36177  );
36178
36179  assert( pFile!=0 );
36180  memset(pFile, 0, sizeof(winFile));
36181  pFile->h = INVALID_HANDLE_VALUE;
36182
36183#if SQLITE_OS_WINRT
36184  if( !zUtf8Name && !sqlite3_temp_directory ){
36185    sqlite3_log(SQLITE_ERROR,
36186        "sqlite3_temp_directory variable should be set for WinRT");
36187  }
36188#endif
36189
36190  /* If the second argument to this function is NULL, generate a
36191  ** temporary file name to use
36192  */
36193  if( !zUtf8Name ){
36194    assert( isDelete && !isOpenJournal );
36195    rc = winGetTempname(pVfs, &zTmpname);
36196    if( rc!=SQLITE_OK ){
36197      OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
36198      return rc;
36199    }
36200    zUtf8Name = zTmpname;
36201  }
36202
36203  /* Database filenames are double-zero terminated if they are not
36204  ** URIs with parameters.  Hence, they can always be passed into
36205  ** sqlite3_uri_parameter().
36206  */
36207  assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
36208       zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
36209
36210  /* Convert the filename to the system encoding. */
36211  zConverted = winConvertFromUtf8Filename(zUtf8Name);
36212  if( zConverted==0 ){
36213    sqlite3_free(zTmpname);
36214    OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
36215    return SQLITE_IOERR_NOMEM;
36216  }
36217
36218  if( winIsDir(zConverted) ){
36219    sqlite3_free(zConverted);
36220    sqlite3_free(zTmpname);
36221    OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
36222    return SQLITE_CANTOPEN_ISDIR;
36223  }
36224
36225  if( isReadWrite ){
36226    dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
36227  }else{
36228    dwDesiredAccess = GENERIC_READ;
36229  }
36230
36231  /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
36232  ** created. SQLite doesn't use it to indicate "exclusive access"
36233  ** as it is usually understood.
36234  */
36235  if( isExclusive ){
36236    /* Creates a new file, only if it does not already exist. */
36237    /* If the file exists, it fails. */
36238    dwCreationDisposition = CREATE_NEW;
36239  }else if( isCreate ){
36240    /* Open existing file, or create if it doesn't exist */
36241    dwCreationDisposition = OPEN_ALWAYS;
36242  }else{
36243    /* Opens a file, only if it exists. */
36244    dwCreationDisposition = OPEN_EXISTING;
36245  }
36246
36247  dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
36248
36249  if( isDelete ){
36250#if SQLITE_OS_WINCE
36251    dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
36252    isTemp = 1;
36253#else
36254    dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
36255                               | FILE_ATTRIBUTE_HIDDEN
36256                               | FILE_FLAG_DELETE_ON_CLOSE;
36257#endif
36258  }else{
36259    dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
36260  }
36261  /* Reports from the internet are that performance is always
36262  ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
36263#if SQLITE_OS_WINCE
36264  dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
36265#endif
36266
36267  if( osIsNT() ){
36268#if SQLITE_OS_WINRT
36269    CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
36270    extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
36271    extendedParameters.dwFileAttributes =
36272            dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
36273    extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
36274    extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
36275    extendedParameters.lpSecurityAttributes = NULL;
36276    extendedParameters.hTemplateFile = NULL;
36277    while( (h = osCreateFile2((LPCWSTR)zConverted,
36278                              dwDesiredAccess,
36279                              dwShareMode,
36280                              dwCreationDisposition,
36281                              &extendedParameters))==INVALID_HANDLE_VALUE &&
36282                              winRetryIoerr(&cnt, &lastErrno) ){
36283               /* Noop */
36284    }
36285#else
36286    while( (h = osCreateFileW((LPCWSTR)zConverted,
36287                              dwDesiredAccess,
36288                              dwShareMode, NULL,
36289                              dwCreationDisposition,
36290                              dwFlagsAndAttributes,
36291                              NULL))==INVALID_HANDLE_VALUE &&
36292                              winRetryIoerr(&cnt, &lastErrno) ){
36293               /* Noop */
36294    }
36295#endif
36296  }
36297#ifdef SQLITE_WIN32_HAS_ANSI
36298  else{
36299    while( (h = osCreateFileA((LPCSTR)zConverted,
36300                              dwDesiredAccess,
36301                              dwShareMode, NULL,
36302                              dwCreationDisposition,
36303                              dwFlagsAndAttributes,
36304                              NULL))==INVALID_HANDLE_VALUE &&
36305                              winRetryIoerr(&cnt, &lastErrno) ){
36306               /* Noop */
36307    }
36308  }
36309#endif
36310  winLogIoerr(cnt);
36311
36312  OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
36313           dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
36314
36315  if( h==INVALID_HANDLE_VALUE ){
36316    pFile->lastErrno = lastErrno;
36317    winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
36318    sqlite3_free(zConverted);
36319    sqlite3_free(zTmpname);
36320    if( isReadWrite && !isExclusive ){
36321      return winOpen(pVfs, zName, id,
36322         ((flags|SQLITE_OPEN_READONLY) &
36323                     ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
36324         pOutFlags);
36325    }else{
36326      return SQLITE_CANTOPEN_BKPT;
36327    }
36328  }
36329
36330  if( pOutFlags ){
36331    if( isReadWrite ){
36332      *pOutFlags = SQLITE_OPEN_READWRITE;
36333    }else{
36334      *pOutFlags = SQLITE_OPEN_READONLY;
36335    }
36336  }
36337
36338  OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
36339           "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
36340           *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
36341
36342#if SQLITE_OS_WINCE
36343  if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
36344       && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
36345  ){
36346    osCloseHandle(h);
36347    sqlite3_free(zConverted);
36348    sqlite3_free(zTmpname);
36349    OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
36350    return rc;
36351  }
36352  if( isTemp ){
36353    pFile->zDeleteOnClose = zConverted;
36354  }else
36355#endif
36356  {
36357    sqlite3_free(zConverted);
36358  }
36359
36360  sqlite3_free(zTmpname);
36361  pFile->pMethod = &winIoMethod;
36362  pFile->pVfs = pVfs;
36363  pFile->h = h;
36364  if( isReadonly ){
36365    pFile->ctrlFlags |= WINFILE_RDONLY;
36366  }
36367  if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
36368    pFile->ctrlFlags |= WINFILE_PSOW;
36369  }
36370  pFile->lastErrno = NO_ERROR;
36371  pFile->zPath = zName;
36372#if SQLITE_MAX_MMAP_SIZE>0
36373  pFile->hMap = NULL;
36374  pFile->pMapRegion = 0;
36375  pFile->mmapSize = 0;
36376  pFile->mmapSizeActual = 0;
36377  pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
36378#endif
36379
36380  OpenCounter(+1);
36381  return rc;
36382}
36383
36384/*
36385** Delete the named file.
36386**
36387** Note that Windows does not allow a file to be deleted if some other
36388** process has it open.  Sometimes a virus scanner or indexing program
36389** will open a journal file shortly after it is created in order to do
36390** whatever it does.  While this other process is holding the
36391** file open, we will be unable to delete it.  To work around this
36392** problem, we delay 100 milliseconds and try to delete again.  Up
36393** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
36394** up and returning an error.
36395*/
36396static int winDelete(
36397  sqlite3_vfs *pVfs,          /* Not used on win32 */
36398  const char *zFilename,      /* Name of file to delete */
36399  int syncDir                 /* Not used on win32 */
36400){
36401  int cnt = 0;
36402  int rc;
36403  DWORD attr;
36404  DWORD lastErrno = 0;
36405  void *zConverted;
36406  UNUSED_PARAMETER(pVfs);
36407  UNUSED_PARAMETER(syncDir);
36408
36409  SimulateIOError(return SQLITE_IOERR_DELETE);
36410  OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
36411
36412  zConverted = winConvertFromUtf8Filename(zFilename);
36413  if( zConverted==0 ){
36414    OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
36415    return SQLITE_IOERR_NOMEM;
36416  }
36417  if( osIsNT() ){
36418    do {
36419#if SQLITE_OS_WINRT
36420      WIN32_FILE_ATTRIBUTE_DATA sAttrData;
36421      memset(&sAttrData, 0, sizeof(sAttrData));
36422      if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
36423                                  &sAttrData) ){
36424        attr = sAttrData.dwFileAttributes;
36425      }else{
36426        lastErrno = osGetLastError();
36427        if( lastErrno==ERROR_FILE_NOT_FOUND
36428         || lastErrno==ERROR_PATH_NOT_FOUND ){
36429          rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
36430        }else{
36431          rc = SQLITE_ERROR;
36432        }
36433        break;
36434      }
36435#else
36436      attr = osGetFileAttributesW(zConverted);
36437#endif
36438      if ( attr==INVALID_FILE_ATTRIBUTES ){
36439        lastErrno = osGetLastError();
36440        if( lastErrno==ERROR_FILE_NOT_FOUND
36441         || lastErrno==ERROR_PATH_NOT_FOUND ){
36442          rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
36443        }else{
36444          rc = SQLITE_ERROR;
36445        }
36446        break;
36447      }
36448      if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
36449        rc = SQLITE_ERROR; /* Files only. */
36450        break;
36451      }
36452      if ( osDeleteFileW(zConverted) ){
36453        rc = SQLITE_OK; /* Deleted OK. */
36454        break;
36455      }
36456      if ( !winRetryIoerr(&cnt, &lastErrno) ){
36457        rc = SQLITE_ERROR; /* No more retries. */
36458        break;
36459      }
36460    } while(1);
36461  }
36462#ifdef SQLITE_WIN32_HAS_ANSI
36463  else{
36464    do {
36465      attr = osGetFileAttributesA(zConverted);
36466      if ( attr==INVALID_FILE_ATTRIBUTES ){
36467        lastErrno = osGetLastError();
36468        if( lastErrno==ERROR_FILE_NOT_FOUND
36469         || lastErrno==ERROR_PATH_NOT_FOUND ){
36470          rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
36471        }else{
36472          rc = SQLITE_ERROR;
36473        }
36474        break;
36475      }
36476      if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
36477        rc = SQLITE_ERROR; /* Files only. */
36478        break;
36479      }
36480      if ( osDeleteFileA(zConverted) ){
36481        rc = SQLITE_OK; /* Deleted OK. */
36482        break;
36483      }
36484      if ( !winRetryIoerr(&cnt, &lastErrno) ){
36485        rc = SQLITE_ERROR; /* No more retries. */
36486        break;
36487      }
36488    } while(1);
36489  }
36490#endif
36491  if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
36492    rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
36493  }else{
36494    winLogIoerr(cnt);
36495  }
36496  sqlite3_free(zConverted);
36497  OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
36498  return rc;
36499}
36500
36501/*
36502** Check the existence and status of a file.
36503*/
36504static int winAccess(
36505  sqlite3_vfs *pVfs,         /* Not used on win32 */
36506  const char *zFilename,     /* Name of file to check */
36507  int flags,                 /* Type of test to make on this file */
36508  int *pResOut               /* OUT: Result */
36509){
36510  DWORD attr;
36511  int rc = 0;
36512  DWORD lastErrno = 0;
36513  void *zConverted;
36514  UNUSED_PARAMETER(pVfs);
36515
36516  SimulateIOError( return SQLITE_IOERR_ACCESS; );
36517  OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
36518           zFilename, flags, pResOut));
36519
36520  zConverted = winConvertFromUtf8Filename(zFilename);
36521  if( zConverted==0 ){
36522    OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
36523    return SQLITE_IOERR_NOMEM;
36524  }
36525  if( osIsNT() ){
36526    int cnt = 0;
36527    WIN32_FILE_ATTRIBUTE_DATA sAttrData;
36528    memset(&sAttrData, 0, sizeof(sAttrData));
36529    while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
36530                             GetFileExInfoStandard,
36531                             &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
36532    if( rc ){
36533      /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
36534      ** as if it does not exist.
36535      */
36536      if(    flags==SQLITE_ACCESS_EXISTS
36537          && sAttrData.nFileSizeHigh==0
36538          && sAttrData.nFileSizeLow==0 ){
36539        attr = INVALID_FILE_ATTRIBUTES;
36540      }else{
36541        attr = sAttrData.dwFileAttributes;
36542      }
36543    }else{
36544      winLogIoerr(cnt);
36545      if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
36546        sqlite3_free(zConverted);
36547        return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
36548                           zFilename);
36549      }else{
36550        attr = INVALID_FILE_ATTRIBUTES;
36551      }
36552    }
36553  }
36554#ifdef SQLITE_WIN32_HAS_ANSI
36555  else{
36556    attr = osGetFileAttributesA((char*)zConverted);
36557  }
36558#endif
36559  sqlite3_free(zConverted);
36560  switch( flags ){
36561    case SQLITE_ACCESS_READ:
36562    case SQLITE_ACCESS_EXISTS:
36563      rc = attr!=INVALID_FILE_ATTRIBUTES;
36564      break;
36565    case SQLITE_ACCESS_READWRITE:
36566      rc = attr!=INVALID_FILE_ATTRIBUTES &&
36567             (attr & FILE_ATTRIBUTE_READONLY)==0;
36568      break;
36569    default:
36570      assert(!"Invalid flags argument");
36571  }
36572  *pResOut = rc;
36573  OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
36574           zFilename, pResOut, *pResOut));
36575  return SQLITE_OK;
36576}
36577
36578/*
36579** Returns non-zero if the specified path name starts with a drive letter
36580** followed by a colon character.
36581*/
36582static BOOL winIsDriveLetterAndColon(
36583  const char *zPathname
36584){
36585  return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
36586}
36587
36588/*
36589** Returns non-zero if the specified path name should be used verbatim.  If
36590** non-zero is returned from this function, the calling function must simply
36591** use the provided path name verbatim -OR- resolve it into a full path name
36592** using the GetFullPathName Win32 API function (if available).
36593*/
36594static BOOL winIsVerbatimPathname(
36595  const char *zPathname
36596){
36597  /*
36598  ** If the path name starts with a forward slash or a backslash, it is either
36599  ** a legal UNC name, a volume relative path, or an absolute path name in the
36600  ** "Unix" format on Windows.  There is no easy way to differentiate between
36601  ** the final two cases; therefore, we return the safer return value of TRUE
36602  ** so that callers of this function will simply use it verbatim.
36603  */
36604  if ( winIsDirSep(zPathname[0]) ){
36605    return TRUE;
36606  }
36607
36608  /*
36609  ** If the path name starts with a letter and a colon it is either a volume
36610  ** relative path or an absolute path.  Callers of this function must not
36611  ** attempt to treat it as a relative path name (i.e. they should simply use
36612  ** it verbatim).
36613  */
36614  if ( winIsDriveLetterAndColon(zPathname) ){
36615    return TRUE;
36616  }
36617
36618  /*
36619  ** If we get to this point, the path name should almost certainly be a purely
36620  ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
36621  */
36622  return FALSE;
36623}
36624
36625/*
36626** Turn a relative pathname into a full pathname.  Write the full
36627** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
36628** bytes in size.
36629*/
36630static int winFullPathname(
36631  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
36632  const char *zRelative,        /* Possibly relative input path */
36633  int nFull,                    /* Size of output buffer in bytes */
36634  char *zFull                   /* Output buffer */
36635){
36636
36637#if defined(__CYGWIN__)
36638  SimulateIOError( return SQLITE_ERROR );
36639  UNUSED_PARAMETER(nFull);
36640  assert( nFull>=pVfs->mxPathname );
36641  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
36642    /*
36643    ** NOTE: We are dealing with a relative path name and the data
36644    **       directory has been set.  Therefore, use it as the basis
36645    **       for converting the relative path name to an absolute
36646    **       one by prepending the data directory and a slash.
36647    */
36648    char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
36649    if( !zOut ){
36650      return SQLITE_IOERR_NOMEM;
36651    }
36652    if( cygwin_conv_path(
36653            (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
36654            CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
36655      sqlite3_free(zOut);
36656      return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
36657                         "winFullPathname1", zRelative);
36658    }else{
36659      char *zUtf8 = winConvertToUtf8Filename(zOut);
36660      if( !zUtf8 ){
36661        sqlite3_free(zOut);
36662        return SQLITE_IOERR_NOMEM;
36663      }
36664      sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
36665                       sqlite3_data_directory, winGetDirSep(), zUtf8);
36666      sqlite3_free(zUtf8);
36667      sqlite3_free(zOut);
36668    }
36669  }else{
36670    char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
36671    if( !zOut ){
36672      return SQLITE_IOERR_NOMEM;
36673    }
36674    if( cygwin_conv_path(
36675            (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
36676            zRelative, zOut, pVfs->mxPathname+1)<0 ){
36677      sqlite3_free(zOut);
36678      return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
36679                         "winFullPathname2", zRelative);
36680    }else{
36681      char *zUtf8 = winConvertToUtf8Filename(zOut);
36682      if( !zUtf8 ){
36683        sqlite3_free(zOut);
36684        return SQLITE_IOERR_NOMEM;
36685      }
36686      sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
36687      sqlite3_free(zUtf8);
36688      sqlite3_free(zOut);
36689    }
36690  }
36691  return SQLITE_OK;
36692#endif
36693
36694#if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
36695  SimulateIOError( return SQLITE_ERROR );
36696  /* WinCE has no concept of a relative pathname, or so I am told. */
36697  /* WinRT has no way to convert a relative path to an absolute one. */
36698  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
36699    /*
36700    ** NOTE: We are dealing with a relative path name and the data
36701    **       directory has been set.  Therefore, use it as the basis
36702    **       for converting the relative path name to an absolute
36703    **       one by prepending the data directory and a backslash.
36704    */
36705    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
36706                     sqlite3_data_directory, winGetDirSep(), zRelative);
36707  }else{
36708    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
36709  }
36710  return SQLITE_OK;
36711#endif
36712
36713#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
36714  DWORD nByte;
36715  void *zConverted;
36716  char *zOut;
36717
36718  /* If this path name begins with "/X:", where "X" is any alphabetic
36719  ** character, discard the initial "/" from the pathname.
36720  */
36721  if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
36722    zRelative++;
36723  }
36724
36725  /* It's odd to simulate an io-error here, but really this is just
36726  ** using the io-error infrastructure to test that SQLite handles this
36727  ** function failing. This function could fail if, for example, the
36728  ** current working directory has been unlinked.
36729  */
36730  SimulateIOError( return SQLITE_ERROR );
36731  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
36732    /*
36733    ** NOTE: We are dealing with a relative path name and the data
36734    **       directory has been set.  Therefore, use it as the basis
36735    **       for converting the relative path name to an absolute
36736    **       one by prepending the data directory and a backslash.
36737    */
36738    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
36739                     sqlite3_data_directory, winGetDirSep(), zRelative);
36740    return SQLITE_OK;
36741  }
36742  zConverted = winConvertFromUtf8Filename(zRelative);
36743  if( zConverted==0 ){
36744    return SQLITE_IOERR_NOMEM;
36745  }
36746  if( osIsNT() ){
36747    LPWSTR zTemp;
36748    nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
36749    if( nByte==0 ){
36750      sqlite3_free(zConverted);
36751      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
36752                         "winFullPathname1", zRelative);
36753    }
36754    nByte += 3;
36755    zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
36756    if( zTemp==0 ){
36757      sqlite3_free(zConverted);
36758      return SQLITE_IOERR_NOMEM;
36759    }
36760    nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
36761    if( nByte==0 ){
36762      sqlite3_free(zConverted);
36763      sqlite3_free(zTemp);
36764      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
36765                         "winFullPathname2", zRelative);
36766    }
36767    sqlite3_free(zConverted);
36768    zOut = winUnicodeToUtf8(zTemp);
36769    sqlite3_free(zTemp);
36770  }
36771#ifdef SQLITE_WIN32_HAS_ANSI
36772  else{
36773    char *zTemp;
36774    nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
36775    if( nByte==0 ){
36776      sqlite3_free(zConverted);
36777      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
36778                         "winFullPathname3", zRelative);
36779    }
36780    nByte += 3;
36781    zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
36782    if( zTemp==0 ){
36783      sqlite3_free(zConverted);
36784      return SQLITE_IOERR_NOMEM;
36785    }
36786    nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
36787    if( nByte==0 ){
36788      sqlite3_free(zConverted);
36789      sqlite3_free(zTemp);
36790      return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
36791                         "winFullPathname4", zRelative);
36792    }
36793    sqlite3_free(zConverted);
36794    zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
36795    sqlite3_free(zTemp);
36796  }
36797#endif
36798  if( zOut ){
36799    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
36800    sqlite3_free(zOut);
36801    return SQLITE_OK;
36802  }else{
36803    return SQLITE_IOERR_NOMEM;
36804  }
36805#endif
36806}
36807
36808#ifndef SQLITE_OMIT_LOAD_EXTENSION
36809/*
36810** Interfaces for opening a shared library, finding entry points
36811** within the shared library, and closing the shared library.
36812*/
36813static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
36814  HANDLE h;
36815#if defined(__CYGWIN__)
36816  int nFull = pVfs->mxPathname+1;
36817  char *zFull = sqlite3MallocZero( nFull );
36818  void *zConverted = 0;
36819  if( zFull==0 ){
36820    OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
36821    return 0;
36822  }
36823  if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
36824    sqlite3_free(zFull);
36825    OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
36826    return 0;
36827  }
36828  zConverted = winConvertFromUtf8Filename(zFull);
36829  sqlite3_free(zFull);
36830#else
36831  void *zConverted = winConvertFromUtf8Filename(zFilename);
36832  UNUSED_PARAMETER(pVfs);
36833#endif
36834  if( zConverted==0 ){
36835    OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
36836    return 0;
36837  }
36838  if( osIsNT() ){
36839#if SQLITE_OS_WINRT
36840    h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
36841#else
36842    h = osLoadLibraryW((LPCWSTR)zConverted);
36843#endif
36844  }
36845#ifdef SQLITE_WIN32_HAS_ANSI
36846  else{
36847    h = osLoadLibraryA((char*)zConverted);
36848  }
36849#endif
36850  OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
36851  sqlite3_free(zConverted);
36852  return (void*)h;
36853}
36854static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
36855  UNUSED_PARAMETER(pVfs);
36856  winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
36857}
36858static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
36859  FARPROC proc;
36860  UNUSED_PARAMETER(pVfs);
36861  proc = osGetProcAddressA((HANDLE)pH, zSym);
36862  OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
36863           (void*)pH, zSym, (void*)proc));
36864  return (void(*)(void))proc;
36865}
36866static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
36867  UNUSED_PARAMETER(pVfs);
36868  osFreeLibrary((HANDLE)pHandle);
36869  OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
36870}
36871#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
36872  #define winDlOpen  0
36873  #define winDlError 0
36874  #define winDlSym   0
36875  #define winDlClose 0
36876#endif
36877
36878
36879/*
36880** Write up to nBuf bytes of randomness into zBuf.
36881*/
36882static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
36883  int n = 0;
36884  UNUSED_PARAMETER(pVfs);
36885#if defined(SQLITE_TEST)
36886  n = nBuf;
36887  memset(zBuf, 0, nBuf);
36888#else
36889  if( sizeof(SYSTEMTIME)<=nBuf-n ){
36890    SYSTEMTIME x;
36891    osGetSystemTime(&x);
36892    memcpy(&zBuf[n], &x, sizeof(x));
36893    n += sizeof(x);
36894  }
36895  if( sizeof(DWORD)<=nBuf-n ){
36896    DWORD pid = osGetCurrentProcessId();
36897    memcpy(&zBuf[n], &pid, sizeof(pid));
36898    n += sizeof(pid);
36899  }
36900#if SQLITE_OS_WINRT
36901  if( sizeof(ULONGLONG)<=nBuf-n ){
36902    ULONGLONG cnt = osGetTickCount64();
36903    memcpy(&zBuf[n], &cnt, sizeof(cnt));
36904    n += sizeof(cnt);
36905  }
36906#else
36907  if( sizeof(DWORD)<=nBuf-n ){
36908    DWORD cnt = osGetTickCount();
36909    memcpy(&zBuf[n], &cnt, sizeof(cnt));
36910    n += sizeof(cnt);
36911  }
36912#endif
36913  if( sizeof(LARGE_INTEGER)<=nBuf-n ){
36914    LARGE_INTEGER i;
36915    osQueryPerformanceCounter(&i);
36916    memcpy(&zBuf[n], &i, sizeof(i));
36917    n += sizeof(i);
36918  }
36919#endif
36920  return n;
36921}
36922
36923
36924/*
36925** Sleep for a little while.  Return the amount of time slept.
36926*/
36927static int winSleep(sqlite3_vfs *pVfs, int microsec){
36928  sqlite3_win32_sleep((microsec+999)/1000);
36929  UNUSED_PARAMETER(pVfs);
36930  return ((microsec+999)/1000)*1000;
36931}
36932
36933/*
36934** The following variable, if set to a non-zero value, is interpreted as
36935** the number of seconds since 1970 and is used to set the result of
36936** sqlite3OsCurrentTime() during testing.
36937*/
36938#ifdef SQLITE_TEST
36939SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
36940#endif
36941
36942/*
36943** Find the current time (in Universal Coordinated Time).  Write into *piNow
36944** the current time and date as a Julian Day number times 86_400_000.  In
36945** other words, write into *piNow the number of milliseconds since the Julian
36946** epoch of noon in Greenwich on November 24, 4714 B.C according to the
36947** proleptic Gregorian calendar.
36948**
36949** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
36950** cannot be found.
36951*/
36952static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
36953  /* FILETIME structure is a 64-bit value representing the number of
36954     100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
36955  */
36956  FILETIME ft;
36957  static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
36958#ifdef SQLITE_TEST
36959  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
36960#endif
36961  /* 2^32 - to avoid use of LL and warnings in gcc */
36962  static const sqlite3_int64 max32BitValue =
36963      (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
36964      (sqlite3_int64)294967296;
36965
36966#if SQLITE_OS_WINCE
36967  SYSTEMTIME time;
36968  osGetSystemTime(&time);
36969  /* if SystemTimeToFileTime() fails, it returns zero. */
36970  if (!osSystemTimeToFileTime(&time,&ft)){
36971    return SQLITE_ERROR;
36972  }
36973#else
36974  osGetSystemTimeAsFileTime( &ft );
36975#endif
36976
36977  *piNow = winFiletimeEpoch +
36978            ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
36979               (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
36980
36981#ifdef SQLITE_TEST
36982  if( sqlite3_current_time ){
36983    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
36984  }
36985#endif
36986  UNUSED_PARAMETER(pVfs);
36987  return SQLITE_OK;
36988}
36989
36990/*
36991** Find the current time (in Universal Coordinated Time).  Write the
36992** current time and date as a Julian Day number into *prNow and
36993** return 0.  Return 1 if the time and date cannot be found.
36994*/
36995static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
36996  int rc;
36997  sqlite3_int64 i;
36998  rc = winCurrentTimeInt64(pVfs, &i);
36999  if( !rc ){
37000    *prNow = i/86400000.0;
37001  }
37002  return rc;
37003}
37004
37005/*
37006** The idea is that this function works like a combination of
37007** GetLastError() and FormatMessage() on Windows (or errno and
37008** strerror_r() on Unix). After an error is returned by an OS
37009** function, SQLite calls this function with zBuf pointing to
37010** a buffer of nBuf bytes. The OS layer should populate the
37011** buffer with a nul-terminated UTF-8 encoded error message
37012** describing the last IO error to have occurred within the calling
37013** thread.
37014**
37015** If the error message is too large for the supplied buffer,
37016** it should be truncated. The return value of xGetLastError
37017** is zero if the error message fits in the buffer, or non-zero
37018** otherwise (if the message was truncated). If non-zero is returned,
37019** then it is not necessary to include the nul-terminator character
37020** in the output buffer.
37021**
37022** Not supplying an error message will have no adverse effect
37023** on SQLite. It is fine to have an implementation that never
37024** returns an error message:
37025**
37026**   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
37027**     assert(zBuf[0]=='\0');
37028**     return 0;
37029**   }
37030**
37031** However if an error message is supplied, it will be incorporated
37032** by sqlite into the error message available to the user using
37033** sqlite3_errmsg(), possibly making IO errors easier to debug.
37034*/
37035static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
37036  UNUSED_PARAMETER(pVfs);
37037  return winGetLastErrorMsg(osGetLastError(), nBuf, zBuf);
37038}
37039
37040/*
37041** Initialize and deinitialize the operating system interface.
37042*/
37043SQLITE_API int sqlite3_os_init(void){
37044  static sqlite3_vfs winVfs = {
37045    3,                   /* iVersion */
37046    sizeof(winFile),     /* szOsFile */
37047    SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
37048    0,                   /* pNext */
37049    "win32",             /* zName */
37050    0,                   /* pAppData */
37051    winOpen,             /* xOpen */
37052    winDelete,           /* xDelete */
37053    winAccess,           /* xAccess */
37054    winFullPathname,     /* xFullPathname */
37055    winDlOpen,           /* xDlOpen */
37056    winDlError,          /* xDlError */
37057    winDlSym,            /* xDlSym */
37058    winDlClose,          /* xDlClose */
37059    winRandomness,       /* xRandomness */
37060    winSleep,            /* xSleep */
37061    winCurrentTime,      /* xCurrentTime */
37062    winGetLastError,     /* xGetLastError */
37063    winCurrentTimeInt64, /* xCurrentTimeInt64 */
37064    winSetSystemCall,    /* xSetSystemCall */
37065    winGetSystemCall,    /* xGetSystemCall */
37066    winNextSystemCall,   /* xNextSystemCall */
37067  };
37068#if defined(SQLITE_WIN32_HAS_WIDE)
37069  static sqlite3_vfs winLongPathVfs = {
37070    3,                   /* iVersion */
37071    sizeof(winFile),     /* szOsFile */
37072    SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
37073    0,                   /* pNext */
37074    "win32-longpath",    /* zName */
37075    0,                   /* pAppData */
37076    winOpen,             /* xOpen */
37077    winDelete,           /* xDelete */
37078    winAccess,           /* xAccess */
37079    winFullPathname,     /* xFullPathname */
37080    winDlOpen,           /* xDlOpen */
37081    winDlError,          /* xDlError */
37082    winDlSym,            /* xDlSym */
37083    winDlClose,          /* xDlClose */
37084    winRandomness,       /* xRandomness */
37085    winSleep,            /* xSleep */
37086    winCurrentTime,      /* xCurrentTime */
37087    winGetLastError,     /* xGetLastError */
37088    winCurrentTimeInt64, /* xCurrentTimeInt64 */
37089    winSetSystemCall,    /* xSetSystemCall */
37090    winGetSystemCall,    /* xGetSystemCall */
37091    winNextSystemCall,   /* xNextSystemCall */
37092  };
37093#endif
37094
37095  /* Double-check that the aSyscall[] array has been constructed
37096  ** correctly.  See ticket [bb3a86e890c8e96ab] */
37097  assert( ArraySize(aSyscall)==76 );
37098
37099  /* get memory map allocation granularity */
37100  memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
37101#if SQLITE_OS_WINRT
37102  osGetNativeSystemInfo(&winSysInfo);
37103#else
37104  osGetSystemInfo(&winSysInfo);
37105#endif
37106  assert( winSysInfo.dwAllocationGranularity>0 );
37107  assert( winSysInfo.dwPageSize>0 );
37108
37109  sqlite3_vfs_register(&winVfs, 1);
37110
37111#if defined(SQLITE_WIN32_HAS_WIDE)
37112  sqlite3_vfs_register(&winLongPathVfs, 0);
37113#endif
37114
37115  return SQLITE_OK;
37116}
37117
37118SQLITE_API int sqlite3_os_end(void){
37119#if SQLITE_OS_WINRT
37120  if( sleepObj!=NULL ){
37121    osCloseHandle(sleepObj);
37122    sleepObj = NULL;
37123  }
37124#endif
37125  return SQLITE_OK;
37126}
37127
37128#endif /* SQLITE_OS_WIN */
37129
37130/************** End of os_win.c **********************************************/
37131/************** Begin file bitvec.c ******************************************/
37132/*
37133** 2008 February 16
37134**
37135** The author disclaims copyright to this source code.  In place of
37136** a legal notice, here is a blessing:
37137**
37138**    May you do good and not evil.
37139**    May you find forgiveness for yourself and forgive others.
37140**    May you share freely, never taking more than you give.
37141**
37142*************************************************************************
37143** This file implements an object that represents a fixed-length
37144** bitmap.  Bits are numbered starting with 1.
37145**
37146** A bitmap is used to record which pages of a database file have been
37147** journalled during a transaction, or which pages have the "dont-write"
37148** property.  Usually only a few pages are meet either condition.
37149** So the bitmap is usually sparse and has low cardinality.
37150** But sometimes (for example when during a DROP of a large table) most
37151** or all of the pages in a database can get journalled.  In those cases,
37152** the bitmap becomes dense with high cardinality.  The algorithm needs
37153** to handle both cases well.
37154**
37155** The size of the bitmap is fixed when the object is created.
37156**
37157** All bits are clear when the bitmap is created.  Individual bits
37158** may be set or cleared one at a time.
37159**
37160** Test operations are about 100 times more common that set operations.
37161** Clear operations are exceedingly rare.  There are usually between
37162** 5 and 500 set operations per Bitvec object, though the number of sets can
37163** sometimes grow into tens of thousands or larger.  The size of the
37164** Bitvec object is the number of pages in the database file at the
37165** start of a transaction, and is thus usually less than a few thousand,
37166** but can be as large as 2 billion for a really big database.
37167*/
37168
37169/* Size of the Bitvec structure in bytes. */
37170#define BITVEC_SZ        512
37171
37172/* Round the union size down to the nearest pointer boundary, since that's how
37173** it will be aligned within the Bitvec struct. */
37174#define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
37175
37176/* Type of the array "element" for the bitmap representation.
37177** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
37178** Setting this to the "natural word" size of your CPU may improve
37179** performance. */
37180#define BITVEC_TELEM     u8
37181/* Size, in bits, of the bitmap element. */
37182#define BITVEC_SZELEM    8
37183/* Number of elements in a bitmap array. */
37184#define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
37185/* Number of bits in the bitmap array. */
37186#define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
37187
37188/* Number of u32 values in hash table. */
37189#define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
37190/* Maximum number of entries in hash table before
37191** sub-dividing and re-hashing. */
37192#define BITVEC_MXHASH    (BITVEC_NINT/2)
37193/* Hashing function for the aHash representation.
37194** Empirical testing showed that the *37 multiplier
37195** (an arbitrary prime)in the hash function provided
37196** no fewer collisions than the no-op *1. */
37197#define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
37198
37199#define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
37200
37201
37202/*
37203** A bitmap is an instance of the following structure.
37204**
37205** This bitmap records the existence of zero or more bits
37206** with values between 1 and iSize, inclusive.
37207**
37208** There are three possible representations of the bitmap.
37209** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
37210** bitmap.  The least significant bit is bit 1.
37211**
37212** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
37213** a hash table that will hold up to BITVEC_MXHASH distinct values.
37214**
37215** Otherwise, the value i is redirected into one of BITVEC_NPTR
37216** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
37217** handles up to iDivisor separate values of i.  apSub[0] holds
37218** values between 1 and iDivisor.  apSub[1] holds values between
37219** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
37220** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
37221** to hold deal with values between 1 and iDivisor.
37222*/
37223struct Bitvec {
37224  u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
37225  u32 nSet;       /* Number of bits that are set - only valid for aHash
37226                  ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
37227                  ** this would be 125. */
37228  u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
37229                  /* Should >=0 for apSub element. */
37230                  /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
37231                  /* For a BITVEC_SZ of 512, this would be 34,359,739. */
37232  union {
37233    BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
37234    u32 aHash[BITVEC_NINT];      /* Hash table representation */
37235    Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
37236  } u;
37237};
37238
37239/*
37240** Create a new bitmap object able to handle bits between 0 and iSize,
37241** inclusive.  Return a pointer to the new object.  Return NULL if
37242** malloc fails.
37243*/
37244SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
37245  Bitvec *p;
37246  assert( sizeof(*p)==BITVEC_SZ );
37247  p = sqlite3MallocZero( sizeof(*p) );
37248  if( p ){
37249    p->iSize = iSize;
37250  }
37251  return p;
37252}
37253
37254/*
37255** Check to see if the i-th bit is set.  Return true or false.
37256** If p is NULL (if the bitmap has not been created) or if
37257** i is out of range, then return false.
37258*/
37259SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
37260  if( p==0 ) return 0;
37261  if( i>p->iSize || i==0 ) return 0;
37262  i--;
37263  while( p->iDivisor ){
37264    u32 bin = i/p->iDivisor;
37265    i = i%p->iDivisor;
37266    p = p->u.apSub[bin];
37267    if (!p) {
37268      return 0;
37269    }
37270  }
37271  if( p->iSize<=BITVEC_NBIT ){
37272    return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
37273  } else{
37274    u32 h = BITVEC_HASH(i++);
37275    while( p->u.aHash[h] ){
37276      if( p->u.aHash[h]==i ) return 1;
37277      h = (h+1) % BITVEC_NINT;
37278    }
37279    return 0;
37280  }
37281}
37282
37283/*
37284** Set the i-th bit.  Return 0 on success and an error code if
37285** anything goes wrong.
37286**
37287** This routine might cause sub-bitmaps to be allocated.  Failing
37288** to get the memory needed to hold the sub-bitmap is the only
37289** that can go wrong with an insert, assuming p and i are valid.
37290**
37291** The calling function must ensure that p is a valid Bitvec object
37292** and that the value for "i" is within range of the Bitvec object.
37293** Otherwise the behavior is undefined.
37294*/
37295SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
37296  u32 h;
37297  if( p==0 ) return SQLITE_OK;
37298  assert( i>0 );
37299  assert( i<=p->iSize );
37300  i--;
37301  while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
37302    u32 bin = i/p->iDivisor;
37303    i = i%p->iDivisor;
37304    if( p->u.apSub[bin]==0 ){
37305      p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
37306      if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
37307    }
37308    p = p->u.apSub[bin];
37309  }
37310  if( p->iSize<=BITVEC_NBIT ){
37311    p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
37312    return SQLITE_OK;
37313  }
37314  h = BITVEC_HASH(i++);
37315  /* if there wasn't a hash collision, and this doesn't */
37316  /* completely fill the hash, then just add it without */
37317  /* worring about sub-dividing and re-hashing. */
37318  if( !p->u.aHash[h] ){
37319    if (p->nSet<(BITVEC_NINT-1)) {
37320      goto bitvec_set_end;
37321    } else {
37322      goto bitvec_set_rehash;
37323    }
37324  }
37325  /* there was a collision, check to see if it's already */
37326  /* in hash, if not, try to find a spot for it */
37327  do {
37328    if( p->u.aHash[h]==i ) return SQLITE_OK;
37329    h++;
37330    if( h>=BITVEC_NINT ) h = 0;
37331  } while( p->u.aHash[h] );
37332  /* we didn't find it in the hash.  h points to the first */
37333  /* available free spot. check to see if this is going to */
37334  /* make our hash too "full".  */
37335bitvec_set_rehash:
37336  if( p->nSet>=BITVEC_MXHASH ){
37337    unsigned int j;
37338    int rc;
37339    u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
37340    if( aiValues==0 ){
37341      return SQLITE_NOMEM;
37342    }else{
37343      memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
37344      memset(p->u.apSub, 0, sizeof(p->u.apSub));
37345      p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
37346      rc = sqlite3BitvecSet(p, i);
37347      for(j=0; j<BITVEC_NINT; j++){
37348        if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
37349      }
37350      sqlite3StackFree(0, aiValues);
37351      return rc;
37352    }
37353  }
37354bitvec_set_end:
37355  p->nSet++;
37356  p->u.aHash[h] = i;
37357  return SQLITE_OK;
37358}
37359
37360/*
37361** Clear the i-th bit.
37362**
37363** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
37364** that BitvecClear can use to rebuilt its hash table.
37365*/
37366SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
37367  if( p==0 ) return;
37368  assert( i>0 );
37369  i--;
37370  while( p->iDivisor ){
37371    u32 bin = i/p->iDivisor;
37372    i = i%p->iDivisor;
37373    p = p->u.apSub[bin];
37374    if (!p) {
37375      return;
37376    }
37377  }
37378  if( p->iSize<=BITVEC_NBIT ){
37379    p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
37380  }else{
37381    unsigned int j;
37382    u32 *aiValues = pBuf;
37383    memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
37384    memset(p->u.aHash, 0, sizeof(p->u.aHash));
37385    p->nSet = 0;
37386    for(j=0; j<BITVEC_NINT; j++){
37387      if( aiValues[j] && aiValues[j]!=(i+1) ){
37388        u32 h = BITVEC_HASH(aiValues[j]-1);
37389        p->nSet++;
37390        while( p->u.aHash[h] ){
37391          h++;
37392          if( h>=BITVEC_NINT ) h = 0;
37393        }
37394        p->u.aHash[h] = aiValues[j];
37395      }
37396    }
37397  }
37398}
37399
37400/*
37401** Destroy a bitmap object.  Reclaim all memory used.
37402*/
37403SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
37404  if( p==0 ) return;
37405  if( p->iDivisor ){
37406    unsigned int i;
37407    for(i=0; i<BITVEC_NPTR; i++){
37408      sqlite3BitvecDestroy(p->u.apSub[i]);
37409    }
37410  }
37411  sqlite3_free(p);
37412}
37413
37414/*
37415** Return the value of the iSize parameter specified when Bitvec *p
37416** was created.
37417*/
37418SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
37419  return p->iSize;
37420}
37421
37422#ifndef SQLITE_OMIT_BUILTIN_TEST
37423/*
37424** Let V[] be an array of unsigned characters sufficient to hold
37425** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
37426** Then the following macros can be used to set, clear, or test
37427** individual bits within V.
37428*/
37429#define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
37430#define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
37431#define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
37432
37433/*
37434** This routine runs an extensive test of the Bitvec code.
37435**
37436** The input is an array of integers that acts as a program
37437** to test the Bitvec.  The integers are opcodes followed
37438** by 0, 1, or 3 operands, depending on the opcode.  Another
37439** opcode follows immediately after the last operand.
37440**
37441** There are 6 opcodes numbered from 0 through 5.  0 is the
37442** "halt" opcode and causes the test to end.
37443**
37444**    0          Halt and return the number of errors
37445**    1 N S X    Set N bits beginning with S and incrementing by X
37446**    2 N S X    Clear N bits beginning with S and incrementing by X
37447**    3 N        Set N randomly chosen bits
37448**    4 N        Clear N randomly chosen bits
37449**    5 N S X    Set N bits from S increment X in array only, not in bitvec
37450**
37451** The opcodes 1 through 4 perform set and clear operations are performed
37452** on both a Bitvec object and on a linear array of bits obtained from malloc.
37453** Opcode 5 works on the linear array only, not on the Bitvec.
37454** Opcode 5 is used to deliberately induce a fault in order to
37455** confirm that error detection works.
37456**
37457** At the conclusion of the test the linear array is compared
37458** against the Bitvec object.  If there are any differences,
37459** an error is returned.  If they are the same, zero is returned.
37460**
37461** If a memory allocation error occurs, return -1.
37462*/
37463SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
37464  Bitvec *pBitvec = 0;
37465  unsigned char *pV = 0;
37466  int rc = -1;
37467  int i, nx, pc, op;
37468  void *pTmpSpace;
37469
37470  /* Allocate the Bitvec to be tested and a linear array of
37471  ** bits to act as the reference */
37472  pBitvec = sqlite3BitvecCreate( sz );
37473  pV = sqlite3MallocZero( (sz+7)/8 + 1 );
37474  pTmpSpace = sqlite3_malloc(BITVEC_SZ);
37475  if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
37476
37477  /* NULL pBitvec tests */
37478  sqlite3BitvecSet(0, 1);
37479  sqlite3BitvecClear(0, 1, pTmpSpace);
37480
37481  /* Run the program */
37482  pc = 0;
37483  while( (op = aOp[pc])!=0 ){
37484    switch( op ){
37485      case 1:
37486      case 2:
37487      case 5: {
37488        nx = 4;
37489        i = aOp[pc+2] - 1;
37490        aOp[pc+2] += aOp[pc+3];
37491        break;
37492      }
37493      case 3:
37494      case 4:
37495      default: {
37496        nx = 2;
37497        sqlite3_randomness(sizeof(i), &i);
37498        break;
37499      }
37500    }
37501    if( (--aOp[pc+1]) > 0 ) nx = 0;
37502    pc += nx;
37503    i = (i & 0x7fffffff)%sz;
37504    if( (op & 1)!=0 ){
37505      SETBIT(pV, (i+1));
37506      if( op!=5 ){
37507        if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
37508      }
37509    }else{
37510      CLEARBIT(pV, (i+1));
37511      sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
37512    }
37513  }
37514
37515  /* Test to make sure the linear array exactly matches the
37516  ** Bitvec object.  Start with the assumption that they do
37517  ** match (rc==0).  Change rc to non-zero if a discrepancy
37518  ** is found.
37519  */
37520  rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
37521          + sqlite3BitvecTest(pBitvec, 0)
37522          + (sqlite3BitvecSize(pBitvec) - sz);
37523  for(i=1; i<=sz; i++){
37524    if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
37525      rc = i;
37526      break;
37527    }
37528  }
37529
37530  /* Free allocated structure */
37531bitvec_end:
37532  sqlite3_free(pTmpSpace);
37533  sqlite3_free(pV);
37534  sqlite3BitvecDestroy(pBitvec);
37535  return rc;
37536}
37537#endif /* SQLITE_OMIT_BUILTIN_TEST */
37538
37539/************** End of bitvec.c **********************************************/
37540/************** Begin file pcache.c ******************************************/
37541/*
37542** 2008 August 05
37543**
37544** The author disclaims copyright to this source code.  In place of
37545** a legal notice, here is a blessing:
37546**
37547**    May you do good and not evil.
37548**    May you find forgiveness for yourself and forgive others.
37549**    May you share freely, never taking more than you give.
37550**
37551*************************************************************************
37552** This file implements that page cache.
37553*/
37554
37555/*
37556** A complete page cache is an instance of this structure.
37557*/
37558struct PCache {
37559  PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
37560  PgHdr *pSynced;                     /* Last synced page in dirty page list */
37561  int nRef;                           /* Number of referenced pages */
37562  int szCache;                        /* Configured cache size */
37563  int szPage;                         /* Size of every page in this cache */
37564  int szExtra;                        /* Size of extra space for each page */
37565  u8 bPurgeable;                      /* True if pages are on backing store */
37566  u8 eCreate;                         /* eCreate value for for xFetch() */
37567  int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
37568  void *pStress;                      /* Argument to xStress */
37569  sqlite3_pcache *pCache;             /* Pluggable cache module */
37570  PgHdr *pPage1;                      /* Reference to page 1 */
37571};
37572
37573/*
37574** Some of the assert() macros in this code are too expensive to run
37575** even during normal debugging.  Use them only rarely on long-running
37576** tests.  Enable the expensive asserts using the
37577** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
37578*/
37579#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
37580# define expensive_assert(X)  assert(X)
37581#else
37582# define expensive_assert(X)
37583#endif
37584
37585/********************************** Linked List Management ********************/
37586
37587#if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
37588/*
37589** Check that the pCache->pSynced variable is set correctly. If it
37590** is not, either fail an assert or return zero. Otherwise, return
37591** non-zero. This is only used in debugging builds, as follows:
37592**
37593**   expensive_assert( pcacheCheckSynced(pCache) );
37594*/
37595static int pcacheCheckSynced(PCache *pCache){
37596  PgHdr *p;
37597  for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
37598    assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
37599  }
37600  return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
37601}
37602#endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
37603
37604/*
37605** Remove page pPage from the list of dirty pages.
37606*/
37607static void pcacheRemoveFromDirtyList(PgHdr *pPage){
37608  PCache *p = pPage->pCache;
37609
37610  assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
37611  assert( pPage->pDirtyPrev || pPage==p->pDirty );
37612
37613  /* Update the PCache1.pSynced variable if necessary. */
37614  if( p->pSynced==pPage ){
37615    PgHdr *pSynced = pPage->pDirtyPrev;
37616    while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
37617      pSynced = pSynced->pDirtyPrev;
37618    }
37619    p->pSynced = pSynced;
37620  }
37621
37622  if( pPage->pDirtyNext ){
37623    pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
37624  }else{
37625    assert( pPage==p->pDirtyTail );
37626    p->pDirtyTail = pPage->pDirtyPrev;
37627  }
37628  if( pPage->pDirtyPrev ){
37629    pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
37630  }else{
37631    assert( pPage==p->pDirty );
37632    p->pDirty = pPage->pDirtyNext;
37633    if( p->pDirty==0 && p->bPurgeable ){
37634      assert( p->eCreate==1 );
37635      p->eCreate = 2;
37636    }
37637  }
37638  pPage->pDirtyNext = 0;
37639  pPage->pDirtyPrev = 0;
37640
37641  expensive_assert( pcacheCheckSynced(p) );
37642}
37643
37644/*
37645** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
37646** pPage).
37647*/
37648static void pcacheAddToDirtyList(PgHdr *pPage){
37649  PCache *p = pPage->pCache;
37650
37651  assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
37652
37653  pPage->pDirtyNext = p->pDirty;
37654  if( pPage->pDirtyNext ){
37655    assert( pPage->pDirtyNext->pDirtyPrev==0 );
37656    pPage->pDirtyNext->pDirtyPrev = pPage;
37657  }else if( p->bPurgeable ){
37658    assert( p->eCreate==2 );
37659    p->eCreate = 1;
37660  }
37661  p->pDirty = pPage;
37662  if( !p->pDirtyTail ){
37663    p->pDirtyTail = pPage;
37664  }
37665  if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
37666    p->pSynced = pPage;
37667  }
37668  expensive_assert( pcacheCheckSynced(p) );
37669}
37670
37671/*
37672** Wrapper around the pluggable caches xUnpin method. If the cache is
37673** being used for an in-memory database, this function is a no-op.
37674*/
37675static void pcacheUnpin(PgHdr *p){
37676  PCache *pCache = p->pCache;
37677  if( pCache->bPurgeable ){
37678    if( p->pgno==1 ){
37679      pCache->pPage1 = 0;
37680    }
37681    sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 0);
37682  }
37683}
37684
37685/*************************************************** General Interfaces ******
37686**
37687** Initialize and shutdown the page cache subsystem. Neither of these
37688** functions are threadsafe.
37689*/
37690SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
37691  if( sqlite3GlobalConfig.pcache2.xInit==0 ){
37692    /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
37693    ** built-in default page cache is used instead of the application defined
37694    ** page cache. */
37695    sqlite3PCacheSetDefault();
37696  }
37697  return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
37698}
37699SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
37700  if( sqlite3GlobalConfig.pcache2.xShutdown ){
37701    /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
37702    sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
37703  }
37704}
37705
37706/*
37707** Return the size in bytes of a PCache object.
37708*/
37709SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
37710
37711/*
37712** Create a new PCache object. Storage space to hold the object
37713** has already been allocated and is passed in as the p pointer.
37714** The caller discovers how much space needs to be allocated by
37715** calling sqlite3PcacheSize().
37716*/
37717SQLITE_PRIVATE void sqlite3PcacheOpen(
37718  int szPage,                  /* Size of every page */
37719  int szExtra,                 /* Extra space associated with each page */
37720  int bPurgeable,              /* True if pages are on backing store */
37721  int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
37722  void *pStress,               /* Argument to xStress */
37723  PCache *p                    /* Preallocated space for the PCache */
37724){
37725  memset(p, 0, sizeof(PCache));
37726  p->szPage = szPage;
37727  p->szExtra = szExtra;
37728  p->bPurgeable = bPurgeable;
37729  p->eCreate = 2;
37730  p->xStress = xStress;
37731  p->pStress = pStress;
37732  p->szCache = 100;
37733}
37734
37735/*
37736** Change the page size for PCache object. The caller must ensure that there
37737** are no outstanding page references when this function is called.
37738*/
37739SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
37740  assert( pCache->nRef==0 && pCache->pDirty==0 );
37741  if( pCache->pCache ){
37742    sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
37743    pCache->pCache = 0;
37744    pCache->pPage1 = 0;
37745  }
37746  pCache->szPage = szPage;
37747}
37748
37749/*
37750** Compute the number of pages of cache requested.
37751*/
37752static int numberOfCachePages(PCache *p){
37753  if( p->szCache>=0 ){
37754    return p->szCache;
37755  }else{
37756    return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
37757  }
37758}
37759
37760/*
37761** Try to obtain a page from the cache.
37762*/
37763SQLITE_PRIVATE int sqlite3PcacheFetch(
37764  PCache *pCache,       /* Obtain the page from this cache */
37765  Pgno pgno,            /* Page number to obtain */
37766  int createFlag,       /* If true, create page if it does not exist already */
37767  PgHdr **ppPage        /* Write the page here */
37768){
37769  sqlite3_pcache_page *pPage;
37770  PgHdr *pPgHdr = 0;
37771  int eCreate;
37772
37773  assert( pCache!=0 );
37774  assert( createFlag==1 || createFlag==0 );
37775  assert( pgno>0 );
37776
37777  /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
37778  ** allocate it now.
37779  */
37780  if( !pCache->pCache ){
37781    sqlite3_pcache *p;
37782    if( !createFlag ){
37783      *ppPage = 0;
37784      return SQLITE_OK;
37785    }
37786    p = sqlite3GlobalConfig.pcache2.xCreate(
37787        pCache->szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
37788    );
37789    if( !p ){
37790      return SQLITE_NOMEM;
37791    }
37792    sqlite3GlobalConfig.pcache2.xCachesize(p, numberOfCachePages(pCache));
37793    pCache->pCache = p;
37794  }
37795
37796  /* eCreate defines what to do if the page does not exist.
37797  **    0     Do not allocate a new page.  (createFlag==0)
37798  **    1     Allocate a new page if doing so is inexpensive.
37799  **          (createFlag==1 AND bPurgeable AND pDirty)
37800  **    2     Allocate a new page even it doing so is difficult.
37801  **          (createFlag==1 AND !(bPurgeable AND pDirty)
37802  */
37803  eCreate = createFlag==0 ? 0 : pCache->eCreate;
37804  assert( (createFlag*(1+(!pCache->bPurgeable||!pCache->pDirty)))==eCreate );
37805  pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
37806  if( !pPage && eCreate==1 ){
37807    PgHdr *pPg;
37808
37809    /* Find a dirty page to write-out and recycle. First try to find a
37810    ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
37811    ** cleared), but if that is not possible settle for any other
37812    ** unreferenced dirty page.
37813    */
37814    expensive_assert( pcacheCheckSynced(pCache) );
37815    for(pPg=pCache->pSynced;
37816        pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
37817        pPg=pPg->pDirtyPrev
37818    );
37819    pCache->pSynced = pPg;
37820    if( !pPg ){
37821      for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
37822    }
37823    if( pPg ){
37824      int rc;
37825#ifdef SQLITE_LOG_CACHE_SPILL
37826      sqlite3_log(SQLITE_FULL,
37827                  "spill page %d making room for %d - cache used: %d/%d",
37828                  pPg->pgno, pgno,
37829                  sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
37830                  numberOfCachePages(pCache));
37831#endif
37832      rc = pCache->xStress(pCache->pStress, pPg);
37833      if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
37834        return rc;
37835      }
37836    }
37837
37838    pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
37839  }
37840
37841  if( pPage ){
37842    pPgHdr = (PgHdr *)pPage->pExtra;
37843
37844    if( !pPgHdr->pPage ){
37845      memset(pPgHdr, 0, sizeof(PgHdr));
37846      pPgHdr->pPage = pPage;
37847      pPgHdr->pData = pPage->pBuf;
37848      pPgHdr->pExtra = (void *)&pPgHdr[1];
37849      memset(pPgHdr->pExtra, 0, pCache->szExtra);
37850      pPgHdr->pCache = pCache;
37851      pPgHdr->pgno = pgno;
37852    }
37853    assert( pPgHdr->pCache==pCache );
37854    assert( pPgHdr->pgno==pgno );
37855    assert( pPgHdr->pData==pPage->pBuf );
37856    assert( pPgHdr->pExtra==(void *)&pPgHdr[1] );
37857
37858    if( 0==pPgHdr->nRef ){
37859      pCache->nRef++;
37860    }
37861    pPgHdr->nRef++;
37862    if( pgno==1 ){
37863      pCache->pPage1 = pPgHdr;
37864    }
37865  }
37866  *ppPage = pPgHdr;
37867  return (pPgHdr==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
37868}
37869
37870/*
37871** Decrement the reference count on a page. If the page is clean and the
37872** reference count drops to 0, then it is made elible for recycling.
37873*/
37874SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
37875  assert( p->nRef>0 );
37876  p->nRef--;
37877  if( p->nRef==0 ){
37878    PCache *pCache = p->pCache;
37879    pCache->nRef--;
37880    if( (p->flags&PGHDR_DIRTY)==0 ){
37881      pcacheUnpin(p);
37882    }else{
37883      /* Move the page to the head of the dirty list. */
37884      pcacheRemoveFromDirtyList(p);
37885      pcacheAddToDirtyList(p);
37886    }
37887  }
37888}
37889
37890/*
37891** Increase the reference count of a supplied page by 1.
37892*/
37893SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
37894  assert(p->nRef>0);
37895  p->nRef++;
37896}
37897
37898/*
37899** Drop a page from the cache. There must be exactly one reference to the
37900** page. This function deletes that reference, so after it returns the
37901** page pointed to by p is invalid.
37902*/
37903SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
37904  PCache *pCache;
37905  assert( p->nRef==1 );
37906  if( p->flags&PGHDR_DIRTY ){
37907    pcacheRemoveFromDirtyList(p);
37908  }
37909  pCache = p->pCache;
37910  pCache->nRef--;
37911  if( p->pgno==1 ){
37912    pCache->pPage1 = 0;
37913  }
37914  sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 1);
37915}
37916
37917/*
37918** Make sure the page is marked as dirty. If it isn't dirty already,
37919** make it so.
37920*/
37921SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
37922  p->flags &= ~PGHDR_DONT_WRITE;
37923  assert( p->nRef>0 );
37924  if( 0==(p->flags & PGHDR_DIRTY) ){
37925    p->flags |= PGHDR_DIRTY;
37926    pcacheAddToDirtyList( p);
37927  }
37928}
37929
37930/*
37931** Make sure the page is marked as clean. If it isn't clean already,
37932** make it so.
37933*/
37934SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
37935  if( (p->flags & PGHDR_DIRTY) ){
37936    pcacheRemoveFromDirtyList(p);
37937    p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
37938    if( p->nRef==0 ){
37939      pcacheUnpin(p);
37940    }
37941  }
37942}
37943
37944/*
37945** Make every page in the cache clean.
37946*/
37947SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
37948  PgHdr *p;
37949  while( (p = pCache->pDirty)!=0 ){
37950    sqlite3PcacheMakeClean(p);
37951  }
37952}
37953
37954/*
37955** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
37956*/
37957SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
37958  PgHdr *p;
37959  for(p=pCache->pDirty; p; p=p->pDirtyNext){
37960    p->flags &= ~PGHDR_NEED_SYNC;
37961  }
37962  pCache->pSynced = pCache->pDirtyTail;
37963}
37964
37965/*
37966** Change the page number of page p to newPgno.
37967*/
37968SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
37969  PCache *pCache = p->pCache;
37970  assert( p->nRef>0 );
37971  assert( newPgno>0 );
37972  sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
37973  p->pgno = newPgno;
37974  if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
37975    pcacheRemoveFromDirtyList(p);
37976    pcacheAddToDirtyList(p);
37977  }
37978}
37979
37980/*
37981** Drop every cache entry whose page number is greater than "pgno". The
37982** caller must ensure that there are no outstanding references to any pages
37983** other than page 1 with a page number greater than pgno.
37984**
37985** If there is a reference to page 1 and the pgno parameter passed to this
37986** function is 0, then the data area associated with page 1 is zeroed, but
37987** the page object is not dropped.
37988*/
37989SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
37990  if( pCache->pCache ){
37991    PgHdr *p;
37992    PgHdr *pNext;
37993    for(p=pCache->pDirty; p; p=pNext){
37994      pNext = p->pDirtyNext;
37995      /* This routine never gets call with a positive pgno except right
37996      ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
37997      ** it must be that pgno==0.
37998      */
37999      assert( p->pgno>0 );
38000      if( ALWAYS(p->pgno>pgno) ){
38001        assert( p->flags&PGHDR_DIRTY );
38002        sqlite3PcacheMakeClean(p);
38003      }
38004    }
38005    if( pgno==0 && pCache->pPage1 ){
38006      memset(pCache->pPage1->pData, 0, pCache->szPage);
38007      pgno = 1;
38008    }
38009    sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
38010  }
38011}
38012
38013/*
38014** Close a cache.
38015*/
38016SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
38017  if( pCache->pCache ){
38018    sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
38019  }
38020}
38021
38022/*
38023** Discard the contents of the cache.
38024*/
38025SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
38026  sqlite3PcacheTruncate(pCache, 0);
38027}
38028
38029/*
38030** Merge two lists of pages connected by pDirty and in pgno order.
38031** Do not both fixing the pDirtyPrev pointers.
38032*/
38033static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
38034  PgHdr result, *pTail;
38035  pTail = &result;
38036  while( pA && pB ){
38037    if( pA->pgno<pB->pgno ){
38038      pTail->pDirty = pA;
38039      pTail = pA;
38040      pA = pA->pDirty;
38041    }else{
38042      pTail->pDirty = pB;
38043      pTail = pB;
38044      pB = pB->pDirty;
38045    }
38046  }
38047  if( pA ){
38048    pTail->pDirty = pA;
38049  }else if( pB ){
38050    pTail->pDirty = pB;
38051  }else{
38052    pTail->pDirty = 0;
38053  }
38054  return result.pDirty;
38055}
38056
38057/*
38058** Sort the list of pages in accending order by pgno.  Pages are
38059** connected by pDirty pointers.  The pDirtyPrev pointers are
38060** corrupted by this sort.
38061**
38062** Since there cannot be more than 2^31 distinct pages in a database,
38063** there cannot be more than 31 buckets required by the merge sorter.
38064** One extra bucket is added to catch overflow in case something
38065** ever changes to make the previous sentence incorrect.
38066*/
38067#define N_SORT_BUCKET  32
38068static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
38069  PgHdr *a[N_SORT_BUCKET], *p;
38070  int i;
38071  memset(a, 0, sizeof(a));
38072  while( pIn ){
38073    p = pIn;
38074    pIn = p->pDirty;
38075    p->pDirty = 0;
38076    for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
38077      if( a[i]==0 ){
38078        a[i] = p;
38079        break;
38080      }else{
38081        p = pcacheMergeDirtyList(a[i], p);
38082        a[i] = 0;
38083      }
38084    }
38085    if( NEVER(i==N_SORT_BUCKET-1) ){
38086      /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
38087      ** the input list.  But that is impossible.
38088      */
38089      a[i] = pcacheMergeDirtyList(a[i], p);
38090    }
38091  }
38092  p = a[0];
38093  for(i=1; i<N_SORT_BUCKET; i++){
38094    p = pcacheMergeDirtyList(p, a[i]);
38095  }
38096  return p;
38097}
38098
38099/*
38100** Return a list of all dirty pages in the cache, sorted by page number.
38101*/
38102SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
38103  PgHdr *p;
38104  for(p=pCache->pDirty; p; p=p->pDirtyNext){
38105    p->pDirty = p->pDirtyNext;
38106  }
38107  return pcacheSortDirtyList(pCache->pDirty);
38108}
38109
38110/*
38111** Return the total number of referenced pages held by the cache.
38112*/
38113SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
38114  return pCache->nRef;
38115}
38116
38117/*
38118** Return the number of references to the page supplied as an argument.
38119*/
38120SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
38121  return p->nRef;
38122}
38123
38124/*
38125** Return the total number of pages in the cache.
38126*/
38127SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
38128  int nPage = 0;
38129  if( pCache->pCache ){
38130    nPage = sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
38131  }
38132  return nPage;
38133}
38134
38135#ifdef SQLITE_TEST
38136/*
38137** Get the suggested cache-size value.
38138*/
38139SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
38140  return numberOfCachePages(pCache);
38141}
38142#endif
38143
38144/*
38145** Set the suggested cache-size value.
38146*/
38147SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
38148  pCache->szCache = mxPage;
38149  if( pCache->pCache ){
38150    sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
38151                                           numberOfCachePages(pCache));
38152  }
38153}
38154
38155/*
38156** Free up as much memory as possible from the page cache.
38157*/
38158SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
38159  if( pCache->pCache ){
38160    sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
38161  }
38162}
38163
38164#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
38165/*
38166** For all dirty pages currently in the cache, invoke the specified
38167** callback. This is only used if the SQLITE_CHECK_PAGES macro is
38168** defined.
38169*/
38170SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
38171  PgHdr *pDirty;
38172  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
38173    xIter(pDirty);
38174  }
38175}
38176#endif
38177
38178/************** End of pcache.c **********************************************/
38179/************** Begin file pcache1.c *****************************************/
38180/*
38181** 2008 November 05
38182**
38183** The author disclaims copyright to this source code.  In place of
38184** a legal notice, here is a blessing:
38185**
38186**    May you do good and not evil.
38187**    May you find forgiveness for yourself and forgive others.
38188**    May you share freely, never taking more than you give.
38189**
38190*************************************************************************
38191**
38192** This file implements the default page cache implementation (the
38193** sqlite3_pcache interface). It also contains part of the implementation
38194** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
38195** If the default page cache implementation is overriden, then neither of
38196** these two features are available.
38197*/
38198
38199
38200typedef struct PCache1 PCache1;
38201typedef struct PgHdr1 PgHdr1;
38202typedef struct PgFreeslot PgFreeslot;
38203typedef struct PGroup PGroup;
38204
38205/* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set
38206** of one or more PCaches that are able to recycle each others unpinned
38207** pages when they are under memory pressure.  A PGroup is an instance of
38208** the following object.
38209**
38210** This page cache implementation works in one of two modes:
38211**
38212**   (1)  Every PCache is the sole member of its own PGroup.  There is
38213**        one PGroup per PCache.
38214**
38215**   (2)  There is a single global PGroup that all PCaches are a member
38216**        of.
38217**
38218** Mode 1 uses more memory (since PCache instances are not able to rob
38219** unused pages from other PCaches) but it also operates without a mutex,
38220** and is therefore often faster.  Mode 2 requires a mutex in order to be
38221** threadsafe, but recycles pages more efficiently.
38222**
38223** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
38224** PGroup which is the pcache1.grp global variable and its mutex is
38225** SQLITE_MUTEX_STATIC_LRU.
38226*/
38227struct PGroup {
38228  sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
38229  unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
38230  unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
38231  unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
38232  unsigned int nCurrentPage;     /* Number of purgeable pages allocated */
38233  PgHdr1 *pLruHead, *pLruTail;   /* LRU list of unpinned pages */
38234};
38235
38236/* Each page cache is an instance of the following object.  Every
38237** open database file (including each in-memory database and each
38238** temporary or transient database) has a single page cache which
38239** is an instance of this object.
38240**
38241** Pointers to structures of this type are cast and returned as
38242** opaque sqlite3_pcache* handles.
38243*/
38244struct PCache1 {
38245  /* Cache configuration parameters. Page size (szPage) and the purgeable
38246  ** flag (bPurgeable) are set when the cache is created. nMax may be
38247  ** modified at any time by a call to the pcache1Cachesize() method.
38248  ** The PGroup mutex must be held when accessing nMax.
38249  */
38250  PGroup *pGroup;                     /* PGroup this cache belongs to */
38251  int szPage;                         /* Size of allocated pages in bytes */
38252  int szExtra;                        /* Size of extra space in bytes */
38253  int bPurgeable;                     /* True if cache is purgeable */
38254  unsigned int nMin;                  /* Minimum number of pages reserved */
38255  unsigned int nMax;                  /* Configured "cache_size" value */
38256  unsigned int n90pct;                /* nMax*9/10 */
38257  unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
38258
38259  /* Hash table of all pages. The following variables may only be accessed
38260  ** when the accessor is holding the PGroup mutex.
38261  */
38262  unsigned int nRecyclable;           /* Number of pages in the LRU list */
38263  unsigned int nPage;                 /* Total number of pages in apHash */
38264  unsigned int nHash;                 /* Number of slots in apHash[] */
38265  PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
38266};
38267
38268/*
38269** Each cache entry is represented by an instance of the following
38270** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
38271** PgHdr1.pCache->szPage bytes is allocated directly before this structure
38272** in memory.
38273*/
38274struct PgHdr1 {
38275  sqlite3_pcache_page page;
38276  unsigned int iKey;             /* Key value (page number) */
38277  u8 isPinned;                   /* Page in use, not on the LRU list */
38278  PgHdr1 *pNext;                 /* Next in hash table chain */
38279  PCache1 *pCache;               /* Cache that currently owns this page */
38280  PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
38281  PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
38282};
38283
38284/*
38285** Free slots in the allocator used to divide up the buffer provided using
38286** the SQLITE_CONFIG_PAGECACHE mechanism.
38287*/
38288struct PgFreeslot {
38289  PgFreeslot *pNext;  /* Next free slot */
38290};
38291
38292/*
38293** Global data used by this cache.
38294*/
38295static SQLITE_WSD struct PCacheGlobal {
38296  PGroup grp;                    /* The global PGroup for mode (2) */
38297
38298  /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
38299  ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
38300  ** fixed at sqlite3_initialize() time and do not require mutex protection.
38301  ** The nFreeSlot and pFree values do require mutex protection.
38302  */
38303  int isInit;                    /* True if initialized */
38304  int szSlot;                    /* Size of each free slot */
38305  int nSlot;                     /* The number of pcache slots */
38306  int nReserve;                  /* Try to keep nFreeSlot above this */
38307  void *pStart, *pEnd;           /* Bounds of pagecache malloc range */
38308  /* Above requires no mutex.  Use mutex below for variable that follow. */
38309  sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
38310  PgFreeslot *pFree;             /* Free page blocks */
38311  int nFreeSlot;                 /* Number of unused pcache slots */
38312  /* The following value requires a mutex to change.  We skip the mutex on
38313  ** reading because (1) most platforms read a 32-bit integer atomically and
38314  ** (2) even if an incorrect value is read, no great harm is done since this
38315  ** is really just an optimization. */
38316  int bUnderPressure;            /* True if low on PAGECACHE memory */
38317} pcache1_g;
38318
38319/*
38320** All code in this file should access the global structure above via the
38321** alias "pcache1". This ensures that the WSD emulation is used when
38322** compiling for systems that do not support real WSD.
38323*/
38324#define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
38325
38326/*
38327** Macros to enter and leave the PCache LRU mutex.
38328*/
38329#define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
38330#define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
38331
38332/******************************************************************************/
38333/******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
38334
38335/*
38336** This function is called during initialization if a static buffer is
38337** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
38338** verb to sqlite3_config(). Parameter pBuf points to an allocation large
38339** enough to contain 'n' buffers of 'sz' bytes each.
38340**
38341** This routine is called from sqlite3_initialize() and so it is guaranteed
38342** to be serialized already.  There is no need for further mutexing.
38343*/
38344SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
38345  if( pcache1.isInit ){
38346    PgFreeslot *p;
38347    sz = ROUNDDOWN8(sz);
38348    pcache1.szSlot = sz;
38349    pcache1.nSlot = pcache1.nFreeSlot = n;
38350    pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
38351    pcache1.pStart = pBuf;
38352    pcache1.pFree = 0;
38353    pcache1.bUnderPressure = 0;
38354    while( n-- ){
38355      p = (PgFreeslot*)pBuf;
38356      p->pNext = pcache1.pFree;
38357      pcache1.pFree = p;
38358      pBuf = (void*)&((char*)pBuf)[sz];
38359    }
38360    pcache1.pEnd = pBuf;
38361  }
38362}
38363
38364/*
38365** Malloc function used within this file to allocate space from the buffer
38366** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
38367** such buffer exists or there is no space left in it, this function falls
38368** back to sqlite3Malloc().
38369**
38370** Multiple threads can run this routine at the same time.  Global variables
38371** in pcache1 need to be protected via mutex.
38372*/
38373static void *pcache1Alloc(int nByte){
38374  void *p = 0;
38375  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
38376  sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
38377  if( nByte<=pcache1.szSlot ){
38378    sqlite3_mutex_enter(pcache1.mutex);
38379    p = (PgHdr1 *)pcache1.pFree;
38380    if( p ){
38381      pcache1.pFree = pcache1.pFree->pNext;
38382      pcache1.nFreeSlot--;
38383      pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
38384      assert( pcache1.nFreeSlot>=0 );
38385      sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
38386    }
38387    sqlite3_mutex_leave(pcache1.mutex);
38388  }
38389  if( p==0 ){
38390    /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
38391    ** it from sqlite3Malloc instead.
38392    */
38393    p = sqlite3Malloc(nByte);
38394#ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
38395    if( p ){
38396      int sz = sqlite3MallocSize(p);
38397      sqlite3_mutex_enter(pcache1.mutex);
38398      sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
38399      sqlite3_mutex_leave(pcache1.mutex);
38400    }
38401#endif
38402    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
38403  }
38404  return p;
38405}
38406
38407/*
38408** Free an allocated buffer obtained from pcache1Alloc().
38409*/
38410static int pcache1Free(void *p){
38411  int nFreed = 0;
38412  if( p==0 ) return 0;
38413  if( p>=pcache1.pStart && p<pcache1.pEnd ){
38414    PgFreeslot *pSlot;
38415    sqlite3_mutex_enter(pcache1.mutex);
38416    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
38417    pSlot = (PgFreeslot*)p;
38418    pSlot->pNext = pcache1.pFree;
38419    pcache1.pFree = pSlot;
38420    pcache1.nFreeSlot++;
38421    pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
38422    assert( pcache1.nFreeSlot<=pcache1.nSlot );
38423    sqlite3_mutex_leave(pcache1.mutex);
38424  }else{
38425    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
38426    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
38427    nFreed = sqlite3MallocSize(p);
38428#ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
38429    sqlite3_mutex_enter(pcache1.mutex);
38430    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
38431    sqlite3_mutex_leave(pcache1.mutex);
38432#endif
38433    sqlite3_free(p);
38434  }
38435  return nFreed;
38436}
38437
38438#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
38439/*
38440** Return the size of a pcache allocation
38441*/
38442static int pcache1MemSize(void *p){
38443  if( p>=pcache1.pStart && p<pcache1.pEnd ){
38444    return pcache1.szSlot;
38445  }else{
38446    int iSize;
38447    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
38448    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
38449    iSize = sqlite3MallocSize(p);
38450    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
38451    return iSize;
38452  }
38453}
38454#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
38455
38456/*
38457** Allocate a new page object initially associated with cache pCache.
38458*/
38459static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
38460  PgHdr1 *p = 0;
38461  void *pPg;
38462
38463  /* The group mutex must be released before pcache1Alloc() is called. This
38464  ** is because it may call sqlite3_release_memory(), which assumes that
38465  ** this mutex is not held. */
38466  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
38467  pcache1LeaveMutex(pCache->pGroup);
38468#ifdef SQLITE_PCACHE_SEPARATE_HEADER
38469  pPg = pcache1Alloc(pCache->szPage);
38470  p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
38471  if( !pPg || !p ){
38472    pcache1Free(pPg);
38473    sqlite3_free(p);
38474    pPg = 0;
38475  }
38476#else
38477  pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
38478  p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
38479#endif
38480  pcache1EnterMutex(pCache->pGroup);
38481
38482  if( pPg ){
38483    p->page.pBuf = pPg;
38484    p->page.pExtra = &p[1];
38485    if( pCache->bPurgeable ){
38486      pCache->pGroup->nCurrentPage++;
38487    }
38488    return p;
38489  }
38490  return 0;
38491}
38492
38493/*
38494** Free a page object allocated by pcache1AllocPage().
38495**
38496** The pointer is allowed to be NULL, which is prudent.  But it turns out
38497** that the current implementation happens to never call this routine
38498** with a NULL pointer, so we mark the NULL test with ALWAYS().
38499*/
38500static void pcache1FreePage(PgHdr1 *p){
38501  if( ALWAYS(p) ){
38502    PCache1 *pCache = p->pCache;
38503    assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
38504    pcache1Free(p->page.pBuf);
38505#ifdef SQLITE_PCACHE_SEPARATE_HEADER
38506    sqlite3_free(p);
38507#endif
38508    if( pCache->bPurgeable ){
38509      pCache->pGroup->nCurrentPage--;
38510    }
38511  }
38512}
38513
38514/*
38515** Malloc function used by SQLite to obtain space from the buffer configured
38516** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
38517** exists, this function falls back to sqlite3Malloc().
38518*/
38519SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
38520  return pcache1Alloc(sz);
38521}
38522
38523/*
38524** Free an allocated buffer obtained from sqlite3PageMalloc().
38525*/
38526SQLITE_PRIVATE void sqlite3PageFree(void *p){
38527  pcache1Free(p);
38528}
38529
38530
38531/*
38532** Return true if it desirable to avoid allocating a new page cache
38533** entry.
38534**
38535** If memory was allocated specifically to the page cache using
38536** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
38537** it is desirable to avoid allocating a new page cache entry because
38538** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
38539** for all page cache needs and we should not need to spill the
38540** allocation onto the heap.
38541**
38542** Or, the heap is used for all page cache memory but the heap is
38543** under memory pressure, then again it is desirable to avoid
38544** allocating a new page cache entry in order to avoid stressing
38545** the heap even further.
38546*/
38547static int pcache1UnderMemoryPressure(PCache1 *pCache){
38548  if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
38549    return pcache1.bUnderPressure;
38550  }else{
38551    return sqlite3HeapNearlyFull();
38552  }
38553}
38554
38555/******************************************************************************/
38556/******** General Implementation Functions ************************************/
38557
38558/*
38559** This function is used to resize the hash table used by the cache passed
38560** as the first argument.
38561**
38562** The PCache mutex must be held when this function is called.
38563*/
38564static int pcache1ResizeHash(PCache1 *p){
38565  PgHdr1 **apNew;
38566  unsigned int nNew;
38567  unsigned int i;
38568
38569  assert( sqlite3_mutex_held(p->pGroup->mutex) );
38570
38571  nNew = p->nHash*2;
38572  if( nNew<256 ){
38573    nNew = 256;
38574  }
38575
38576  pcache1LeaveMutex(p->pGroup);
38577  if( p->nHash ){ sqlite3BeginBenignMalloc(); }
38578  apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
38579  if( p->nHash ){ sqlite3EndBenignMalloc(); }
38580  pcache1EnterMutex(p->pGroup);
38581  if( apNew ){
38582    for(i=0; i<p->nHash; i++){
38583      PgHdr1 *pPage;
38584      PgHdr1 *pNext = p->apHash[i];
38585      while( (pPage = pNext)!=0 ){
38586        unsigned int h = pPage->iKey % nNew;
38587        pNext = pPage->pNext;
38588        pPage->pNext = apNew[h];
38589        apNew[h] = pPage;
38590      }
38591    }
38592    sqlite3_free(p->apHash);
38593    p->apHash = apNew;
38594    p->nHash = nNew;
38595  }
38596
38597  return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
38598}
38599
38600/*
38601** This function is used internally to remove the page pPage from the
38602** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
38603** LRU list, then this function is a no-op.
38604**
38605** The PGroup mutex must be held when this function is called.
38606*/
38607static void pcache1PinPage(PgHdr1 *pPage){
38608  PCache1 *pCache;
38609  PGroup *pGroup;
38610
38611  assert( pPage!=0 );
38612  assert( pPage->isPinned==0 );
38613  pCache = pPage->pCache;
38614  pGroup = pCache->pGroup;
38615  assert( pPage->pLruNext || pPage==pGroup->pLruTail );
38616  assert( pPage->pLruPrev || pPage==pGroup->pLruHead );
38617  assert( sqlite3_mutex_held(pGroup->mutex) );
38618  if( pPage->pLruPrev ){
38619    pPage->pLruPrev->pLruNext = pPage->pLruNext;
38620  }else{
38621    pGroup->pLruHead = pPage->pLruNext;
38622  }
38623  if( pPage->pLruNext ){
38624    pPage->pLruNext->pLruPrev = pPage->pLruPrev;
38625  }else{
38626    pGroup->pLruTail = pPage->pLruPrev;
38627  }
38628  pPage->pLruNext = 0;
38629  pPage->pLruPrev = 0;
38630  pPage->isPinned = 1;
38631  pCache->nRecyclable--;
38632}
38633
38634
38635/*
38636** Remove the page supplied as an argument from the hash table
38637** (PCache1.apHash structure) that it is currently stored in.
38638**
38639** The PGroup mutex must be held when this function is called.
38640*/
38641static void pcache1RemoveFromHash(PgHdr1 *pPage){
38642  unsigned int h;
38643  PCache1 *pCache = pPage->pCache;
38644  PgHdr1 **pp;
38645
38646  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
38647  h = pPage->iKey % pCache->nHash;
38648  for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
38649  *pp = (*pp)->pNext;
38650
38651  pCache->nPage--;
38652}
38653
38654/*
38655** If there are currently more than nMaxPage pages allocated, try
38656** to recycle pages to reduce the number allocated to nMaxPage.
38657*/
38658static void pcache1EnforceMaxPage(PGroup *pGroup){
38659  assert( sqlite3_mutex_held(pGroup->mutex) );
38660  while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
38661    PgHdr1 *p = pGroup->pLruTail;
38662    assert( p->pCache->pGroup==pGroup );
38663    assert( p->isPinned==0 );
38664    pcache1PinPage(p);
38665    pcache1RemoveFromHash(p);
38666    pcache1FreePage(p);
38667  }
38668}
38669
38670/*
38671** Discard all pages from cache pCache with a page number (key value)
38672** greater than or equal to iLimit. Any pinned pages that meet this
38673** criteria are unpinned before they are discarded.
38674**
38675** The PCache mutex must be held when this function is called.
38676*/
38677static void pcache1TruncateUnsafe(
38678  PCache1 *pCache,             /* The cache to truncate */
38679  unsigned int iLimit          /* Drop pages with this pgno or larger */
38680){
38681  TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
38682  unsigned int h;
38683  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
38684  for(h=0; h<pCache->nHash; h++){
38685    PgHdr1 **pp = &pCache->apHash[h];
38686    PgHdr1 *pPage;
38687    while( (pPage = *pp)!=0 ){
38688      if( pPage->iKey>=iLimit ){
38689        pCache->nPage--;
38690        *pp = pPage->pNext;
38691        if( !pPage->isPinned ) pcache1PinPage(pPage);
38692        pcache1FreePage(pPage);
38693      }else{
38694        pp = &pPage->pNext;
38695        TESTONLY( nPage++; )
38696      }
38697    }
38698  }
38699  assert( pCache->nPage==nPage );
38700}
38701
38702/******************************************************************************/
38703/******** sqlite3_pcache Methods **********************************************/
38704
38705/*
38706** Implementation of the sqlite3_pcache.xInit method.
38707*/
38708static int pcache1Init(void *NotUsed){
38709  UNUSED_PARAMETER(NotUsed);
38710  assert( pcache1.isInit==0 );
38711  memset(&pcache1, 0, sizeof(pcache1));
38712  if( sqlite3GlobalConfig.bCoreMutex ){
38713    pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
38714    pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
38715  }
38716  pcache1.grp.mxPinned = 10;
38717  pcache1.isInit = 1;
38718  return SQLITE_OK;
38719}
38720
38721/*
38722** Implementation of the sqlite3_pcache.xShutdown method.
38723** Note that the static mutex allocated in xInit does
38724** not need to be freed.
38725*/
38726static void pcache1Shutdown(void *NotUsed){
38727  UNUSED_PARAMETER(NotUsed);
38728  assert( pcache1.isInit!=0 );
38729  memset(&pcache1, 0, sizeof(pcache1));
38730}
38731
38732/*
38733** Implementation of the sqlite3_pcache.xCreate method.
38734**
38735** Allocate a new cache.
38736*/
38737static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
38738  PCache1 *pCache;      /* The newly created page cache */
38739  PGroup *pGroup;       /* The group the new page cache will belong to */
38740  int sz;               /* Bytes of memory required to allocate the new cache */
38741
38742  /*
38743  ** The separateCache variable is true if each PCache has its own private
38744  ** PGroup.  In other words, separateCache is true for mode (1) where no
38745  ** mutexing is required.
38746  **
38747  **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
38748  **
38749  **   *  Always use a unified cache in single-threaded applications
38750  **
38751  **   *  Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
38752  **      use separate caches (mode-1)
38753  */
38754#if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
38755  const int separateCache = 0;
38756#else
38757  int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
38758#endif
38759
38760  assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
38761  assert( szExtra < 300 );
38762
38763  sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
38764  pCache = (PCache1 *)sqlite3MallocZero(sz);
38765  if( pCache ){
38766    if( separateCache ){
38767      pGroup = (PGroup*)&pCache[1];
38768      pGroup->mxPinned = 10;
38769    }else{
38770      pGroup = &pcache1.grp;
38771    }
38772    pCache->pGroup = pGroup;
38773    pCache->szPage = szPage;
38774    pCache->szExtra = szExtra;
38775    pCache->bPurgeable = (bPurgeable ? 1 : 0);
38776    if( bPurgeable ){
38777      pCache->nMin = 10;
38778      pcache1EnterMutex(pGroup);
38779      pGroup->nMinPage += pCache->nMin;
38780      pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
38781      pcache1LeaveMutex(pGroup);
38782    }
38783  }
38784  return (sqlite3_pcache *)pCache;
38785}
38786
38787/*
38788** Implementation of the sqlite3_pcache.xCachesize method.
38789**
38790** Configure the cache_size limit for a cache.
38791*/
38792static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
38793  PCache1 *pCache = (PCache1 *)p;
38794  if( pCache->bPurgeable ){
38795    PGroup *pGroup = pCache->pGroup;
38796    pcache1EnterMutex(pGroup);
38797    pGroup->nMaxPage += (nMax - pCache->nMax);
38798    pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
38799    pCache->nMax = nMax;
38800    pCache->n90pct = pCache->nMax*9/10;
38801    pcache1EnforceMaxPage(pGroup);
38802    pcache1LeaveMutex(pGroup);
38803  }
38804}
38805
38806/*
38807** Implementation of the sqlite3_pcache.xShrink method.
38808**
38809** Free up as much memory as possible.
38810*/
38811static void pcache1Shrink(sqlite3_pcache *p){
38812  PCache1 *pCache = (PCache1*)p;
38813  if( pCache->bPurgeable ){
38814    PGroup *pGroup = pCache->pGroup;
38815    int savedMaxPage;
38816    pcache1EnterMutex(pGroup);
38817    savedMaxPage = pGroup->nMaxPage;
38818    pGroup->nMaxPage = 0;
38819    pcache1EnforceMaxPage(pGroup);
38820    pGroup->nMaxPage = savedMaxPage;
38821    pcache1LeaveMutex(pGroup);
38822  }
38823}
38824
38825/*
38826** Implementation of the sqlite3_pcache.xPagecount method.
38827*/
38828static int pcache1Pagecount(sqlite3_pcache *p){
38829  int n;
38830  PCache1 *pCache = (PCache1*)p;
38831  pcache1EnterMutex(pCache->pGroup);
38832  n = pCache->nPage;
38833  pcache1LeaveMutex(pCache->pGroup);
38834  return n;
38835}
38836
38837/*
38838** Implementation of the sqlite3_pcache.xFetch method.
38839**
38840** Fetch a page by key value.
38841**
38842** Whether or not a new page may be allocated by this function depends on
38843** the value of the createFlag argument.  0 means do not allocate a new
38844** page.  1 means allocate a new page if space is easily available.  2
38845** means to try really hard to allocate a new page.
38846**
38847** For a non-purgeable cache (a cache used as the storage for an in-memory
38848** database) there is really no difference between createFlag 1 and 2.  So
38849** the calling function (pcache.c) will never have a createFlag of 1 on
38850** a non-purgeable cache.
38851**
38852** There are three different approaches to obtaining space for a page,
38853** depending on the value of parameter createFlag (which may be 0, 1 or 2).
38854**
38855**   1. Regardless of the value of createFlag, the cache is searched for a
38856**      copy of the requested page. If one is found, it is returned.
38857**
38858**   2. If createFlag==0 and the page is not already in the cache, NULL is
38859**      returned.
38860**
38861**   3. If createFlag is 1, and the page is not already in the cache, then
38862**      return NULL (do not allocate a new page) if any of the following
38863**      conditions are true:
38864**
38865**       (a) the number of pages pinned by the cache is greater than
38866**           PCache1.nMax, or
38867**
38868**       (b) the number of pages pinned by the cache is greater than
38869**           the sum of nMax for all purgeable caches, less the sum of
38870**           nMin for all other purgeable caches, or
38871**
38872**   4. If none of the first three conditions apply and the cache is marked
38873**      as purgeable, and if one of the following is true:
38874**
38875**       (a) The number of pages allocated for the cache is already
38876**           PCache1.nMax, or
38877**
38878**       (b) The number of pages allocated for all purgeable caches is
38879**           already equal to or greater than the sum of nMax for all
38880**           purgeable caches,
38881**
38882**       (c) The system is under memory pressure and wants to avoid
38883**           unnecessary pages cache entry allocations
38884**
38885**      then attempt to recycle a page from the LRU list. If it is the right
38886**      size, return the recycled buffer. Otherwise, free the buffer and
38887**      proceed to step 5.
38888**
38889**   5. Otherwise, allocate and return a new page buffer.
38890*/
38891static sqlite3_pcache_page *pcache1Fetch(
38892  sqlite3_pcache *p,
38893  unsigned int iKey,
38894  int createFlag
38895){
38896  unsigned int nPinned;
38897  PCache1 *pCache = (PCache1 *)p;
38898  PGroup *pGroup;
38899  PgHdr1 *pPage = 0;
38900
38901  assert( offsetof(PgHdr1,page)==0 );
38902  assert( pCache->bPurgeable || createFlag!=1 );
38903  assert( pCache->bPurgeable || pCache->nMin==0 );
38904  assert( pCache->bPurgeable==0 || pCache->nMin==10 );
38905  assert( pCache->nMin==0 || pCache->bPurgeable );
38906  pcache1EnterMutex(pGroup = pCache->pGroup);
38907
38908  /* Step 1: Search the hash table for an existing entry. */
38909  if( pCache->nHash>0 ){
38910    unsigned int h = iKey % pCache->nHash;
38911    for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
38912  }
38913
38914  /* Step 2: Abort if no existing page is found and createFlag is 0 */
38915  if( pPage ){
38916    if( !pPage->isPinned ) pcache1PinPage(pPage);
38917    goto fetch_out;
38918  }
38919  if( createFlag==0 ){
38920    goto fetch_out;
38921  }
38922
38923  /* The pGroup local variable will normally be initialized by the
38924  ** pcache1EnterMutex() macro above.  But if SQLITE_MUTEX_OMIT is defined,
38925  ** then pcache1EnterMutex() is a no-op, so we have to initialize the
38926  ** local variable here.  Delaying the initialization of pGroup is an
38927  ** optimization:  The common case is to exit the module before reaching
38928  ** this point.
38929  */
38930#ifdef SQLITE_MUTEX_OMIT
38931  pGroup = pCache->pGroup;
38932#endif
38933
38934  /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
38935  assert( pCache->nPage >= pCache->nRecyclable );
38936  nPinned = pCache->nPage - pCache->nRecyclable;
38937  assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
38938  assert( pCache->n90pct == pCache->nMax*9/10 );
38939  if( createFlag==1 && (
38940        nPinned>=pGroup->mxPinned
38941     || nPinned>=pCache->n90pct
38942     || pcache1UnderMemoryPressure(pCache)
38943  )){
38944    goto fetch_out;
38945  }
38946
38947  if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
38948    goto fetch_out;
38949  }
38950  assert( pCache->nHash>0 && pCache->apHash );
38951
38952  /* Step 4. Try to recycle a page. */
38953  if( pCache->bPurgeable && pGroup->pLruTail && (
38954         (pCache->nPage+1>=pCache->nMax)
38955      || pGroup->nCurrentPage>=pGroup->nMaxPage
38956      || pcache1UnderMemoryPressure(pCache)
38957  )){
38958    PCache1 *pOther;
38959    pPage = pGroup->pLruTail;
38960    assert( pPage->isPinned==0 );
38961    pcache1RemoveFromHash(pPage);
38962    pcache1PinPage(pPage);
38963    pOther = pPage->pCache;
38964
38965    /* We want to verify that szPage and szExtra are the same for pOther
38966    ** and pCache.  Assert that we can verify this by comparing sums. */
38967    assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
38968    assert( pCache->szExtra<512 );
38969    assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
38970    assert( pOther->szExtra<512 );
38971
38972    if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
38973      pcache1FreePage(pPage);
38974      pPage = 0;
38975    }else{
38976      pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
38977    }
38978  }
38979
38980  /* Step 5. If a usable page buffer has still not been found,
38981  ** attempt to allocate a new one.
38982  */
38983  if( !pPage ){
38984    if( createFlag==1 ) sqlite3BeginBenignMalloc();
38985    pPage = pcache1AllocPage(pCache);
38986    if( createFlag==1 ) sqlite3EndBenignMalloc();
38987  }
38988
38989  if( pPage ){
38990    unsigned int h = iKey % pCache->nHash;
38991    pCache->nPage++;
38992    pPage->iKey = iKey;
38993    pPage->pNext = pCache->apHash[h];
38994    pPage->pCache = pCache;
38995    pPage->pLruPrev = 0;
38996    pPage->pLruNext = 0;
38997    pPage->isPinned = 1;
38998    *(void **)pPage->page.pExtra = 0;
38999    pCache->apHash[h] = pPage;
39000  }
39001
39002fetch_out:
39003  if( pPage && iKey>pCache->iMaxKey ){
39004    pCache->iMaxKey = iKey;
39005  }
39006  pcache1LeaveMutex(pGroup);
39007  return (sqlite3_pcache_page*)pPage;
39008}
39009
39010
39011/*
39012** Implementation of the sqlite3_pcache.xUnpin method.
39013**
39014** Mark a page as unpinned (eligible for asynchronous recycling).
39015*/
39016static void pcache1Unpin(
39017  sqlite3_pcache *p,
39018  sqlite3_pcache_page *pPg,
39019  int reuseUnlikely
39020){
39021  PCache1 *pCache = (PCache1 *)p;
39022  PgHdr1 *pPage = (PgHdr1 *)pPg;
39023  PGroup *pGroup = pCache->pGroup;
39024
39025  assert( pPage->pCache==pCache );
39026  pcache1EnterMutex(pGroup);
39027
39028  /* It is an error to call this function if the page is already
39029  ** part of the PGroup LRU list.
39030  */
39031  assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
39032  assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
39033  assert( pPage->isPinned==1 );
39034
39035  if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
39036    pcache1RemoveFromHash(pPage);
39037    pcache1FreePage(pPage);
39038  }else{
39039    /* Add the page to the PGroup LRU list. */
39040    if( pGroup->pLruHead ){
39041      pGroup->pLruHead->pLruPrev = pPage;
39042      pPage->pLruNext = pGroup->pLruHead;
39043      pGroup->pLruHead = pPage;
39044    }else{
39045      pGroup->pLruTail = pPage;
39046      pGroup->pLruHead = pPage;
39047    }
39048    pCache->nRecyclable++;
39049    pPage->isPinned = 0;
39050  }
39051
39052  pcache1LeaveMutex(pCache->pGroup);
39053}
39054
39055/*
39056** Implementation of the sqlite3_pcache.xRekey method.
39057*/
39058static void pcache1Rekey(
39059  sqlite3_pcache *p,
39060  sqlite3_pcache_page *pPg,
39061  unsigned int iOld,
39062  unsigned int iNew
39063){
39064  PCache1 *pCache = (PCache1 *)p;
39065  PgHdr1 *pPage = (PgHdr1 *)pPg;
39066  PgHdr1 **pp;
39067  unsigned int h;
39068  assert( pPage->iKey==iOld );
39069  assert( pPage->pCache==pCache );
39070
39071  pcache1EnterMutex(pCache->pGroup);
39072
39073  h = iOld%pCache->nHash;
39074  pp = &pCache->apHash[h];
39075  while( (*pp)!=pPage ){
39076    pp = &(*pp)->pNext;
39077  }
39078  *pp = pPage->pNext;
39079
39080  h = iNew%pCache->nHash;
39081  pPage->iKey = iNew;
39082  pPage->pNext = pCache->apHash[h];
39083  pCache->apHash[h] = pPage;
39084  if( iNew>pCache->iMaxKey ){
39085    pCache->iMaxKey = iNew;
39086  }
39087
39088  pcache1LeaveMutex(pCache->pGroup);
39089}
39090
39091/*
39092** Implementation of the sqlite3_pcache.xTruncate method.
39093**
39094** Discard all unpinned pages in the cache with a page number equal to
39095** or greater than parameter iLimit. Any pinned pages with a page number
39096** equal to or greater than iLimit are implicitly unpinned.
39097*/
39098static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
39099  PCache1 *pCache = (PCache1 *)p;
39100  pcache1EnterMutex(pCache->pGroup);
39101  if( iLimit<=pCache->iMaxKey ){
39102    pcache1TruncateUnsafe(pCache, iLimit);
39103    pCache->iMaxKey = iLimit-1;
39104  }
39105  pcache1LeaveMutex(pCache->pGroup);
39106}
39107
39108/*
39109** Implementation of the sqlite3_pcache.xDestroy method.
39110**
39111** Destroy a cache allocated using pcache1Create().
39112*/
39113static void pcache1Destroy(sqlite3_pcache *p){
39114  PCache1 *pCache = (PCache1 *)p;
39115  PGroup *pGroup = pCache->pGroup;
39116  assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
39117  pcache1EnterMutex(pGroup);
39118  pcache1TruncateUnsafe(pCache, 0);
39119  assert( pGroup->nMaxPage >= pCache->nMax );
39120  pGroup->nMaxPage -= pCache->nMax;
39121  assert( pGroup->nMinPage >= pCache->nMin );
39122  pGroup->nMinPage -= pCache->nMin;
39123  pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
39124  pcache1EnforceMaxPage(pGroup);
39125  pcache1LeaveMutex(pGroup);
39126  sqlite3_free(pCache->apHash);
39127  sqlite3_free(pCache);
39128}
39129
39130/*
39131** This function is called during initialization (sqlite3_initialize()) to
39132** install the default pluggable cache module, assuming the user has not
39133** already provided an alternative.
39134*/
39135SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
39136  static const sqlite3_pcache_methods2 defaultMethods = {
39137    1,                       /* iVersion */
39138    0,                       /* pArg */
39139    pcache1Init,             /* xInit */
39140    pcache1Shutdown,         /* xShutdown */
39141    pcache1Create,           /* xCreate */
39142    pcache1Cachesize,        /* xCachesize */
39143    pcache1Pagecount,        /* xPagecount */
39144    pcache1Fetch,            /* xFetch */
39145    pcache1Unpin,            /* xUnpin */
39146    pcache1Rekey,            /* xRekey */
39147    pcache1Truncate,         /* xTruncate */
39148    pcache1Destroy,          /* xDestroy */
39149    pcache1Shrink            /* xShrink */
39150  };
39151  sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
39152}
39153
39154#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
39155/*
39156** This function is called to free superfluous dynamically allocated memory
39157** held by the pager system. Memory in use by any SQLite pager allocated
39158** by the current thread may be sqlite3_free()ed.
39159**
39160** nReq is the number of bytes of memory required. Once this much has
39161** been released, the function returns. The return value is the total number
39162** of bytes of memory released.
39163*/
39164SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
39165  int nFree = 0;
39166  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
39167  assert( sqlite3_mutex_notheld(pcache1.mutex) );
39168  if( pcache1.pStart==0 ){
39169    PgHdr1 *p;
39170    pcache1EnterMutex(&pcache1.grp);
39171    while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
39172      nFree += pcache1MemSize(p->page.pBuf);
39173#ifdef SQLITE_PCACHE_SEPARATE_HEADER
39174      nFree += sqlite3MemSize(p);
39175#endif
39176      assert( p->isPinned==0 );
39177      pcache1PinPage(p);
39178      pcache1RemoveFromHash(p);
39179      pcache1FreePage(p);
39180    }
39181    pcache1LeaveMutex(&pcache1.grp);
39182  }
39183  return nFree;
39184}
39185#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
39186
39187#ifdef SQLITE_TEST
39188/*
39189** This function is used by test procedures to inspect the internal state
39190** of the global cache.
39191*/
39192SQLITE_PRIVATE void sqlite3PcacheStats(
39193  int *pnCurrent,      /* OUT: Total number of pages cached */
39194  int *pnMax,          /* OUT: Global maximum cache size */
39195  int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
39196  int *pnRecyclable    /* OUT: Total number of pages available for recycling */
39197){
39198  PgHdr1 *p;
39199  int nRecyclable = 0;
39200  for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
39201    assert( p->isPinned==0 );
39202    nRecyclable++;
39203  }
39204  *pnCurrent = pcache1.grp.nCurrentPage;
39205  *pnMax = (int)pcache1.grp.nMaxPage;
39206  *pnMin = (int)pcache1.grp.nMinPage;
39207  *pnRecyclable = nRecyclable;
39208}
39209#endif
39210
39211/************** End of pcache1.c *********************************************/
39212/************** Begin file rowset.c ******************************************/
39213/*
39214** 2008 December 3
39215**
39216** The author disclaims copyright to this source code.  In place of
39217** a legal notice, here is a blessing:
39218**
39219**    May you do good and not evil.
39220**    May you find forgiveness for yourself and forgive others.
39221**    May you share freely, never taking more than you give.
39222**
39223*************************************************************************
39224**
39225** This module implements an object we call a "RowSet".
39226**
39227** The RowSet object is a collection of rowids.  Rowids
39228** are inserted into the RowSet in an arbitrary order.  Inserts
39229** can be intermixed with tests to see if a given rowid has been
39230** previously inserted into the RowSet.
39231**
39232** After all inserts are finished, it is possible to extract the
39233** elements of the RowSet in sorted order.  Once this extraction
39234** process has started, no new elements may be inserted.
39235**
39236** Hence, the primitive operations for a RowSet are:
39237**
39238**    CREATE
39239**    INSERT
39240**    TEST
39241**    SMALLEST
39242**    DESTROY
39243**
39244** The CREATE and DESTROY primitives are the constructor and destructor,
39245** obviously.  The INSERT primitive adds a new element to the RowSet.
39246** TEST checks to see if an element is already in the RowSet.  SMALLEST
39247** extracts the least value from the RowSet.
39248**
39249** The INSERT primitive might allocate additional memory.  Memory is
39250** allocated in chunks so most INSERTs do no allocation.  There is an
39251** upper bound on the size of allocated memory.  No memory is freed
39252** until DESTROY.
39253**
39254** The TEST primitive includes a "batch" number.  The TEST primitive
39255** will only see elements that were inserted before the last change
39256** in the batch number.  In other words, if an INSERT occurs between
39257** two TESTs where the TESTs have the same batch nubmer, then the
39258** value added by the INSERT will not be visible to the second TEST.
39259** The initial batch number is zero, so if the very first TEST contains
39260** a non-zero batch number, it will see all prior INSERTs.
39261**
39262** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
39263** that is attempted.
39264**
39265** The cost of an INSERT is roughly constant.  (Sometime new memory
39266** has to be allocated on an INSERT.)  The cost of a TEST with a new
39267** batch number is O(NlogN) where N is the number of elements in the RowSet.
39268** The cost of a TEST using the same batch number is O(logN).  The cost
39269** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
39270** primitives are constant time.  The cost of DESTROY is O(N).
39271**
39272** There is an added cost of O(N) when switching between TEST and
39273** SMALLEST primitives.
39274*/
39275
39276
39277/*
39278** Target size for allocation chunks.
39279*/
39280#define ROWSET_ALLOCATION_SIZE 1024
39281
39282/*
39283** The number of rowset entries per allocation chunk.
39284*/
39285#define ROWSET_ENTRY_PER_CHUNK  \
39286                       ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
39287
39288/*
39289** Each entry in a RowSet is an instance of the following object.
39290**
39291** This same object is reused to store a linked list of trees of RowSetEntry
39292** objects.  In that alternative use, pRight points to the next entry
39293** in the list, pLeft points to the tree, and v is unused.  The
39294** RowSet.pForest value points to the head of this forest list.
39295*/
39296struct RowSetEntry {
39297  i64 v;                        /* ROWID value for this entry */
39298  struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
39299  struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
39300};
39301
39302/*
39303** RowSetEntry objects are allocated in large chunks (instances of the
39304** following structure) to reduce memory allocation overhead.  The
39305** chunks are kept on a linked list so that they can be deallocated
39306** when the RowSet is destroyed.
39307*/
39308struct RowSetChunk {
39309  struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
39310  struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
39311};
39312
39313/*
39314** A RowSet in an instance of the following structure.
39315**
39316** A typedef of this structure if found in sqliteInt.h.
39317*/
39318struct RowSet {
39319  struct RowSetChunk *pChunk;    /* List of all chunk allocations */
39320  sqlite3 *db;                   /* The database connection */
39321  struct RowSetEntry *pEntry;    /* List of entries using pRight */
39322  struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
39323  struct RowSetEntry *pFresh;    /* Source of new entry objects */
39324  struct RowSetEntry *pForest;   /* List of binary trees of entries */
39325  u16 nFresh;                    /* Number of objects on pFresh */
39326  u16 rsFlags;                   /* Various flags */
39327  int iBatch;                    /* Current insert batch */
39328};
39329
39330/*
39331** Allowed values for RowSet.rsFlags
39332*/
39333#define ROWSET_SORTED  0x01   /* True if RowSet.pEntry is sorted */
39334#define ROWSET_NEXT    0x02   /* True if sqlite3RowSetNext() has been called */
39335
39336/*
39337** Turn bulk memory into a RowSet object.  N bytes of memory
39338** are available at pSpace.  The db pointer is used as a memory context
39339** for any subsequent allocations that need to occur.
39340** Return a pointer to the new RowSet object.
39341**
39342** It must be the case that N is sufficient to make a Rowset.  If not
39343** an assertion fault occurs.
39344**
39345** If N is larger than the minimum, use the surplus as an initial
39346** allocation of entries available to be filled.
39347*/
39348SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
39349  RowSet *p;
39350  assert( N >= ROUND8(sizeof(*p)) );
39351  p = pSpace;
39352  p->pChunk = 0;
39353  p->db = db;
39354  p->pEntry = 0;
39355  p->pLast = 0;
39356  p->pForest = 0;
39357  p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
39358  p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
39359  p->rsFlags = ROWSET_SORTED;
39360  p->iBatch = 0;
39361  return p;
39362}
39363
39364/*
39365** Deallocate all chunks from a RowSet.  This frees all memory that
39366** the RowSet has allocated over its lifetime.  This routine is
39367** the destructor for the RowSet.
39368*/
39369SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
39370  struct RowSetChunk *pChunk, *pNextChunk;
39371  for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
39372    pNextChunk = pChunk->pNextChunk;
39373    sqlite3DbFree(p->db, pChunk);
39374  }
39375  p->pChunk = 0;
39376  p->nFresh = 0;
39377  p->pEntry = 0;
39378  p->pLast = 0;
39379  p->pForest = 0;
39380  p->rsFlags = ROWSET_SORTED;
39381}
39382
39383/*
39384** Allocate a new RowSetEntry object that is associated with the
39385** given RowSet.  Return a pointer to the new and completely uninitialized
39386** objected.
39387**
39388** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
39389** routine returns NULL.
39390*/
39391static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
39392  assert( p!=0 );
39393  if( p->nFresh==0 ){
39394    struct RowSetChunk *pNew;
39395    pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
39396    if( pNew==0 ){
39397      return 0;
39398    }
39399    pNew->pNextChunk = p->pChunk;
39400    p->pChunk = pNew;
39401    p->pFresh = pNew->aEntry;
39402    p->nFresh = ROWSET_ENTRY_PER_CHUNK;
39403  }
39404  p->nFresh--;
39405  return p->pFresh++;
39406}
39407
39408/*
39409** Insert a new value into a RowSet.
39410**
39411** The mallocFailed flag of the database connection is set if a
39412** memory allocation fails.
39413*/
39414SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
39415  struct RowSetEntry *pEntry;  /* The new entry */
39416  struct RowSetEntry *pLast;   /* The last prior entry */
39417
39418  /* This routine is never called after sqlite3RowSetNext() */
39419  assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
39420
39421  pEntry = rowSetEntryAlloc(p);
39422  if( pEntry==0 ) return;
39423  pEntry->v = rowid;
39424  pEntry->pRight = 0;
39425  pLast = p->pLast;
39426  if( pLast ){
39427    if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
39428      p->rsFlags &= ~ROWSET_SORTED;
39429    }
39430    pLast->pRight = pEntry;
39431  }else{
39432    p->pEntry = pEntry;
39433  }
39434  p->pLast = pEntry;
39435}
39436
39437/*
39438** Merge two lists of RowSetEntry objects.  Remove duplicates.
39439**
39440** The input lists are connected via pRight pointers and are
39441** assumed to each already be in sorted order.
39442*/
39443static struct RowSetEntry *rowSetEntryMerge(
39444  struct RowSetEntry *pA,    /* First sorted list to be merged */
39445  struct RowSetEntry *pB     /* Second sorted list to be merged */
39446){
39447  struct RowSetEntry head;
39448  struct RowSetEntry *pTail;
39449
39450  pTail = &head;
39451  while( pA && pB ){
39452    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
39453    assert( pB->pRight==0 || pB->v<=pB->pRight->v );
39454    if( pA->v<pB->v ){
39455      pTail->pRight = pA;
39456      pA = pA->pRight;
39457      pTail = pTail->pRight;
39458    }else if( pB->v<pA->v ){
39459      pTail->pRight = pB;
39460      pB = pB->pRight;
39461      pTail = pTail->pRight;
39462    }else{
39463      pA = pA->pRight;
39464    }
39465  }
39466  if( pA ){
39467    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
39468    pTail->pRight = pA;
39469  }else{
39470    assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
39471    pTail->pRight = pB;
39472  }
39473  return head.pRight;
39474}
39475
39476/*
39477** Sort all elements on the list of RowSetEntry objects into order of
39478** increasing v.
39479*/
39480static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
39481  unsigned int i;
39482  struct RowSetEntry *pNext, *aBucket[40];
39483
39484  memset(aBucket, 0, sizeof(aBucket));
39485  while( pIn ){
39486    pNext = pIn->pRight;
39487    pIn->pRight = 0;
39488    for(i=0; aBucket[i]; i++){
39489      pIn = rowSetEntryMerge(aBucket[i], pIn);
39490      aBucket[i] = 0;
39491    }
39492    aBucket[i] = pIn;
39493    pIn = pNext;
39494  }
39495  pIn = 0;
39496  for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
39497    pIn = rowSetEntryMerge(pIn, aBucket[i]);
39498  }
39499  return pIn;
39500}
39501
39502
39503/*
39504** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
39505** Convert this tree into a linked list connected by the pRight pointers
39506** and return pointers to the first and last elements of the new list.
39507*/
39508static void rowSetTreeToList(
39509  struct RowSetEntry *pIn,         /* Root of the input tree */
39510  struct RowSetEntry **ppFirst,    /* Write head of the output list here */
39511  struct RowSetEntry **ppLast      /* Write tail of the output list here */
39512){
39513  assert( pIn!=0 );
39514  if( pIn->pLeft ){
39515    struct RowSetEntry *p;
39516    rowSetTreeToList(pIn->pLeft, ppFirst, &p);
39517    p->pRight = pIn;
39518  }else{
39519    *ppFirst = pIn;
39520  }
39521  if( pIn->pRight ){
39522    rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
39523  }else{
39524    *ppLast = pIn;
39525  }
39526  assert( (*ppLast)->pRight==0 );
39527}
39528
39529
39530/*
39531** Convert a sorted list of elements (connected by pRight) into a binary
39532** tree with depth of iDepth.  A depth of 1 means the tree contains a single
39533** node taken from the head of *ppList.  A depth of 2 means a tree with
39534** three nodes.  And so forth.
39535**
39536** Use as many entries from the input list as required and update the
39537** *ppList to point to the unused elements of the list.  If the input
39538** list contains too few elements, then construct an incomplete tree
39539** and leave *ppList set to NULL.
39540**
39541** Return a pointer to the root of the constructed binary tree.
39542*/
39543static struct RowSetEntry *rowSetNDeepTree(
39544  struct RowSetEntry **ppList,
39545  int iDepth
39546){
39547  struct RowSetEntry *p;         /* Root of the new tree */
39548  struct RowSetEntry *pLeft;     /* Left subtree */
39549  if( *ppList==0 ){
39550    return 0;
39551  }
39552  if( iDepth==1 ){
39553    p = *ppList;
39554    *ppList = p->pRight;
39555    p->pLeft = p->pRight = 0;
39556    return p;
39557  }
39558  pLeft = rowSetNDeepTree(ppList, iDepth-1);
39559  p = *ppList;
39560  if( p==0 ){
39561    return pLeft;
39562  }
39563  p->pLeft = pLeft;
39564  *ppList = p->pRight;
39565  p->pRight = rowSetNDeepTree(ppList, iDepth-1);
39566  return p;
39567}
39568
39569/*
39570** Convert a sorted list of elements into a binary tree. Make the tree
39571** as deep as it needs to be in order to contain the entire list.
39572*/
39573static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
39574  int iDepth;           /* Depth of the tree so far */
39575  struct RowSetEntry *p;       /* Current tree root */
39576  struct RowSetEntry *pLeft;   /* Left subtree */
39577
39578  assert( pList!=0 );
39579  p = pList;
39580  pList = p->pRight;
39581  p->pLeft = p->pRight = 0;
39582  for(iDepth=1; pList; iDepth++){
39583    pLeft = p;
39584    p = pList;
39585    pList = p->pRight;
39586    p->pLeft = pLeft;
39587    p->pRight = rowSetNDeepTree(&pList, iDepth);
39588  }
39589  return p;
39590}
39591
39592/*
39593** Take all the entries on p->pEntry and on the trees in p->pForest and
39594** sort them all together into one big ordered list on p->pEntry.
39595**
39596** This routine should only be called once in the life of a RowSet.
39597*/
39598static void rowSetToList(RowSet *p){
39599
39600  /* This routine is called only once */
39601  assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
39602
39603  if( (p->rsFlags & ROWSET_SORTED)==0 ){
39604    p->pEntry = rowSetEntrySort(p->pEntry);
39605  }
39606
39607  /* While this module could theoretically support it, sqlite3RowSetNext()
39608  ** is never called after sqlite3RowSetText() for the same RowSet.  So
39609  ** there is never a forest to deal with.  Should this change, simply
39610  ** remove the assert() and the #if 0. */
39611  assert( p->pForest==0 );
39612#if 0
39613  while( p->pForest ){
39614    struct RowSetEntry *pTree = p->pForest->pLeft;
39615    if( pTree ){
39616      struct RowSetEntry *pHead, *pTail;
39617      rowSetTreeToList(pTree, &pHead, &pTail);
39618      p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
39619    }
39620    p->pForest = p->pForest->pRight;
39621  }
39622#endif
39623  p->rsFlags |= ROWSET_NEXT;  /* Verify this routine is never called again */
39624}
39625
39626/*
39627** Extract the smallest element from the RowSet.
39628** Write the element into *pRowid.  Return 1 on success.  Return
39629** 0 if the RowSet is already empty.
39630**
39631** After this routine has been called, the sqlite3RowSetInsert()
39632** routine may not be called again.
39633*/
39634SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
39635  assert( p!=0 );
39636
39637  /* Merge the forest into a single sorted list on first call */
39638  if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
39639
39640  /* Return the next entry on the list */
39641  if( p->pEntry ){
39642    *pRowid = p->pEntry->v;
39643    p->pEntry = p->pEntry->pRight;
39644    if( p->pEntry==0 ){
39645      sqlite3RowSetClear(p);
39646    }
39647    return 1;
39648  }else{
39649    return 0;
39650  }
39651}
39652
39653/*
39654** Check to see if element iRowid was inserted into the rowset as
39655** part of any insert batch prior to iBatch.  Return 1 or 0.
39656**
39657** If this is the first test of a new batch and if there exist entires
39658** on pRowSet->pEntry, then sort those entires into the forest at
39659** pRowSet->pForest so that they can be tested.
39660*/
39661SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
39662  struct RowSetEntry *p, *pTree;
39663
39664  /* This routine is never called after sqlite3RowSetNext() */
39665  assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
39666
39667  /* Sort entries into the forest on the first test of a new batch
39668  */
39669  if( iBatch!=pRowSet->iBatch ){
39670    p = pRowSet->pEntry;
39671    if( p ){
39672      struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
39673      if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
39674        p = rowSetEntrySort(p);
39675      }
39676      for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
39677        ppPrevTree = &pTree->pRight;
39678        if( pTree->pLeft==0 ){
39679          pTree->pLeft = rowSetListToTree(p);
39680          break;
39681        }else{
39682          struct RowSetEntry *pAux, *pTail;
39683          rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
39684          pTree->pLeft = 0;
39685          p = rowSetEntryMerge(pAux, p);
39686        }
39687      }
39688      if( pTree==0 ){
39689        *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
39690        if( pTree ){
39691          pTree->v = 0;
39692          pTree->pRight = 0;
39693          pTree->pLeft = rowSetListToTree(p);
39694        }
39695      }
39696      pRowSet->pEntry = 0;
39697      pRowSet->pLast = 0;
39698      pRowSet->rsFlags |= ROWSET_SORTED;
39699    }
39700    pRowSet->iBatch = iBatch;
39701  }
39702
39703  /* Test to see if the iRowid value appears anywhere in the forest.
39704  ** Return 1 if it does and 0 if not.
39705  */
39706  for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
39707    p = pTree->pLeft;
39708    while( p ){
39709      if( p->v<iRowid ){
39710        p = p->pRight;
39711      }else if( p->v>iRowid ){
39712        p = p->pLeft;
39713      }else{
39714        return 1;
39715      }
39716    }
39717  }
39718  return 0;
39719}
39720
39721/************** End of rowset.c **********************************************/
39722/************** Begin file pager.c *******************************************/
39723/*
39724** 2001 September 15
39725**
39726** The author disclaims copyright to this source code.  In place of
39727** a legal notice, here is a blessing:
39728**
39729**    May you do good and not evil.
39730**    May you find forgiveness for yourself and forgive others.
39731**    May you share freely, never taking more than you give.
39732**
39733*************************************************************************
39734** This is the implementation of the page cache subsystem or "pager".
39735**
39736** The pager is used to access a database disk file.  It implements
39737** atomic commit and rollback through the use of a journal file that
39738** is separate from the database file.  The pager also implements file
39739** locking to prevent two processes from writing the same database
39740** file simultaneously, or one process from reading the database while
39741** another is writing.
39742*/
39743#ifndef SQLITE_OMIT_DISKIO
39744/************** Include wal.h in the middle of pager.c ***********************/
39745/************** Begin file wal.h *********************************************/
39746/*
39747** 2010 February 1
39748**
39749** The author disclaims copyright to this source code.  In place of
39750** a legal notice, here is a blessing:
39751**
39752**    May you do good and not evil.
39753**    May you find forgiveness for yourself and forgive others.
39754**    May you share freely, never taking more than you give.
39755**
39756*************************************************************************
39757** This header file defines the interface to the write-ahead logging
39758** system. Refer to the comments below and the header comment attached to
39759** the implementation of each function in log.c for further details.
39760*/
39761
39762#ifndef _WAL_H_
39763#define _WAL_H_
39764
39765
39766/* Additional values that can be added to the sync_flags argument of
39767** sqlite3WalFrames():
39768*/
39769#define WAL_SYNC_TRANSACTIONS  0x20   /* Sync at the end of each transaction */
39770#define SQLITE_SYNC_MASK       0x13   /* Mask off the SQLITE_SYNC_* values */
39771
39772#ifdef SQLITE_OMIT_WAL
39773# define sqlite3WalOpen(x,y,z)                   0
39774# define sqlite3WalLimit(x,y)
39775# define sqlite3WalClose(w,x,y,z)                0
39776# define sqlite3WalBeginReadTransaction(y,z)     0
39777# define sqlite3WalEndReadTransaction(z)
39778# define sqlite3WalDbsize(y)                     0
39779# define sqlite3WalBeginWriteTransaction(y)      0
39780# define sqlite3WalEndWriteTransaction(x)        0
39781# define sqlite3WalUndo(x,y,z)                   0
39782# define sqlite3WalSavepoint(y,z)
39783# define sqlite3WalSavepointUndo(y,z)            0
39784# define sqlite3WalFrames(u,v,w,x,y,z)           0
39785# define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
39786# define sqlite3WalCallback(z)                   0
39787# define sqlite3WalExclusiveMode(y,z)            0
39788# define sqlite3WalHeapMemory(z)                 0
39789# define sqlite3WalFramesize(z)                  0
39790# define sqlite3WalFindFrame(x,y,z)              0
39791#else
39792
39793#define WAL_SAVEPOINT_NDATA 4
39794
39795/* Connection to a write-ahead log (WAL) file.
39796** There is one object of this type for each pager.
39797*/
39798typedef struct Wal Wal;
39799
39800/* Open and close a connection to a write-ahead log. */
39801SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
39802SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
39803
39804/* Set the limiting size of a WAL file. */
39805SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
39806
39807/* Used by readers to open (lock) and close (unlock) a snapshot.  A
39808** snapshot is like a read-transaction.  It is the state of the database
39809** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
39810** preserves the current state even if the other threads or processes
39811** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
39812** transaction and releases the lock.
39813*/
39814SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
39815SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
39816
39817/* Read a page from the write-ahead log, if it is present. */
39818SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
39819SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
39820
39821/* If the WAL is not empty, return the size of the database. */
39822SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
39823
39824/* Obtain or release the WRITER lock. */
39825SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
39826SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
39827
39828/* Undo any frames written (but not committed) to the log */
39829SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
39830
39831/* Return an integer that records the current (uncommitted) write
39832** position in the WAL */
39833SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
39834
39835/* Move the write position of the WAL back to iFrame.  Called in
39836** response to a ROLLBACK TO command. */
39837SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
39838
39839/* Write a frame or frames to the log. */
39840SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
39841
39842/* Copy pages from the log to the database file */
39843SQLITE_PRIVATE int sqlite3WalCheckpoint(
39844  Wal *pWal,                      /* Write-ahead log connection */
39845  int eMode,                      /* One of PASSIVE, FULL and RESTART */
39846  int (*xBusy)(void*),            /* Function to call when busy */
39847  void *pBusyArg,                 /* Context argument for xBusyHandler */
39848  int sync_flags,                 /* Flags to sync db file with (or 0) */
39849  int nBuf,                       /* Size of buffer nBuf */
39850  u8 *zBuf,                       /* Temporary buffer to use */
39851  int *pnLog,                     /* OUT: Number of frames in WAL */
39852  int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
39853);
39854
39855/* Return the value to pass to a sqlite3_wal_hook callback, the
39856** number of frames in the WAL at the point of the last commit since
39857** sqlite3WalCallback() was called.  If no commits have occurred since
39858** the last call, then return 0.
39859*/
39860SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
39861
39862/* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
39863** by the pager layer on the database file.
39864*/
39865SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
39866
39867/* Return true if the argument is non-NULL and the WAL module is using
39868** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
39869** WAL module is using shared-memory, return false.
39870*/
39871SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
39872
39873#ifdef SQLITE_ENABLE_ZIPVFS
39874/* If the WAL file is not empty, return the number of bytes of content
39875** stored in each frame (i.e. the db page-size when the WAL was created).
39876*/
39877SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
39878#endif
39879
39880#endif /* ifndef SQLITE_OMIT_WAL */
39881#endif /* _WAL_H_ */
39882
39883/************** End of wal.h *************************************************/
39884/************** Continuing where we left off in pager.c **********************/
39885
39886
39887/******************* NOTES ON THE DESIGN OF THE PAGER ************************
39888**
39889** This comment block describes invariants that hold when using a rollback
39890** journal.  These invariants do not apply for journal_mode=WAL,
39891** journal_mode=MEMORY, or journal_mode=OFF.
39892**
39893** Within this comment block, a page is deemed to have been synced
39894** automatically as soon as it is written when PRAGMA synchronous=OFF.
39895** Otherwise, the page is not synced until the xSync method of the VFS
39896** is called successfully on the file containing the page.
39897**
39898** Definition:  A page of the database file is said to be "overwriteable" if
39899** one or more of the following are true about the page:
39900**
39901**     (a)  The original content of the page as it was at the beginning of
39902**          the transaction has been written into the rollback journal and
39903**          synced.
39904**
39905**     (b)  The page was a freelist leaf page at the start of the transaction.
39906**
39907**     (c)  The page number is greater than the largest page that existed in
39908**          the database file at the start of the transaction.
39909**
39910** (1) A page of the database file is never overwritten unless one of the
39911**     following are true:
39912**
39913**     (a) The page and all other pages on the same sector are overwriteable.
39914**
39915**     (b) The atomic page write optimization is enabled, and the entire
39916**         transaction other than the update of the transaction sequence
39917**         number consists of a single page change.
39918**
39919** (2) The content of a page written into the rollback journal exactly matches
39920**     both the content in the database when the rollback journal was written
39921**     and the content in the database at the beginning of the current
39922**     transaction.
39923**
39924** (3) Writes to the database file are an integer multiple of the page size
39925**     in length and are aligned on a page boundary.
39926**
39927** (4) Reads from the database file are either aligned on a page boundary and
39928**     an integer multiple of the page size in length or are taken from the
39929**     first 100 bytes of the database file.
39930**
39931** (5) All writes to the database file are synced prior to the rollback journal
39932**     being deleted, truncated, or zeroed.
39933**
39934** (6) If a master journal file is used, then all writes to the database file
39935**     are synced prior to the master journal being deleted.
39936**
39937** Definition: Two databases (or the same database at two points it time)
39938** are said to be "logically equivalent" if they give the same answer to
39939** all queries.  Note in particular the content of freelist leaf
39940** pages can be changed arbitarily without effecting the logical equivalence
39941** of the database.
39942**
39943** (7) At any time, if any subset, including the empty set and the total set,
39944**     of the unsynced changes to a rollback journal are removed and the
39945**     journal is rolled back, the resulting database file will be logical
39946**     equivalent to the database file at the beginning of the transaction.
39947**
39948** (8) When a transaction is rolled back, the xTruncate method of the VFS
39949**     is called to restore the database file to the same size it was at
39950**     the beginning of the transaction.  (In some VFSes, the xTruncate
39951**     method is a no-op, but that does not change the fact the SQLite will
39952**     invoke it.)
39953**
39954** (9) Whenever the database file is modified, at least one bit in the range
39955**     of bytes from 24 through 39 inclusive will be changed prior to releasing
39956**     the EXCLUSIVE lock, thus signaling other connections on the same
39957**     database to flush their caches.
39958**
39959** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
39960**      than one billion transactions.
39961**
39962** (11) A database file is well-formed at the beginning and at the conclusion
39963**      of every transaction.
39964**
39965** (12) An EXCLUSIVE lock is held on the database file when writing to
39966**      the database file.
39967**
39968** (13) A SHARED lock is held on the database file while reading any
39969**      content out of the database file.
39970**
39971******************************************************************************/
39972
39973/*
39974** Macros for troubleshooting.  Normally turned off
39975*/
39976#if 0
39977int sqlite3PagerTrace=1;  /* True to enable tracing */
39978#define sqlite3DebugPrintf printf
39979#define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
39980#else
39981#define PAGERTRACE(X)
39982#endif
39983
39984/*
39985** The following two macros are used within the PAGERTRACE() macros above
39986** to print out file-descriptors.
39987**
39988** PAGERID() takes a pointer to a Pager struct as its argument. The
39989** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
39990** struct as its argument.
39991*/
39992#define PAGERID(p) ((int)(p->fd))
39993#define FILEHANDLEID(fd) ((int)fd)
39994
39995/*
39996** The Pager.eState variable stores the current 'state' of a pager. A
39997** pager may be in any one of the seven states shown in the following
39998** state diagram.
39999**
40000**                            OPEN <------+------+
40001**                              |         |      |
40002**                              V         |      |
40003**               +---------> READER-------+      |
40004**               |              |                |
40005**               |              V                |
40006**               |<-------WRITER_LOCKED------> ERROR
40007**               |              |                ^
40008**               |              V                |
40009**               |<------WRITER_CACHEMOD-------->|
40010**               |              |                |
40011**               |              V                |
40012**               |<-------WRITER_DBMOD---------->|
40013**               |              |                |
40014**               |              V                |
40015**               +<------WRITER_FINISHED-------->+
40016**
40017**
40018** List of state transitions and the C [function] that performs each:
40019**
40020**   OPEN              -> READER              [sqlite3PagerSharedLock]
40021**   READER            -> OPEN                [pager_unlock]
40022**
40023**   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
40024**   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
40025**   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
40026**   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
40027**   WRITER_***        -> READER              [pager_end_transaction]
40028**
40029**   WRITER_***        -> ERROR               [pager_error]
40030**   ERROR             -> OPEN                [pager_unlock]
40031**
40032**
40033**  OPEN:
40034**
40035**    The pager starts up in this state. Nothing is guaranteed in this
40036**    state - the file may or may not be locked and the database size is
40037**    unknown. The database may not be read or written.
40038**
40039**    * No read or write transaction is active.
40040**    * Any lock, or no lock at all, may be held on the database file.
40041**    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
40042**
40043**  READER:
40044**
40045**    In this state all the requirements for reading the database in
40046**    rollback (non-WAL) mode are met. Unless the pager is (or recently
40047**    was) in exclusive-locking mode, a user-level read transaction is
40048**    open. The database size is known in this state.
40049**
40050**    A connection running with locking_mode=normal enters this state when
40051**    it opens a read-transaction on the database and returns to state
40052**    OPEN after the read-transaction is completed. However a connection
40053**    running in locking_mode=exclusive (including temp databases) remains in
40054**    this state even after the read-transaction is closed. The only way
40055**    a locking_mode=exclusive connection can transition from READER to OPEN
40056**    is via the ERROR state (see below).
40057**
40058**    * A read transaction may be active (but a write-transaction cannot).
40059**    * A SHARED or greater lock is held on the database file.
40060**    * The dbSize variable may be trusted (even if a user-level read
40061**      transaction is not active). The dbOrigSize and dbFileSize variables
40062**      may not be trusted at this point.
40063**    * If the database is a WAL database, then the WAL connection is open.
40064**    * Even if a read-transaction is not open, it is guaranteed that
40065**      there is no hot-journal in the file-system.
40066**
40067**  WRITER_LOCKED:
40068**
40069**    The pager moves to this state from READER when a write-transaction
40070**    is first opened on the database. In WRITER_LOCKED state, all locks
40071**    required to start a write-transaction are held, but no actual
40072**    modifications to the cache or database have taken place.
40073**
40074**    In rollback mode, a RESERVED or (if the transaction was opened with
40075**    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
40076**    moving to this state, but the journal file is not written to or opened
40077**    to in this state. If the transaction is committed or rolled back while
40078**    in WRITER_LOCKED state, all that is required is to unlock the database
40079**    file.
40080**
40081**    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
40082**    If the connection is running with locking_mode=exclusive, an attempt
40083**    is made to obtain an EXCLUSIVE lock on the database file.
40084**
40085**    * A write transaction is active.
40086**    * If the connection is open in rollback-mode, a RESERVED or greater
40087**      lock is held on the database file.
40088**    * If the connection is open in WAL-mode, a WAL write transaction
40089**      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
40090**      called).
40091**    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
40092**    * The contents of the pager cache have not been modified.
40093**    * The journal file may or may not be open.
40094**    * Nothing (not even the first header) has been written to the journal.
40095**
40096**  WRITER_CACHEMOD:
40097**
40098**    A pager moves from WRITER_LOCKED state to this state when a page is
40099**    first modified by the upper layer. In rollback mode the journal file
40100**    is opened (if it is not already open) and a header written to the
40101**    start of it. The database file on disk has not been modified.
40102**
40103**    * A write transaction is active.
40104**    * A RESERVED or greater lock is held on the database file.
40105**    * The journal file is open and the first header has been written
40106**      to it, but the header has not been synced to disk.
40107**    * The contents of the page cache have been modified.
40108**
40109**  WRITER_DBMOD:
40110**
40111**    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
40112**    when it modifies the contents of the database file. WAL connections
40113**    never enter this state (since they do not modify the database file,
40114**    just the log file).
40115**
40116**    * A write transaction is active.
40117**    * An EXCLUSIVE or greater lock is held on the database file.
40118**    * The journal file is open and the first header has been written
40119**      and synced to disk.
40120**    * The contents of the page cache have been modified (and possibly
40121**      written to disk).
40122**
40123**  WRITER_FINISHED:
40124**
40125**    It is not possible for a WAL connection to enter this state.
40126**
40127**    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
40128**    state after the entire transaction has been successfully written into the
40129**    database file. In this state the transaction may be committed simply
40130**    by finalizing the journal file. Once in WRITER_FINISHED state, it is
40131**    not possible to modify the database further. At this point, the upper
40132**    layer must either commit or rollback the transaction.
40133**
40134**    * A write transaction is active.
40135**    * An EXCLUSIVE or greater lock is held on the database file.
40136**    * All writing and syncing of journal and database data has finished.
40137**      If no error occurred, all that remains is to finalize the journal to
40138**      commit the transaction. If an error did occur, the caller will need
40139**      to rollback the transaction.
40140**
40141**  ERROR:
40142**
40143**    The ERROR state is entered when an IO or disk-full error (including
40144**    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
40145**    difficult to be sure that the in-memory pager state (cache contents,
40146**    db size etc.) are consistent with the contents of the file-system.
40147**
40148**    Temporary pager files may enter the ERROR state, but in-memory pagers
40149**    cannot.
40150**
40151**    For example, if an IO error occurs while performing a rollback,
40152**    the contents of the page-cache may be left in an inconsistent state.
40153**    At this point it would be dangerous to change back to READER state
40154**    (as usually happens after a rollback). Any subsequent readers might
40155**    report database corruption (due to the inconsistent cache), and if
40156**    they upgrade to writers, they may inadvertently corrupt the database
40157**    file. To avoid this hazard, the pager switches into the ERROR state
40158**    instead of READER following such an error.
40159**
40160**    Once it has entered the ERROR state, any attempt to use the pager
40161**    to read or write data returns an error. Eventually, once all
40162**    outstanding transactions have been abandoned, the pager is able to
40163**    transition back to OPEN state, discarding the contents of the
40164**    page-cache and any other in-memory state at the same time. Everything
40165**    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
40166**    when a read-transaction is next opened on the pager (transitioning
40167**    the pager into READER state). At that point the system has recovered
40168**    from the error.
40169**
40170**    Specifically, the pager jumps into the ERROR state if:
40171**
40172**      1. An error occurs while attempting a rollback. This happens in
40173**         function sqlite3PagerRollback().
40174**
40175**      2. An error occurs while attempting to finalize a journal file
40176**         following a commit in function sqlite3PagerCommitPhaseTwo().
40177**
40178**      3. An error occurs while attempting to write to the journal or
40179**         database file in function pagerStress() in order to free up
40180**         memory.
40181**
40182**    In other cases, the error is returned to the b-tree layer. The b-tree
40183**    layer then attempts a rollback operation. If the error condition
40184**    persists, the pager enters the ERROR state via condition (1) above.
40185**
40186**    Condition (3) is necessary because it can be triggered by a read-only
40187**    statement executed within a transaction. In this case, if the error
40188**    code were simply returned to the user, the b-tree layer would not
40189**    automatically attempt a rollback, as it assumes that an error in a
40190**    read-only statement cannot leave the pager in an internally inconsistent
40191**    state.
40192**
40193**    * The Pager.errCode variable is set to something other than SQLITE_OK.
40194**    * There are one or more outstanding references to pages (after the
40195**      last reference is dropped the pager should move back to OPEN state).
40196**    * The pager is not an in-memory pager.
40197**
40198**
40199** Notes:
40200**
40201**   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
40202**     connection is open in WAL mode. A WAL connection is always in one
40203**     of the first four states.
40204**
40205**   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
40206**     state. There are two exceptions: immediately after exclusive-mode has
40207**     been turned on (and before any read or write transactions are
40208**     executed), and when the pager is leaving the "error state".
40209**
40210**   * See also: assert_pager_state().
40211*/
40212#define PAGER_OPEN                  0
40213#define PAGER_READER                1
40214#define PAGER_WRITER_LOCKED         2
40215#define PAGER_WRITER_CACHEMOD       3
40216#define PAGER_WRITER_DBMOD          4
40217#define PAGER_WRITER_FINISHED       5
40218#define PAGER_ERROR                 6
40219
40220/*
40221** The Pager.eLock variable is almost always set to one of the
40222** following locking-states, according to the lock currently held on
40223** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
40224** This variable is kept up to date as locks are taken and released by
40225** the pagerLockDb() and pagerUnlockDb() wrappers.
40226**
40227** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
40228** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
40229** the operation was successful. In these circumstances pagerLockDb() and
40230** pagerUnlockDb() take a conservative approach - eLock is always updated
40231** when unlocking the file, and only updated when locking the file if the
40232** VFS call is successful. This way, the Pager.eLock variable may be set
40233** to a less exclusive (lower) value than the lock that is actually held
40234** at the system level, but it is never set to a more exclusive value.
40235**
40236** This is usually safe. If an xUnlock fails or appears to fail, there may
40237** be a few redundant xLock() calls or a lock may be held for longer than
40238** required, but nothing really goes wrong.
40239**
40240** The exception is when the database file is unlocked as the pager moves
40241** from ERROR to OPEN state. At this point there may be a hot-journal file
40242** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
40243** transition, by the same pager or any other). If the call to xUnlock()
40244** fails at this point and the pager is left holding an EXCLUSIVE lock, this
40245** can confuse the call to xCheckReservedLock() call made later as part
40246** of hot-journal detection.
40247**
40248** xCheckReservedLock() is defined as returning true "if there is a RESERVED
40249** lock held by this process or any others". So xCheckReservedLock may
40250** return true because the caller itself is holding an EXCLUSIVE lock (but
40251** doesn't know it because of a previous error in xUnlock). If this happens
40252** a hot-journal may be mistaken for a journal being created by an active
40253** transaction in another process, causing SQLite to read from the database
40254** without rolling it back.
40255**
40256** To work around this, if a call to xUnlock() fails when unlocking the
40257** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
40258** is only changed back to a real locking state after a successful call
40259** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
40260** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
40261** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
40262** lock on the database file before attempting to roll it back. See function
40263** PagerSharedLock() for more detail.
40264**
40265** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
40266** PAGER_OPEN state.
40267*/
40268#define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
40269
40270/*
40271** A macro used for invoking the codec if there is one
40272*/
40273#ifdef SQLITE_HAS_CODEC
40274# define CODEC1(P,D,N,X,E) \
40275    if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
40276# define CODEC2(P,D,N,X,E,O) \
40277    if( P->xCodec==0 ){ O=(char*)D; }else \
40278    if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
40279#else
40280# define CODEC1(P,D,N,X,E)   /* NO-OP */
40281# define CODEC2(P,D,N,X,E,O) O=(char*)D
40282#endif
40283
40284/*
40285** The maximum allowed sector size. 64KiB. If the xSectorsize() method
40286** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
40287** This could conceivably cause corruption following a power failure on
40288** such a system. This is currently an undocumented limit.
40289*/
40290#define MAX_SECTOR_SIZE 0x10000
40291
40292/*
40293** An instance of the following structure is allocated for each active
40294** savepoint and statement transaction in the system. All such structures
40295** are stored in the Pager.aSavepoint[] array, which is allocated and
40296** resized using sqlite3Realloc().
40297**
40298** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
40299** set to 0. If a journal-header is written into the main journal while
40300** the savepoint is active, then iHdrOffset is set to the byte offset
40301** immediately following the last journal record written into the main
40302** journal before the journal-header. This is required during savepoint
40303** rollback (see pagerPlaybackSavepoint()).
40304*/
40305typedef struct PagerSavepoint PagerSavepoint;
40306struct PagerSavepoint {
40307  i64 iOffset;                 /* Starting offset in main journal */
40308  i64 iHdrOffset;              /* See above */
40309  Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
40310  Pgno nOrig;                  /* Original number of pages in file */
40311  Pgno iSubRec;                /* Index of first record in sub-journal */
40312#ifndef SQLITE_OMIT_WAL
40313  u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
40314#endif
40315};
40316
40317/*
40318** Bits of the Pager.doNotSpill flag.  See further description below.
40319*/
40320#define SPILLFLAG_OFF         0x01      /* Never spill cache.  Set via pragma */
40321#define SPILLFLAG_ROLLBACK    0x02      /* Current rolling back, so do not spill */
40322#define SPILLFLAG_NOSYNC      0x04      /* Spill is ok, but do not sync */
40323
40324/*
40325** A open page cache is an instance of struct Pager. A description of
40326** some of the more important member variables follows:
40327**
40328** eState
40329**
40330**   The current 'state' of the pager object. See the comment and state
40331**   diagram above for a description of the pager state.
40332**
40333** eLock
40334**
40335**   For a real on-disk database, the current lock held on the database file -
40336**   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
40337**
40338**   For a temporary or in-memory database (neither of which require any
40339**   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
40340**   databases always have Pager.exclusiveMode==1, this tricks the pager
40341**   logic into thinking that it already has all the locks it will ever
40342**   need (and no reason to release them).
40343**
40344**   In some (obscure) circumstances, this variable may also be set to
40345**   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
40346**   details.
40347**
40348** changeCountDone
40349**
40350**   This boolean variable is used to make sure that the change-counter
40351**   (the 4-byte header field at byte offset 24 of the database file) is
40352**   not updated more often than necessary.
40353**
40354**   It is set to true when the change-counter field is updated, which
40355**   can only happen if an exclusive lock is held on the database file.
40356**   It is cleared (set to false) whenever an exclusive lock is
40357**   relinquished on the database file. Each time a transaction is committed,
40358**   The changeCountDone flag is inspected. If it is true, the work of
40359**   updating the change-counter is omitted for the current transaction.
40360**
40361**   This mechanism means that when running in exclusive mode, a connection
40362**   need only update the change-counter once, for the first transaction
40363**   committed.
40364**
40365** setMaster
40366**
40367**   When PagerCommitPhaseOne() is called to commit a transaction, it may
40368**   (or may not) specify a master-journal name to be written into the
40369**   journal file before it is synced to disk.
40370**
40371**   Whether or not a journal file contains a master-journal pointer affects
40372**   the way in which the journal file is finalized after the transaction is
40373**   committed or rolled back when running in "journal_mode=PERSIST" mode.
40374**   If a journal file does not contain a master-journal pointer, it is
40375**   finalized by overwriting the first journal header with zeroes. If
40376**   it does contain a master-journal pointer the journal file is finalized
40377**   by truncating it to zero bytes, just as if the connection were
40378**   running in "journal_mode=truncate" mode.
40379**
40380**   Journal files that contain master journal pointers cannot be finalized
40381**   simply by overwriting the first journal-header with zeroes, as the
40382**   master journal pointer could interfere with hot-journal rollback of any
40383**   subsequently interrupted transaction that reuses the journal file.
40384**
40385**   The flag is cleared as soon as the journal file is finalized (either
40386**   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
40387**   journal file from being successfully finalized, the setMaster flag
40388**   is cleared anyway (and the pager will move to ERROR state).
40389**
40390** doNotSpill
40391**
40392**   This variables control the behavior of cache-spills  (calls made by
40393**   the pcache module to the pagerStress() routine to write cached data
40394**   to the file-system in order to free up memory).
40395**
40396**   When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
40397**   writing to the database from pagerStress() is disabled altogether.
40398**   The SPILLFLAG_ROLLBACK case is done in a very obscure case that
40399**   comes up during savepoint rollback that requires the pcache module
40400**   to allocate a new page to prevent the journal file from being written
40401**   while it is being traversed by code in pager_playback().  The SPILLFLAG_OFF
40402**   case is a user preference.
40403**
40404**   If the SPILLFLAG_NOSYNC bit is set, writing to the database from pagerStress()
40405**   is permitted, but syncing the journal file is not. This flag is set
40406**   by sqlite3PagerWrite() when the file-system sector-size is larger than
40407**   the database page-size in order to prevent a journal sync from happening
40408**   in between the journalling of two pages on the same sector.
40409**
40410** subjInMemory
40411**
40412**   This is a boolean variable. If true, then any required sub-journal
40413**   is opened as an in-memory journal file. If false, then in-memory
40414**   sub-journals are only used for in-memory pager files.
40415**
40416**   This variable is updated by the upper layer each time a new
40417**   write-transaction is opened.
40418**
40419** dbSize, dbOrigSize, dbFileSize
40420**
40421**   Variable dbSize is set to the number of pages in the database file.
40422**   It is valid in PAGER_READER and higher states (all states except for
40423**   OPEN and ERROR).
40424**
40425**   dbSize is set based on the size of the database file, which may be
40426**   larger than the size of the database (the value stored at offset
40427**   28 of the database header by the btree). If the size of the file
40428**   is not an integer multiple of the page-size, the value stored in
40429**   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
40430**   Except, any file that is greater than 0 bytes in size is considered
40431**   to have at least one page. (i.e. a 1KB file with 2K page-size leads
40432**   to dbSize==1).
40433**
40434**   During a write-transaction, if pages with page-numbers greater than
40435**   dbSize are modified in the cache, dbSize is updated accordingly.
40436**   Similarly, if the database is truncated using PagerTruncateImage(),
40437**   dbSize is updated.
40438**
40439**   Variables dbOrigSize and dbFileSize are valid in states
40440**   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
40441**   variable at the start of the transaction. It is used during rollback,
40442**   and to determine whether or not pages need to be journalled before
40443**   being modified.
40444**
40445**   Throughout a write-transaction, dbFileSize contains the size of
40446**   the file on disk in pages. It is set to a copy of dbSize when the
40447**   write-transaction is first opened, and updated when VFS calls are made
40448**   to write or truncate the database file on disk.
40449**
40450**   The only reason the dbFileSize variable is required is to suppress
40451**   unnecessary calls to xTruncate() after committing a transaction. If,
40452**   when a transaction is committed, the dbFileSize variable indicates
40453**   that the database file is larger than the database image (Pager.dbSize),
40454**   pager_truncate() is called. The pager_truncate() call uses xFilesize()
40455**   to measure the database file on disk, and then truncates it if required.
40456**   dbFileSize is not used when rolling back a transaction. In this case
40457**   pager_truncate() is called unconditionally (which means there may be
40458**   a call to xFilesize() that is not strictly required). In either case,
40459**   pager_truncate() may cause the file to become smaller or larger.
40460**
40461** dbHintSize
40462**
40463**   The dbHintSize variable is used to limit the number of calls made to
40464**   the VFS xFileControl(FCNTL_SIZE_HINT) method.
40465**
40466**   dbHintSize is set to a copy of the dbSize variable when a
40467**   write-transaction is opened (at the same time as dbFileSize and
40468**   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
40469**   dbHintSize is increased to the number of pages that correspond to the
40470**   size-hint passed to the method call. See pager_write_pagelist() for
40471**   details.
40472**
40473** errCode
40474**
40475**   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
40476**   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
40477**   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
40478**   sub-codes.
40479*/
40480struct Pager {
40481  sqlite3_vfs *pVfs;          /* OS functions to use for IO */
40482  u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
40483  u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
40484  u8 useJournal;              /* Use a rollback journal on this file */
40485  u8 noSync;                  /* Do not sync the journal if true */
40486  u8 fullSync;                /* Do extra syncs of the journal for robustness */
40487  u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
40488  u8 walSyncFlags;            /* SYNC_NORMAL or SYNC_FULL for wal writes */
40489  u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
40490  u8 tempFile;                /* zFilename is a temporary or immutable file */
40491  u8 noLock;                  /* Do not lock (except in WAL mode) */
40492  u8 readOnly;                /* True for a read-only database */
40493  u8 memDb;                   /* True to inhibit all file I/O */
40494
40495  /**************************************************************************
40496  ** The following block contains those class members that change during
40497  ** routine opertion.  Class members not in this block are either fixed
40498  ** when the pager is first created or else only change when there is a
40499  ** significant mode change (such as changing the page_size, locking_mode,
40500  ** or the journal_mode).  From another view, these class members describe
40501  ** the "state" of the pager, while other class members describe the
40502  ** "configuration" of the pager.
40503  */
40504  u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
40505  u8 eLock;                   /* Current lock held on database file */
40506  u8 changeCountDone;         /* Set after incrementing the change-counter */
40507  u8 setMaster;               /* True if a m-j name has been written to jrnl */
40508  u8 doNotSpill;              /* Do not spill the cache when non-zero */
40509  u8 subjInMemory;            /* True to use in-memory sub-journals */
40510  Pgno dbSize;                /* Number of pages in the database */
40511  Pgno dbOrigSize;            /* dbSize before the current transaction */
40512  Pgno dbFileSize;            /* Number of pages in the database file */
40513  Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
40514  int errCode;                /* One of several kinds of errors */
40515  int nRec;                   /* Pages journalled since last j-header written */
40516  u32 cksumInit;              /* Quasi-random value added to every checksum */
40517  u32 nSubRec;                /* Number of records written to sub-journal */
40518  Bitvec *pInJournal;         /* One bit for each page in the database file */
40519  sqlite3_file *fd;           /* File descriptor for database */
40520  sqlite3_file *jfd;          /* File descriptor for main journal */
40521  sqlite3_file *sjfd;         /* File descriptor for sub-journal */
40522  i64 journalOff;             /* Current write offset in the journal file */
40523  i64 journalHdr;             /* Byte offset to previous journal header */
40524  sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
40525  PagerSavepoint *aSavepoint; /* Array of active savepoints */
40526  int nSavepoint;             /* Number of elements in aSavepoint[] */
40527  char dbFileVers[16];        /* Changes whenever database file changes */
40528
40529  u8 bUseFetch;               /* True to use xFetch() */
40530  int nMmapOut;               /* Number of mmap pages currently outstanding */
40531  sqlite3_int64 szMmap;       /* Desired maximum mmap size */
40532  PgHdr *pMmapFreelist;       /* List of free mmap page headers (pDirty) */
40533  /*
40534  ** End of the routinely-changing class members
40535  ***************************************************************************/
40536
40537  u16 nExtra;                 /* Add this many bytes to each in-memory page */
40538  i16 nReserve;               /* Number of unused bytes at end of each page */
40539  u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
40540  u32 sectorSize;             /* Assumed sector size during rollback */
40541  int pageSize;               /* Number of bytes in a page */
40542  Pgno mxPgno;                /* Maximum allowed size of the database */
40543  i64 journalSizeLimit;       /* Size limit for persistent journal files */
40544  char *zFilename;            /* Name of the database file */
40545  char *zJournal;             /* Name of the journal file */
40546  int (*xBusyHandler)(void*); /* Function to call when busy */
40547  void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
40548  int aStat[3];               /* Total cache hits, misses and writes */
40549#ifdef SQLITE_TEST
40550  int nRead;                  /* Database pages read */
40551#endif
40552  void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
40553#ifdef SQLITE_HAS_CODEC
40554  void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
40555  void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
40556  void (*xCodecFree)(void*);             /* Destructor for the codec */
40557  void *pCodec;               /* First argument to xCodec... methods */
40558#endif
40559  char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
40560  PCache *pPCache;            /* Pointer to page cache object */
40561#ifndef SQLITE_OMIT_WAL
40562  Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
40563  char *zWal;                 /* File name for write-ahead log */
40564#endif
40565};
40566
40567/*
40568** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
40569** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
40570** or CACHE_WRITE to sqlite3_db_status().
40571*/
40572#define PAGER_STAT_HIT   0
40573#define PAGER_STAT_MISS  1
40574#define PAGER_STAT_WRITE 2
40575
40576/*
40577** The following global variables hold counters used for
40578** testing purposes only.  These variables do not exist in
40579** a non-testing build.  These variables are not thread-safe.
40580*/
40581#ifdef SQLITE_TEST
40582SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
40583SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
40584SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
40585# define PAGER_INCR(v)  v++
40586#else
40587# define PAGER_INCR(v)
40588#endif
40589
40590
40591
40592/*
40593** Journal files begin with the following magic string.  The data
40594** was obtained from /dev/random.  It is used only as a sanity check.
40595**
40596** Since version 2.8.0, the journal format contains additional sanity
40597** checking information.  If the power fails while the journal is being
40598** written, semi-random garbage data might appear in the journal
40599** file after power is restored.  If an attempt is then made
40600** to roll the journal back, the database could be corrupted.  The additional
40601** sanity checking data is an attempt to discover the garbage in the
40602** journal and ignore it.
40603**
40604** The sanity checking information for the new journal format consists
40605** of a 32-bit checksum on each page of data.  The checksum covers both
40606** the page number and the pPager->pageSize bytes of data for the page.
40607** This cksum is initialized to a 32-bit random value that appears in the
40608** journal file right after the header.  The random initializer is important,
40609** because garbage data that appears at the end of a journal is likely
40610** data that was once in other files that have now been deleted.  If the
40611** garbage data came from an obsolete journal file, the checksums might
40612** be correct.  But by initializing the checksum to random value which
40613** is different for every journal, we minimize that risk.
40614*/
40615static const unsigned char aJournalMagic[] = {
40616  0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
40617};
40618
40619/*
40620** The size of the of each page record in the journal is given by
40621** the following macro.
40622*/
40623#define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
40624
40625/*
40626** The journal header size for this pager. This is usually the same
40627** size as a single disk sector. See also setSectorSize().
40628*/
40629#define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
40630
40631/*
40632** The macro MEMDB is true if we are dealing with an in-memory database.
40633** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
40634** the value of MEMDB will be a constant and the compiler will optimize
40635** out code that would never execute.
40636*/
40637#ifdef SQLITE_OMIT_MEMORYDB
40638# define MEMDB 0
40639#else
40640# define MEMDB pPager->memDb
40641#endif
40642
40643/*
40644** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
40645** interfaces to access the database using memory-mapped I/O.
40646*/
40647#if SQLITE_MAX_MMAP_SIZE>0
40648# define USEFETCH(x) ((x)->bUseFetch)
40649#else
40650# define USEFETCH(x) 0
40651#endif
40652
40653/*
40654** The maximum legal page number is (2^31 - 1).
40655*/
40656#define PAGER_MAX_PGNO 2147483647
40657
40658/*
40659** The argument to this macro is a file descriptor (type sqlite3_file*).
40660** Return 0 if it is not open, or non-zero (but not 1) if it is.
40661**
40662** This is so that expressions can be written as:
40663**
40664**   if( isOpen(pPager->jfd) ){ ...
40665**
40666** instead of
40667**
40668**   if( pPager->jfd->pMethods ){ ...
40669*/
40670#define isOpen(pFd) ((pFd)->pMethods)
40671
40672/*
40673** Return true if this pager uses a write-ahead log instead of the usual
40674** rollback journal. Otherwise false.
40675*/
40676#ifndef SQLITE_OMIT_WAL
40677static int pagerUseWal(Pager *pPager){
40678  return (pPager->pWal!=0);
40679}
40680#else
40681# define pagerUseWal(x) 0
40682# define pagerRollbackWal(x) 0
40683# define pagerWalFrames(v,w,x,y) 0
40684# define pagerOpenWalIfPresent(z) SQLITE_OK
40685# define pagerBeginReadTransaction(z) SQLITE_OK
40686#endif
40687
40688#ifndef NDEBUG
40689/*
40690** Usage:
40691**
40692**   assert( assert_pager_state(pPager) );
40693**
40694** This function runs many asserts to try to find inconsistencies in
40695** the internal state of the Pager object.
40696*/
40697static int assert_pager_state(Pager *p){
40698  Pager *pPager = p;
40699
40700  /* State must be valid. */
40701  assert( p->eState==PAGER_OPEN
40702       || p->eState==PAGER_READER
40703       || p->eState==PAGER_WRITER_LOCKED
40704       || p->eState==PAGER_WRITER_CACHEMOD
40705       || p->eState==PAGER_WRITER_DBMOD
40706       || p->eState==PAGER_WRITER_FINISHED
40707       || p->eState==PAGER_ERROR
40708  );
40709
40710  /* Regardless of the current state, a temp-file connection always behaves
40711  ** as if it has an exclusive lock on the database file. It never updates
40712  ** the change-counter field, so the changeCountDone flag is always set.
40713  */
40714  assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
40715  assert( p->tempFile==0 || pPager->changeCountDone );
40716
40717  /* If the useJournal flag is clear, the journal-mode must be "OFF".
40718  ** And if the journal-mode is "OFF", the journal file must not be open.
40719  */
40720  assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
40721  assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
40722
40723  /* Check that MEMDB implies noSync. And an in-memory journal. Since
40724  ** this means an in-memory pager performs no IO at all, it cannot encounter
40725  ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
40726  ** a journal file. (although the in-memory journal implementation may
40727  ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
40728  ** is therefore not possible for an in-memory pager to enter the ERROR
40729  ** state.
40730  */
40731  if( MEMDB ){
40732    assert( p->noSync );
40733    assert( p->journalMode==PAGER_JOURNALMODE_OFF
40734         || p->journalMode==PAGER_JOURNALMODE_MEMORY
40735    );
40736    assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
40737    assert( pagerUseWal(p)==0 );
40738  }
40739
40740  /* If changeCountDone is set, a RESERVED lock or greater must be held
40741  ** on the file.
40742  */
40743  assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
40744  assert( p->eLock!=PENDING_LOCK );
40745
40746  switch( p->eState ){
40747    case PAGER_OPEN:
40748      assert( !MEMDB );
40749      assert( pPager->errCode==SQLITE_OK );
40750      assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
40751      break;
40752
40753    case PAGER_READER:
40754      assert( pPager->errCode==SQLITE_OK );
40755      assert( p->eLock!=UNKNOWN_LOCK );
40756      assert( p->eLock>=SHARED_LOCK );
40757      break;
40758
40759    case PAGER_WRITER_LOCKED:
40760      assert( p->eLock!=UNKNOWN_LOCK );
40761      assert( pPager->errCode==SQLITE_OK );
40762      if( !pagerUseWal(pPager) ){
40763        assert( p->eLock>=RESERVED_LOCK );
40764      }
40765      assert( pPager->dbSize==pPager->dbOrigSize );
40766      assert( pPager->dbOrigSize==pPager->dbFileSize );
40767      assert( pPager->dbOrigSize==pPager->dbHintSize );
40768      assert( pPager->setMaster==0 );
40769      break;
40770
40771    case PAGER_WRITER_CACHEMOD:
40772      assert( p->eLock!=UNKNOWN_LOCK );
40773      assert( pPager->errCode==SQLITE_OK );
40774      if( !pagerUseWal(pPager) ){
40775        /* It is possible that if journal_mode=wal here that neither the
40776        ** journal file nor the WAL file are open. This happens during
40777        ** a rollback transaction that switches from journal_mode=off
40778        ** to journal_mode=wal.
40779        */
40780        assert( p->eLock>=RESERVED_LOCK );
40781        assert( isOpen(p->jfd)
40782             || p->journalMode==PAGER_JOURNALMODE_OFF
40783             || p->journalMode==PAGER_JOURNALMODE_WAL
40784        );
40785      }
40786      assert( pPager->dbOrigSize==pPager->dbFileSize );
40787      assert( pPager->dbOrigSize==pPager->dbHintSize );
40788      break;
40789
40790    case PAGER_WRITER_DBMOD:
40791      assert( p->eLock==EXCLUSIVE_LOCK );
40792      assert( pPager->errCode==SQLITE_OK );
40793      assert( !pagerUseWal(pPager) );
40794      assert( p->eLock>=EXCLUSIVE_LOCK );
40795      assert( isOpen(p->jfd)
40796           || p->journalMode==PAGER_JOURNALMODE_OFF
40797           || p->journalMode==PAGER_JOURNALMODE_WAL
40798      );
40799      assert( pPager->dbOrigSize<=pPager->dbHintSize );
40800      break;
40801
40802    case PAGER_WRITER_FINISHED:
40803      assert( p->eLock==EXCLUSIVE_LOCK );
40804      assert( pPager->errCode==SQLITE_OK );
40805      assert( !pagerUseWal(pPager) );
40806      assert( isOpen(p->jfd)
40807           || p->journalMode==PAGER_JOURNALMODE_OFF
40808           || p->journalMode==PAGER_JOURNALMODE_WAL
40809      );
40810      break;
40811
40812    case PAGER_ERROR:
40813      /* There must be at least one outstanding reference to the pager if
40814      ** in ERROR state. Otherwise the pager should have already dropped
40815      ** back to OPEN state.
40816      */
40817      assert( pPager->errCode!=SQLITE_OK );
40818      assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
40819      break;
40820  }
40821
40822  return 1;
40823}
40824#endif /* ifndef NDEBUG */
40825
40826#ifdef SQLITE_DEBUG
40827/*
40828** Return a pointer to a human readable string in a static buffer
40829** containing the state of the Pager object passed as an argument. This
40830** is intended to be used within debuggers. For example, as an alternative
40831** to "print *pPager" in gdb:
40832**
40833** (gdb) printf "%s", print_pager_state(pPager)
40834*/
40835static char *print_pager_state(Pager *p){
40836  static char zRet[1024];
40837
40838  sqlite3_snprintf(1024, zRet,
40839      "Filename:      %s\n"
40840      "State:         %s errCode=%d\n"
40841      "Lock:          %s\n"
40842      "Locking mode:  locking_mode=%s\n"
40843      "Journal mode:  journal_mode=%s\n"
40844      "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
40845      "Journal:       journalOff=%lld journalHdr=%lld\n"
40846      "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
40847      , p->zFilename
40848      , p->eState==PAGER_OPEN            ? "OPEN" :
40849        p->eState==PAGER_READER          ? "READER" :
40850        p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
40851        p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
40852        p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
40853        p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
40854        p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
40855      , (int)p->errCode
40856      , p->eLock==NO_LOCK         ? "NO_LOCK" :
40857        p->eLock==RESERVED_LOCK   ? "RESERVED" :
40858        p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
40859        p->eLock==SHARED_LOCK     ? "SHARED" :
40860        p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
40861      , p->exclusiveMode ? "exclusive" : "normal"
40862      , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
40863        p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
40864        p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
40865        p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
40866        p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
40867        p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
40868      , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
40869      , p->journalOff, p->journalHdr
40870      , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
40871  );
40872
40873  return zRet;
40874}
40875#endif
40876
40877/*
40878** Return true if it is necessary to write page *pPg into the sub-journal.
40879** A page needs to be written into the sub-journal if there exists one
40880** or more open savepoints for which:
40881**
40882**   * The page-number is less than or equal to PagerSavepoint.nOrig, and
40883**   * The bit corresponding to the page-number is not set in
40884**     PagerSavepoint.pInSavepoint.
40885*/
40886static int subjRequiresPage(PgHdr *pPg){
40887  Pager *pPager = pPg->pPager;
40888  PagerSavepoint *p;
40889  Pgno pgno = pPg->pgno;
40890  int i;
40891  for(i=0; i<pPager->nSavepoint; i++){
40892    p = &pPager->aSavepoint[i];
40893    if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
40894      return 1;
40895    }
40896  }
40897  return 0;
40898}
40899
40900/*
40901** Return true if the page is already in the journal file.
40902*/
40903static int pageInJournal(Pager *pPager, PgHdr *pPg){
40904  return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
40905}
40906
40907/*
40908** Read a 32-bit integer from the given file descriptor.  Store the integer
40909** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
40910** error code is something goes wrong.
40911**
40912** All values are stored on disk as big-endian.
40913*/
40914static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
40915  unsigned char ac[4];
40916  int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
40917  if( rc==SQLITE_OK ){
40918    *pRes = sqlite3Get4byte(ac);
40919  }
40920  return rc;
40921}
40922
40923/*
40924** Write a 32-bit integer into a string buffer in big-endian byte order.
40925*/
40926#define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
40927
40928
40929/*
40930** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
40931** on success or an error code is something goes wrong.
40932*/
40933static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
40934  char ac[4];
40935  put32bits(ac, val);
40936  return sqlite3OsWrite(fd, ac, 4, offset);
40937}
40938
40939/*
40940** Unlock the database file to level eLock, which must be either NO_LOCK
40941** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
40942** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
40943**
40944** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
40945** called, do not modify it. See the comment above the #define of
40946** UNKNOWN_LOCK for an explanation of this.
40947*/
40948static int pagerUnlockDb(Pager *pPager, int eLock){
40949  int rc = SQLITE_OK;
40950
40951  assert( !pPager->exclusiveMode || pPager->eLock==eLock );
40952  assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
40953  assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
40954  if( isOpen(pPager->fd) ){
40955    assert( pPager->eLock>=eLock );
40956    rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
40957    if( pPager->eLock!=UNKNOWN_LOCK ){
40958      pPager->eLock = (u8)eLock;
40959    }
40960    IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
40961  }
40962  return rc;
40963}
40964
40965/*
40966** Lock the database file to level eLock, which must be either SHARED_LOCK,
40967** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
40968** Pager.eLock variable to the new locking state.
40969**
40970** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
40971** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
40972** See the comment above the #define of UNKNOWN_LOCK for an explanation
40973** of this.
40974*/
40975static int pagerLockDb(Pager *pPager, int eLock){
40976  int rc = SQLITE_OK;
40977
40978  assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
40979  if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
40980    rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
40981    if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
40982      pPager->eLock = (u8)eLock;
40983      IOTRACE(("LOCK %p %d\n", pPager, eLock))
40984    }
40985  }
40986  return rc;
40987}
40988
40989/*
40990** This function determines whether or not the atomic-write optimization
40991** can be used with this pager. The optimization can be used if:
40992**
40993**  (a) the value returned by OsDeviceCharacteristics() indicates that
40994**      a database page may be written atomically, and
40995**  (b) the value returned by OsSectorSize() is less than or equal
40996**      to the page size.
40997**
40998** The optimization is also always enabled for temporary files. It is
40999** an error to call this function if pPager is opened on an in-memory
41000** database.
41001**
41002** If the optimization cannot be used, 0 is returned. If it can be used,
41003** then the value returned is the size of the journal file when it
41004** contains rollback data for exactly one page.
41005*/
41006#ifdef SQLITE_ENABLE_ATOMIC_WRITE
41007static int jrnlBufferSize(Pager *pPager){
41008  assert( !MEMDB );
41009  if( !pPager->tempFile ){
41010    int dc;                           /* Device characteristics */
41011    int nSector;                      /* Sector size */
41012    int szPage;                       /* Page size */
41013
41014    assert( isOpen(pPager->fd) );
41015    dc = sqlite3OsDeviceCharacteristics(pPager->fd);
41016    nSector = pPager->sectorSize;
41017    szPage = pPager->pageSize;
41018
41019    assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
41020    assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
41021    if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
41022      return 0;
41023    }
41024  }
41025
41026  return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
41027}
41028#endif
41029
41030/*
41031** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
41032** on the cache using a hash function.  This is used for testing
41033** and debugging only.
41034*/
41035#ifdef SQLITE_CHECK_PAGES
41036/*
41037** Return a 32-bit hash of the page data for pPage.
41038*/
41039static u32 pager_datahash(int nByte, unsigned char *pData){
41040  u32 hash = 0;
41041  int i;
41042  for(i=0; i<nByte; i++){
41043    hash = (hash*1039) + pData[i];
41044  }
41045  return hash;
41046}
41047static u32 pager_pagehash(PgHdr *pPage){
41048  return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
41049}
41050static void pager_set_pagehash(PgHdr *pPage){
41051  pPage->pageHash = pager_pagehash(pPage);
41052}
41053
41054/*
41055** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
41056** is defined, and NDEBUG is not defined, an assert() statement checks
41057** that the page is either dirty or still matches the calculated page-hash.
41058*/
41059#define CHECK_PAGE(x) checkPage(x)
41060static void checkPage(PgHdr *pPg){
41061  Pager *pPager = pPg->pPager;
41062  assert( pPager->eState!=PAGER_ERROR );
41063  assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
41064}
41065
41066#else
41067#define pager_datahash(X,Y)  0
41068#define pager_pagehash(X)  0
41069#define pager_set_pagehash(X)
41070#define CHECK_PAGE(x)
41071#endif  /* SQLITE_CHECK_PAGES */
41072
41073/*
41074** When this is called the journal file for pager pPager must be open.
41075** This function attempts to read a master journal file name from the
41076** end of the file and, if successful, copies it into memory supplied
41077** by the caller. See comments above writeMasterJournal() for the format
41078** used to store a master journal file name at the end of a journal file.
41079**
41080** zMaster must point to a buffer of at least nMaster bytes allocated by
41081** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
41082** enough space to write the master journal name). If the master journal
41083** name in the journal is longer than nMaster bytes (including a
41084** nul-terminator), then this is handled as if no master journal name
41085** were present in the journal.
41086**
41087** If a master journal file name is present at the end of the journal
41088** file, then it is copied into the buffer pointed to by zMaster. A
41089** nul-terminator byte is appended to the buffer following the master
41090** journal file name.
41091**
41092** If it is determined that no master journal file name is present
41093** zMaster[0] is set to 0 and SQLITE_OK returned.
41094**
41095** If an error occurs while reading from the journal file, an SQLite
41096** error code is returned.
41097*/
41098static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
41099  int rc;                    /* Return code */
41100  u32 len;                   /* Length in bytes of master journal name */
41101  i64 szJ;                   /* Total size in bytes of journal file pJrnl */
41102  u32 cksum;                 /* MJ checksum value read from journal */
41103  u32 u;                     /* Unsigned loop counter */
41104  unsigned char aMagic[8];   /* A buffer to hold the magic header */
41105  zMaster[0] = '\0';
41106
41107  if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
41108   || szJ<16
41109   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
41110   || len>=nMaster
41111   || len==0
41112   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
41113   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
41114   || memcmp(aMagic, aJournalMagic, 8)
41115   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
41116  ){
41117    return rc;
41118  }
41119
41120  /* See if the checksum matches the master journal name */
41121  for(u=0; u<len; u++){
41122    cksum -= zMaster[u];
41123  }
41124  if( cksum ){
41125    /* If the checksum doesn't add up, then one or more of the disk sectors
41126    ** containing the master journal filename is corrupted. This means
41127    ** definitely roll back, so just return SQLITE_OK and report a (nul)
41128    ** master-journal filename.
41129    */
41130    len = 0;
41131  }
41132  zMaster[len] = '\0';
41133
41134  return SQLITE_OK;
41135}
41136
41137/*
41138** Return the offset of the sector boundary at or immediately
41139** following the value in pPager->journalOff, assuming a sector
41140** size of pPager->sectorSize bytes.
41141**
41142** i.e for a sector size of 512:
41143**
41144**   Pager.journalOff          Return value
41145**   ---------------------------------------
41146**   0                         0
41147**   512                       512
41148**   100                       512
41149**   2000                      2048
41150**
41151*/
41152static i64 journalHdrOffset(Pager *pPager){
41153  i64 offset = 0;
41154  i64 c = pPager->journalOff;
41155  if( c ){
41156    offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
41157  }
41158  assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
41159  assert( offset>=c );
41160  assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
41161  return offset;
41162}
41163
41164/*
41165** The journal file must be open when this function is called.
41166**
41167** This function is a no-op if the journal file has not been written to
41168** within the current transaction (i.e. if Pager.journalOff==0).
41169**
41170** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
41171** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
41172** zero the 28-byte header at the start of the journal file. In either case,
41173** if the pager is not in no-sync mode, sync the journal file immediately
41174** after writing or truncating it.
41175**
41176** If Pager.journalSizeLimit is set to a positive, non-zero value, and
41177** following the truncation or zeroing described above the size of the
41178** journal file in bytes is larger than this value, then truncate the
41179** journal file to Pager.journalSizeLimit bytes. The journal file does
41180** not need to be synced following this operation.
41181**
41182** If an IO error occurs, abandon processing and return the IO error code.
41183** Otherwise, return SQLITE_OK.
41184*/
41185static int zeroJournalHdr(Pager *pPager, int doTruncate){
41186  int rc = SQLITE_OK;                               /* Return code */
41187  assert( isOpen(pPager->jfd) );
41188  if( pPager->journalOff ){
41189    const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
41190
41191    IOTRACE(("JZEROHDR %p\n", pPager))
41192    if( doTruncate || iLimit==0 ){
41193      rc = sqlite3OsTruncate(pPager->jfd, 0);
41194    }else{
41195      static const char zeroHdr[28] = {0};
41196      rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
41197    }
41198    if( rc==SQLITE_OK && !pPager->noSync ){
41199      rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
41200    }
41201
41202    /* At this point the transaction is committed but the write lock
41203    ** is still held on the file. If there is a size limit configured for
41204    ** the persistent journal and the journal file currently consumes more
41205    ** space than that limit allows for, truncate it now. There is no need
41206    ** to sync the file following this operation.
41207    */
41208    if( rc==SQLITE_OK && iLimit>0 ){
41209      i64 sz;
41210      rc = sqlite3OsFileSize(pPager->jfd, &sz);
41211      if( rc==SQLITE_OK && sz>iLimit ){
41212        rc = sqlite3OsTruncate(pPager->jfd, iLimit);
41213      }
41214    }
41215  }
41216  return rc;
41217}
41218
41219/*
41220** The journal file must be open when this routine is called. A journal
41221** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
41222** current location.
41223**
41224** The format for the journal header is as follows:
41225** - 8 bytes: Magic identifying journal format.
41226** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
41227** - 4 bytes: Random number used for page hash.
41228** - 4 bytes: Initial database page count.
41229** - 4 bytes: Sector size used by the process that wrote this journal.
41230** - 4 bytes: Database page size.
41231**
41232** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
41233*/
41234static int writeJournalHdr(Pager *pPager){
41235  int rc = SQLITE_OK;                 /* Return code */
41236  char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
41237  u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
41238  u32 nWrite;                         /* Bytes of header sector written */
41239  int ii;                             /* Loop counter */
41240
41241  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
41242
41243  if( nHeader>JOURNAL_HDR_SZ(pPager) ){
41244    nHeader = JOURNAL_HDR_SZ(pPager);
41245  }
41246
41247  /* If there are active savepoints and any of them were created
41248  ** since the most recent journal header was written, update the
41249  ** PagerSavepoint.iHdrOffset fields now.
41250  */
41251  for(ii=0; ii<pPager->nSavepoint; ii++){
41252    if( pPager->aSavepoint[ii].iHdrOffset==0 ){
41253      pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
41254    }
41255  }
41256
41257  pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
41258
41259  /*
41260  ** Write the nRec Field - the number of page records that follow this
41261  ** journal header. Normally, zero is written to this value at this time.
41262  ** After the records are added to the journal (and the journal synced,
41263  ** if in full-sync mode), the zero is overwritten with the true number
41264  ** of records (see syncJournal()).
41265  **
41266  ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
41267  ** reading the journal this value tells SQLite to assume that the
41268  ** rest of the journal file contains valid page records. This assumption
41269  ** is dangerous, as if a failure occurred whilst writing to the journal
41270  ** file it may contain some garbage data. There are two scenarios
41271  ** where this risk can be ignored:
41272  **
41273  **   * When the pager is in no-sync mode. Corruption can follow a
41274  **     power failure in this case anyway.
41275  **
41276  **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
41277  **     that garbage data is never appended to the journal file.
41278  */
41279  assert( isOpen(pPager->fd) || pPager->noSync );
41280  if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
41281   || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
41282  ){
41283    memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
41284    put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
41285  }else{
41286    memset(zHeader, 0, sizeof(aJournalMagic)+4);
41287  }
41288
41289  /* The random check-hash initializer */
41290  sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
41291  put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
41292  /* The initial database size */
41293  put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
41294  /* The assumed sector size for this process */
41295  put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
41296
41297  /* The page size */
41298  put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
41299
41300  /* Initializing the tail of the buffer is not necessary.  Everything
41301  ** works find if the following memset() is omitted.  But initializing
41302  ** the memory prevents valgrind from complaining, so we are willing to
41303  ** take the performance hit.
41304  */
41305  memset(&zHeader[sizeof(aJournalMagic)+20], 0,
41306         nHeader-(sizeof(aJournalMagic)+20));
41307
41308  /* In theory, it is only necessary to write the 28 bytes that the
41309  ** journal header consumes to the journal file here. Then increment the
41310  ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
41311  ** record is written to the following sector (leaving a gap in the file
41312  ** that will be implicitly filled in by the OS).
41313  **
41314  ** However it has been discovered that on some systems this pattern can
41315  ** be significantly slower than contiguously writing data to the file,
41316  ** even if that means explicitly writing data to the block of
41317  ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
41318  ** is done.
41319  **
41320  ** The loop is required here in case the sector-size is larger than the
41321  ** database page size. Since the zHeader buffer is only Pager.pageSize
41322  ** bytes in size, more than one call to sqlite3OsWrite() may be required
41323  ** to populate the entire journal header sector.
41324  */
41325  for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
41326    IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
41327    rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
41328    assert( pPager->journalHdr <= pPager->journalOff );
41329    pPager->journalOff += nHeader;
41330  }
41331
41332  return rc;
41333}
41334
41335/*
41336** The journal file must be open when this is called. A journal header file
41337** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
41338** file. The current location in the journal file is given by
41339** pPager->journalOff. See comments above function writeJournalHdr() for
41340** a description of the journal header format.
41341**
41342** If the header is read successfully, *pNRec is set to the number of
41343** page records following this header and *pDbSize is set to the size of the
41344** database before the transaction began, in pages. Also, pPager->cksumInit
41345** is set to the value read from the journal header. SQLITE_OK is returned
41346** in this case.
41347**
41348** If the journal header file appears to be corrupted, SQLITE_DONE is
41349** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
41350** cannot be read from the journal file an error code is returned.
41351*/
41352static int readJournalHdr(
41353  Pager *pPager,               /* Pager object */
41354  int isHot,
41355  i64 journalSize,             /* Size of the open journal file in bytes */
41356  u32 *pNRec,                  /* OUT: Value read from the nRec field */
41357  u32 *pDbSize                 /* OUT: Value of original database size field */
41358){
41359  int rc;                      /* Return code */
41360  unsigned char aMagic[8];     /* A buffer to hold the magic header */
41361  i64 iHdrOff;                 /* Offset of journal header being read */
41362
41363  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
41364
41365  /* Advance Pager.journalOff to the start of the next sector. If the
41366  ** journal file is too small for there to be a header stored at this
41367  ** point, return SQLITE_DONE.
41368  */
41369  pPager->journalOff = journalHdrOffset(pPager);
41370  if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
41371    return SQLITE_DONE;
41372  }
41373  iHdrOff = pPager->journalOff;
41374
41375  /* Read in the first 8 bytes of the journal header. If they do not match
41376  ** the  magic string found at the start of each journal header, return
41377  ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
41378  ** proceed.
41379  */
41380  if( isHot || iHdrOff!=pPager->journalHdr ){
41381    rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
41382    if( rc ){
41383      return rc;
41384    }
41385    if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
41386      return SQLITE_DONE;
41387    }
41388  }
41389
41390  /* Read the first three 32-bit fields of the journal header: The nRec
41391  ** field, the checksum-initializer and the database size at the start
41392  ** of the transaction. Return an error code if anything goes wrong.
41393  */
41394  if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
41395   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
41396   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
41397  ){
41398    return rc;
41399  }
41400
41401  if( pPager->journalOff==0 ){
41402    u32 iPageSize;               /* Page-size field of journal header */
41403    u32 iSectorSize;             /* Sector-size field of journal header */
41404
41405    /* Read the page-size and sector-size journal header fields. */
41406    if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
41407     || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
41408    ){
41409      return rc;
41410    }
41411
41412    /* Versions of SQLite prior to 3.5.8 set the page-size field of the
41413    ** journal header to zero. In this case, assume that the Pager.pageSize
41414    ** variable is already set to the correct page size.
41415    */
41416    if( iPageSize==0 ){
41417      iPageSize = pPager->pageSize;
41418    }
41419
41420    /* Check that the values read from the page-size and sector-size fields
41421    ** are within range. To be 'in range', both values need to be a power
41422    ** of two greater than or equal to 512 or 32, and not greater than their
41423    ** respective compile time maximum limits.
41424    */
41425    if( iPageSize<512                  || iSectorSize<32
41426     || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
41427     || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
41428    ){
41429      /* If the either the page-size or sector-size in the journal-header is
41430      ** invalid, then the process that wrote the journal-header must have
41431      ** crashed before the header was synced. In this case stop reading
41432      ** the journal file here.
41433      */
41434      return SQLITE_DONE;
41435    }
41436
41437    /* Update the page-size to match the value read from the journal.
41438    ** Use a testcase() macro to make sure that malloc failure within
41439    ** PagerSetPagesize() is tested.
41440    */
41441    rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
41442    testcase( rc!=SQLITE_OK );
41443
41444    /* Update the assumed sector-size to match the value used by
41445    ** the process that created this journal. If this journal was
41446    ** created by a process other than this one, then this routine
41447    ** is being called from within pager_playback(). The local value
41448    ** of Pager.sectorSize is restored at the end of that routine.
41449    */
41450    pPager->sectorSize = iSectorSize;
41451  }
41452
41453  pPager->journalOff += JOURNAL_HDR_SZ(pPager);
41454  return rc;
41455}
41456
41457
41458/*
41459** Write the supplied master journal name into the journal file for pager
41460** pPager at the current location. The master journal name must be the last
41461** thing written to a journal file. If the pager is in full-sync mode, the
41462** journal file descriptor is advanced to the next sector boundary before
41463** anything is written. The format is:
41464**
41465**   + 4 bytes: PAGER_MJ_PGNO.
41466**   + N bytes: Master journal filename in utf-8.
41467**   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
41468**   + 4 bytes: Master journal name checksum.
41469**   + 8 bytes: aJournalMagic[].
41470**
41471** The master journal page checksum is the sum of the bytes in the master
41472** journal name, where each byte is interpreted as a signed 8-bit integer.
41473**
41474** If zMaster is a NULL pointer (occurs for a single database transaction),
41475** this call is a no-op.
41476*/
41477static int writeMasterJournal(Pager *pPager, const char *zMaster){
41478  int rc;                          /* Return code */
41479  int nMaster;                     /* Length of string zMaster */
41480  i64 iHdrOff;                     /* Offset of header in journal file */
41481  i64 jrnlSize;                    /* Size of journal file on disk */
41482  u32 cksum = 0;                   /* Checksum of string zMaster */
41483
41484  assert( pPager->setMaster==0 );
41485  assert( !pagerUseWal(pPager) );
41486
41487  if( !zMaster
41488   || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
41489   || !isOpen(pPager->jfd)
41490  ){
41491    return SQLITE_OK;
41492  }
41493  pPager->setMaster = 1;
41494  assert( pPager->journalHdr <= pPager->journalOff );
41495
41496  /* Calculate the length in bytes and the checksum of zMaster */
41497  for(nMaster=0; zMaster[nMaster]; nMaster++){
41498    cksum += zMaster[nMaster];
41499  }
41500
41501  /* If in full-sync mode, advance to the next disk sector before writing
41502  ** the master journal name. This is in case the previous page written to
41503  ** the journal has already been synced.
41504  */
41505  if( pPager->fullSync ){
41506    pPager->journalOff = journalHdrOffset(pPager);
41507  }
41508  iHdrOff = pPager->journalOff;
41509
41510  /* Write the master journal data to the end of the journal file. If
41511  ** an error occurs, return the error code to the caller.
41512  */
41513  if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
41514   || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
41515   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
41516   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
41517   || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
41518  ){
41519    return rc;
41520  }
41521  pPager->journalOff += (nMaster+20);
41522
41523  /* If the pager is in peristent-journal mode, then the physical
41524  ** journal-file may extend past the end of the master-journal name
41525  ** and 8 bytes of magic data just written to the file. This is
41526  ** dangerous because the code to rollback a hot-journal file
41527  ** will not be able to find the master-journal name to determine
41528  ** whether or not the journal is hot.
41529  **
41530  ** Easiest thing to do in this scenario is to truncate the journal
41531  ** file to the required size.
41532  */
41533  if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
41534   && jrnlSize>pPager->journalOff
41535  ){
41536    rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
41537  }
41538  return rc;
41539}
41540
41541/*
41542** Find a page in the hash table given its page number. Return
41543** a pointer to the page or NULL if the requested page is not
41544** already in memory.
41545*/
41546static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
41547  PgHdr *p = 0;                     /* Return value */
41548
41549  /* It is not possible for a call to PcacheFetch() with createFlag==0 to
41550  ** fail, since no attempt to allocate dynamic memory will be made.
41551  */
41552  (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
41553  return p;
41554}
41555
41556/*
41557** Discard the entire contents of the in-memory page-cache.
41558*/
41559static void pager_reset(Pager *pPager){
41560  sqlite3BackupRestart(pPager->pBackup);
41561  sqlite3PcacheClear(pPager->pPCache);
41562}
41563
41564/*
41565** Free all structures in the Pager.aSavepoint[] array and set both
41566** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
41567** if it is open and the pager is not in exclusive mode.
41568*/
41569static void releaseAllSavepoints(Pager *pPager){
41570  int ii;               /* Iterator for looping through Pager.aSavepoint */
41571  for(ii=0; ii<pPager->nSavepoint; ii++){
41572    sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
41573  }
41574  if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
41575    sqlite3OsClose(pPager->sjfd);
41576  }
41577  sqlite3_free(pPager->aSavepoint);
41578  pPager->aSavepoint = 0;
41579  pPager->nSavepoint = 0;
41580  pPager->nSubRec = 0;
41581}
41582
41583/*
41584** Set the bit number pgno in the PagerSavepoint.pInSavepoint
41585** bitvecs of all open savepoints. Return SQLITE_OK if successful
41586** or SQLITE_NOMEM if a malloc failure occurs.
41587*/
41588static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
41589  int ii;                   /* Loop counter */
41590  int rc = SQLITE_OK;       /* Result code */
41591
41592  for(ii=0; ii<pPager->nSavepoint; ii++){
41593    PagerSavepoint *p = &pPager->aSavepoint[ii];
41594    if( pgno<=p->nOrig ){
41595      rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
41596      testcase( rc==SQLITE_NOMEM );
41597      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
41598    }
41599  }
41600  return rc;
41601}
41602
41603/*
41604** This function is a no-op if the pager is in exclusive mode and not
41605** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
41606** state.
41607**
41608** If the pager is not in exclusive-access mode, the database file is
41609** completely unlocked. If the file is unlocked and the file-system does
41610** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
41611** closed (if it is open).
41612**
41613** If the pager is in ERROR state when this function is called, the
41614** contents of the pager cache are discarded before switching back to
41615** the OPEN state. Regardless of whether the pager is in exclusive-mode
41616** or not, any journal file left in the file-system will be treated
41617** as a hot-journal and rolled back the next time a read-transaction
41618** is opened (by this or by any other connection).
41619*/
41620static void pager_unlock(Pager *pPager){
41621
41622  assert( pPager->eState==PAGER_READER
41623       || pPager->eState==PAGER_OPEN
41624       || pPager->eState==PAGER_ERROR
41625  );
41626
41627  sqlite3BitvecDestroy(pPager->pInJournal);
41628  pPager->pInJournal = 0;
41629  releaseAllSavepoints(pPager);
41630
41631  if( pagerUseWal(pPager) ){
41632    assert( !isOpen(pPager->jfd) );
41633    sqlite3WalEndReadTransaction(pPager->pWal);
41634    pPager->eState = PAGER_OPEN;
41635  }else if( !pPager->exclusiveMode ){
41636    int rc;                       /* Error code returned by pagerUnlockDb() */
41637    int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
41638
41639    /* If the operating system support deletion of open files, then
41640    ** close the journal file when dropping the database lock.  Otherwise
41641    ** another connection with journal_mode=delete might delete the file
41642    ** out from under us.
41643    */
41644    assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
41645    assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
41646    assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
41647    assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
41648    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
41649    assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
41650    if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
41651     || 1!=(pPager->journalMode & 5)
41652    ){
41653      sqlite3OsClose(pPager->jfd);
41654    }
41655
41656    /* If the pager is in the ERROR state and the call to unlock the database
41657    ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
41658    ** above the #define for UNKNOWN_LOCK for an explanation of why this
41659    ** is necessary.
41660    */
41661    rc = pagerUnlockDb(pPager, NO_LOCK);
41662    if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
41663      pPager->eLock = UNKNOWN_LOCK;
41664    }
41665
41666    /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
41667    ** without clearing the error code. This is intentional - the error
41668    ** code is cleared and the cache reset in the block below.
41669    */
41670    assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
41671    pPager->changeCountDone = 0;
41672    pPager->eState = PAGER_OPEN;
41673  }
41674
41675  /* If Pager.errCode is set, the contents of the pager cache cannot be
41676  ** trusted. Now that there are no outstanding references to the pager,
41677  ** it can safely move back to PAGER_OPEN state. This happens in both
41678  ** normal and exclusive-locking mode.
41679  */
41680  if( pPager->errCode ){
41681    assert( !MEMDB );
41682    pager_reset(pPager);
41683    pPager->changeCountDone = pPager->tempFile;
41684    pPager->eState = PAGER_OPEN;
41685    pPager->errCode = SQLITE_OK;
41686    if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
41687  }
41688
41689  pPager->journalOff = 0;
41690  pPager->journalHdr = 0;
41691  pPager->setMaster = 0;
41692}
41693
41694/*
41695** This function is called whenever an IOERR or FULL error that requires
41696** the pager to transition into the ERROR state may ahve occurred.
41697** The first argument is a pointer to the pager structure, the second
41698** the error-code about to be returned by a pager API function. The
41699** value returned is a copy of the second argument to this function.
41700**
41701** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
41702** IOERR sub-codes, the pager enters the ERROR state and the error code
41703** is stored in Pager.errCode. While the pager remains in the ERROR state,
41704** all major API calls on the Pager will immediately return Pager.errCode.
41705**
41706** The ERROR state indicates that the contents of the pager-cache
41707** cannot be trusted. This state can be cleared by completely discarding
41708** the contents of the pager-cache. If a transaction was active when
41709** the persistent error occurred, then the rollback journal may need
41710** to be replayed to restore the contents of the database file (as if
41711** it were a hot-journal).
41712*/
41713static int pager_error(Pager *pPager, int rc){
41714  int rc2 = rc & 0xff;
41715  assert( rc==SQLITE_OK || !MEMDB );
41716  assert(
41717       pPager->errCode==SQLITE_FULL ||
41718       pPager->errCode==SQLITE_OK ||
41719       (pPager->errCode & 0xff)==SQLITE_IOERR
41720  );
41721  if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
41722    pPager->errCode = rc;
41723    pPager->eState = PAGER_ERROR;
41724  }
41725  return rc;
41726}
41727
41728static int pager_truncate(Pager *pPager, Pgno nPage);
41729
41730/*
41731** This routine ends a transaction. A transaction is usually ended by
41732** either a COMMIT or a ROLLBACK operation. This routine may be called
41733** after rollback of a hot-journal, or if an error occurs while opening
41734** the journal file or writing the very first journal-header of a
41735** database transaction.
41736**
41737** This routine is never called in PAGER_ERROR state. If it is called
41738** in PAGER_NONE or PAGER_SHARED state and the lock held is less
41739** exclusive than a RESERVED lock, it is a no-op.
41740**
41741** Otherwise, any active savepoints are released.
41742**
41743** If the journal file is open, then it is "finalized". Once a journal
41744** file has been finalized it is not possible to use it to roll back a
41745** transaction. Nor will it be considered to be a hot-journal by this
41746** or any other database connection. Exactly how a journal is finalized
41747** depends on whether or not the pager is running in exclusive mode and
41748** the current journal-mode (Pager.journalMode value), as follows:
41749**
41750**   journalMode==MEMORY
41751**     Journal file descriptor is simply closed. This destroys an
41752**     in-memory journal.
41753**
41754**   journalMode==TRUNCATE
41755**     Journal file is truncated to zero bytes in size.
41756**
41757**   journalMode==PERSIST
41758**     The first 28 bytes of the journal file are zeroed. This invalidates
41759**     the first journal header in the file, and hence the entire journal
41760**     file. An invalid journal file cannot be rolled back.
41761**
41762**   journalMode==DELETE
41763**     The journal file is closed and deleted using sqlite3OsDelete().
41764**
41765**     If the pager is running in exclusive mode, this method of finalizing
41766**     the journal file is never used. Instead, if the journalMode is
41767**     DELETE and the pager is in exclusive mode, the method described under
41768**     journalMode==PERSIST is used instead.
41769**
41770** After the journal is finalized, the pager moves to PAGER_READER state.
41771** If running in non-exclusive rollback mode, the lock on the file is
41772** downgraded to a SHARED_LOCK.
41773**
41774** SQLITE_OK is returned if no error occurs. If an error occurs during
41775** any of the IO operations to finalize the journal file or unlock the
41776** database then the IO error code is returned to the user. If the
41777** operation to finalize the journal file fails, then the code still
41778** tries to unlock the database file if not in exclusive mode. If the
41779** unlock operation fails as well, then the first error code related
41780** to the first error encountered (the journal finalization one) is
41781** returned.
41782*/
41783static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
41784  int rc = SQLITE_OK;      /* Error code from journal finalization operation */
41785  int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
41786
41787  /* Do nothing if the pager does not have an open write transaction
41788  ** or at least a RESERVED lock. This function may be called when there
41789  ** is no write-transaction active but a RESERVED or greater lock is
41790  ** held under two circumstances:
41791  **
41792  **   1. After a successful hot-journal rollback, it is called with
41793  **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
41794  **
41795  **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
41796  **      lock switches back to locking_mode=normal and then executes a
41797  **      read-transaction, this function is called with eState==PAGER_READER
41798  **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
41799  */
41800  assert( assert_pager_state(pPager) );
41801  assert( pPager->eState!=PAGER_ERROR );
41802  if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
41803    return SQLITE_OK;
41804  }
41805
41806  releaseAllSavepoints(pPager);
41807  assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
41808  if( isOpen(pPager->jfd) ){
41809    assert( !pagerUseWal(pPager) );
41810
41811    /* Finalize the journal file. */
41812    if( sqlite3IsMemJournal(pPager->jfd) ){
41813      assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
41814      sqlite3OsClose(pPager->jfd);
41815    }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
41816      if( pPager->journalOff==0 ){
41817        rc = SQLITE_OK;
41818      }else{
41819        rc = sqlite3OsTruncate(pPager->jfd, 0);
41820      }
41821      pPager->journalOff = 0;
41822    }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
41823      || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
41824    ){
41825      rc = zeroJournalHdr(pPager, hasMaster);
41826      pPager->journalOff = 0;
41827    }else{
41828      /* This branch may be executed with Pager.journalMode==MEMORY if
41829      ** a hot-journal was just rolled back. In this case the journal
41830      ** file should be closed and deleted. If this connection writes to
41831      ** the database file, it will do so using an in-memory journal.
41832      */
41833      int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
41834      assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
41835           || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
41836           || pPager->journalMode==PAGER_JOURNALMODE_WAL
41837      );
41838      sqlite3OsClose(pPager->jfd);
41839      if( bDelete ){
41840        rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
41841      }
41842    }
41843  }
41844
41845#ifdef SQLITE_CHECK_PAGES
41846  sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
41847  if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
41848    PgHdr *p = pager_lookup(pPager, 1);
41849    if( p ){
41850      p->pageHash = 0;
41851      sqlite3PagerUnrefNotNull(p);
41852    }
41853  }
41854#endif
41855
41856  sqlite3BitvecDestroy(pPager->pInJournal);
41857  pPager->pInJournal = 0;
41858  pPager->nRec = 0;
41859  sqlite3PcacheCleanAll(pPager->pPCache);
41860  sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
41861
41862  if( pagerUseWal(pPager) ){
41863    /* Drop the WAL write-lock, if any. Also, if the connection was in
41864    ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
41865    ** lock held on the database file.
41866    */
41867    rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
41868    assert( rc2==SQLITE_OK );
41869  }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
41870    /* This branch is taken when committing a transaction in rollback-journal
41871    ** mode if the database file on disk is larger than the database image.
41872    ** At this point the journal has been finalized and the transaction
41873    ** successfully committed, but the EXCLUSIVE lock is still held on the
41874    ** file. So it is safe to truncate the database file to its minimum
41875    ** required size.  */
41876    assert( pPager->eLock==EXCLUSIVE_LOCK );
41877    rc = pager_truncate(pPager, pPager->dbSize);
41878  }
41879
41880  if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
41881    rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
41882    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
41883  }
41884
41885  if( !pPager->exclusiveMode
41886   && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
41887  ){
41888    rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
41889    pPager->changeCountDone = 0;
41890  }
41891  pPager->eState = PAGER_READER;
41892  pPager->setMaster = 0;
41893
41894  return (rc==SQLITE_OK?rc2:rc);
41895}
41896
41897/*
41898** Execute a rollback if a transaction is active and unlock the
41899** database file.
41900**
41901** If the pager has already entered the ERROR state, do not attempt
41902** the rollback at this time. Instead, pager_unlock() is called. The
41903** call to pager_unlock() will discard all in-memory pages, unlock
41904** the database file and move the pager back to OPEN state. If this
41905** means that there is a hot-journal left in the file-system, the next
41906** connection to obtain a shared lock on the pager (which may be this one)
41907** will roll it back.
41908**
41909** If the pager has not already entered the ERROR state, but an IO or
41910** malloc error occurs during a rollback, then this will itself cause
41911** the pager to enter the ERROR state. Which will be cleared by the
41912** call to pager_unlock(), as described above.
41913*/
41914static void pagerUnlockAndRollback(Pager *pPager){
41915  if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
41916    assert( assert_pager_state(pPager) );
41917    if( pPager->eState>=PAGER_WRITER_LOCKED ){
41918      sqlite3BeginBenignMalloc();
41919      sqlite3PagerRollback(pPager);
41920      sqlite3EndBenignMalloc();
41921    }else if( !pPager->exclusiveMode ){
41922      assert( pPager->eState==PAGER_READER );
41923      pager_end_transaction(pPager, 0, 0);
41924    }
41925  }
41926  pager_unlock(pPager);
41927}
41928
41929/*
41930** Parameter aData must point to a buffer of pPager->pageSize bytes
41931** of data. Compute and return a checksum based ont the contents of the
41932** page of data and the current value of pPager->cksumInit.
41933**
41934** This is not a real checksum. It is really just the sum of the
41935** random initial value (pPager->cksumInit) and every 200th byte
41936** of the page data, starting with byte offset (pPager->pageSize%200).
41937** Each byte is interpreted as an 8-bit unsigned integer.
41938**
41939** Changing the formula used to compute this checksum results in an
41940** incompatible journal file format.
41941**
41942** If journal corruption occurs due to a power failure, the most likely
41943** scenario is that one end or the other of the record will be changed.
41944** It is much less likely that the two ends of the journal record will be
41945** correct and the middle be corrupt.  Thus, this "checksum" scheme,
41946** though fast and simple, catches the mostly likely kind of corruption.
41947*/
41948static u32 pager_cksum(Pager *pPager, const u8 *aData){
41949  u32 cksum = pPager->cksumInit;         /* Checksum value to return */
41950  int i = pPager->pageSize-200;          /* Loop counter */
41951  while( i>0 ){
41952    cksum += aData[i];
41953    i -= 200;
41954  }
41955  return cksum;
41956}
41957
41958/*
41959** Report the current page size and number of reserved bytes back
41960** to the codec.
41961*/
41962#ifdef SQLITE_HAS_CODEC
41963static void pagerReportSize(Pager *pPager){
41964  if( pPager->xCodecSizeChng ){
41965    pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
41966                           (int)pPager->nReserve);
41967  }
41968}
41969#else
41970# define pagerReportSize(X)     /* No-op if we do not support a codec */
41971#endif
41972
41973/*
41974** Read a single page from either the journal file (if isMainJrnl==1) or
41975** from the sub-journal (if isMainJrnl==0) and playback that page.
41976** The page begins at offset *pOffset into the file. The *pOffset
41977** value is increased to the start of the next page in the journal.
41978**
41979** The main rollback journal uses checksums - the statement journal does
41980** not.
41981**
41982** If the page number of the page record read from the (sub-)journal file
41983** is greater than the current value of Pager.dbSize, then playback is
41984** skipped and SQLITE_OK is returned.
41985**
41986** If pDone is not NULL, then it is a record of pages that have already
41987** been played back.  If the page at *pOffset has already been played back
41988** (if the corresponding pDone bit is set) then skip the playback.
41989** Make sure the pDone bit corresponding to the *pOffset page is set
41990** prior to returning.
41991**
41992** If the page record is successfully read from the (sub-)journal file
41993** and played back, then SQLITE_OK is returned. If an IO error occurs
41994** while reading the record from the (sub-)journal file or while writing
41995** to the database file, then the IO error code is returned. If data
41996** is successfully read from the (sub-)journal file but appears to be
41997** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
41998** two circumstances:
41999**
42000**   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
42001**   * If the record is being rolled back from the main journal file
42002**     and the checksum field does not match the record content.
42003**
42004** Neither of these two scenarios are possible during a savepoint rollback.
42005**
42006** If this is a savepoint rollback, then memory may have to be dynamically
42007** allocated by this function. If this is the case and an allocation fails,
42008** SQLITE_NOMEM is returned.
42009*/
42010static int pager_playback_one_page(
42011  Pager *pPager,                /* The pager being played back */
42012  i64 *pOffset,                 /* Offset of record to playback */
42013  Bitvec *pDone,                /* Bitvec of pages already played back */
42014  int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
42015  int isSavepnt                 /* True for a savepoint rollback */
42016){
42017  int rc;
42018  PgHdr *pPg;                   /* An existing page in the cache */
42019  Pgno pgno;                    /* The page number of a page in journal */
42020  u32 cksum;                    /* Checksum used for sanity checking */
42021  char *aData;                  /* Temporary storage for the page */
42022  sqlite3_file *jfd;            /* The file descriptor for the journal file */
42023  int isSynced;                 /* True if journal page is synced */
42024
42025  assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
42026  assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
42027  assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
42028  assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
42029
42030  aData = pPager->pTmpSpace;
42031  assert( aData );         /* Temp storage must have already been allocated */
42032  assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
42033
42034  /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
42035  ** or savepoint rollback done at the request of the caller) or this is
42036  ** a hot-journal rollback. If it is a hot-journal rollback, the pager
42037  ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
42038  ** only reads from the main journal, not the sub-journal.
42039  */
42040  assert( pPager->eState>=PAGER_WRITER_CACHEMOD
42041       || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
42042  );
42043  assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
42044
42045  /* Read the page number and page data from the journal or sub-journal
42046  ** file. Return an error code to the caller if an IO error occurs.
42047  */
42048  jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
42049  rc = read32bits(jfd, *pOffset, &pgno);
42050  if( rc!=SQLITE_OK ) return rc;
42051  rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
42052  if( rc!=SQLITE_OK ) return rc;
42053  *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
42054
42055  /* Sanity checking on the page.  This is more important that I originally
42056  ** thought.  If a power failure occurs while the journal is being written,
42057  ** it could cause invalid data to be written into the journal.  We need to
42058  ** detect this invalid data (with high probability) and ignore it.
42059  */
42060  if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
42061    assert( !isSavepnt );
42062    return SQLITE_DONE;
42063  }
42064  if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
42065    return SQLITE_OK;
42066  }
42067  if( isMainJrnl ){
42068    rc = read32bits(jfd, (*pOffset)-4, &cksum);
42069    if( rc ) return rc;
42070    if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
42071      return SQLITE_DONE;
42072    }
42073  }
42074
42075  /* If this page has already been played by before during the current
42076  ** rollback, then don't bother to play it back again.
42077  */
42078  if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
42079    return rc;
42080  }
42081
42082  /* When playing back page 1, restore the nReserve setting
42083  */
42084  if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
42085    pPager->nReserve = ((u8*)aData)[20];
42086    pagerReportSize(pPager);
42087  }
42088
42089  /* If the pager is in CACHEMOD state, then there must be a copy of this
42090  ** page in the pager cache. In this case just update the pager cache,
42091  ** not the database file. The page is left marked dirty in this case.
42092  **
42093  ** An exception to the above rule: If the database is in no-sync mode
42094  ** and a page is moved during an incremental vacuum then the page may
42095  ** not be in the pager cache. Later: if a malloc() or IO error occurs
42096  ** during a Movepage() call, then the page may not be in the cache
42097  ** either. So the condition described in the above paragraph is not
42098  ** assert()able.
42099  **
42100  ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
42101  ** pager cache if it exists and the main file. The page is then marked
42102  ** not dirty. Since this code is only executed in PAGER_OPEN state for
42103  ** a hot-journal rollback, it is guaranteed that the page-cache is empty
42104  ** if the pager is in OPEN state.
42105  **
42106  ** Ticket #1171:  The statement journal might contain page content that is
42107  ** different from the page content at the start of the transaction.
42108  ** This occurs when a page is changed prior to the start of a statement
42109  ** then changed again within the statement.  When rolling back such a
42110  ** statement we must not write to the original database unless we know
42111  ** for certain that original page contents are synced into the main rollback
42112  ** journal.  Otherwise, a power loss might leave modified data in the
42113  ** database file without an entry in the rollback journal that can
42114  ** restore the database to its original form.  Two conditions must be
42115  ** met before writing to the database files. (1) the database must be
42116  ** locked.  (2) we know that the original page content is fully synced
42117  ** in the main journal either because the page is not in cache or else
42118  ** the page is marked as needSync==0.
42119  **
42120  ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
42121  ** is possible to fail a statement on a database that does not yet exist.
42122  ** Do not attempt to write if database file has never been opened.
42123  */
42124  if( pagerUseWal(pPager) ){
42125    pPg = 0;
42126  }else{
42127    pPg = pager_lookup(pPager, pgno);
42128  }
42129  assert( pPg || !MEMDB );
42130  assert( pPager->eState!=PAGER_OPEN || pPg==0 );
42131  PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
42132           PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
42133           (isMainJrnl?"main-journal":"sub-journal")
42134  ));
42135  if( isMainJrnl ){
42136    isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
42137  }else{
42138    isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
42139  }
42140  if( isOpen(pPager->fd)
42141   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
42142   && isSynced
42143  ){
42144    i64 ofst = (pgno-1)*(i64)pPager->pageSize;
42145    testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
42146    assert( !pagerUseWal(pPager) );
42147    rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
42148    if( pgno>pPager->dbFileSize ){
42149      pPager->dbFileSize = pgno;
42150    }
42151    if( pPager->pBackup ){
42152      CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
42153      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
42154      CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
42155    }
42156  }else if( !isMainJrnl && pPg==0 ){
42157    /* If this is a rollback of a savepoint and data was not written to
42158    ** the database and the page is not in-memory, there is a potential
42159    ** problem. When the page is next fetched by the b-tree layer, it
42160    ** will be read from the database file, which may or may not be
42161    ** current.
42162    **
42163    ** There are a couple of different ways this can happen. All are quite
42164    ** obscure. When running in synchronous mode, this can only happen
42165    ** if the page is on the free-list at the start of the transaction, then
42166    ** populated, then moved using sqlite3PagerMovepage().
42167    **
42168    ** The solution is to add an in-memory page to the cache containing
42169    ** the data just read from the sub-journal. Mark the page as dirty
42170    ** and if the pager requires a journal-sync, then mark the page as
42171    ** requiring a journal-sync before it is written.
42172    */
42173    assert( isSavepnt );
42174    assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
42175    pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
42176    rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
42177    assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
42178    pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
42179    if( rc!=SQLITE_OK ) return rc;
42180    pPg->flags &= ~PGHDR_NEED_READ;
42181    sqlite3PcacheMakeDirty(pPg);
42182  }
42183  if( pPg ){
42184    /* No page should ever be explicitly rolled back that is in use, except
42185    ** for page 1 which is held in use in order to keep the lock on the
42186    ** database active. However such a page may be rolled back as a result
42187    ** of an internal error resulting in an automatic call to
42188    ** sqlite3PagerRollback().
42189    */
42190    void *pData;
42191    pData = pPg->pData;
42192    memcpy(pData, (u8*)aData, pPager->pageSize);
42193    pPager->xReiniter(pPg);
42194    if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
42195      /* If the contents of this page were just restored from the main
42196      ** journal file, then its content must be as they were when the
42197      ** transaction was first opened. In this case we can mark the page
42198      ** as clean, since there will be no need to write it out to the
42199      ** database.
42200      **
42201      ** There is one exception to this rule. If the page is being rolled
42202      ** back as part of a savepoint (or statement) rollback from an
42203      ** unsynced portion of the main journal file, then it is not safe
42204      ** to mark the page as clean. This is because marking the page as
42205      ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
42206      ** already in the journal file (recorded in Pager.pInJournal) and
42207      ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
42208      ** again within this transaction, it will be marked as dirty but
42209      ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
42210      ** be written out into the database file before its journal file
42211      ** segment is synced. If a crash occurs during or following this,
42212      ** database corruption may ensue.
42213      */
42214      assert( !pagerUseWal(pPager) );
42215      sqlite3PcacheMakeClean(pPg);
42216    }
42217    pager_set_pagehash(pPg);
42218
42219    /* If this was page 1, then restore the value of Pager.dbFileVers.
42220    ** Do this before any decoding. */
42221    if( pgno==1 ){
42222      memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
42223    }
42224
42225    /* Decode the page just read from disk */
42226    CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
42227    sqlite3PcacheRelease(pPg);
42228  }
42229  return rc;
42230}
42231
42232/*
42233** Parameter zMaster is the name of a master journal file. A single journal
42234** file that referred to the master journal file has just been rolled back.
42235** This routine checks if it is possible to delete the master journal file,
42236** and does so if it is.
42237**
42238** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
42239** available for use within this function.
42240**
42241** When a master journal file is created, it is populated with the names
42242** of all of its child journals, one after another, formatted as utf-8
42243** encoded text. The end of each child journal file is marked with a
42244** nul-terminator byte (0x00). i.e. the entire contents of a master journal
42245** file for a transaction involving two databases might be:
42246**
42247**   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
42248**
42249** A master journal file may only be deleted once all of its child
42250** journals have been rolled back.
42251**
42252** This function reads the contents of the master-journal file into
42253** memory and loops through each of the child journal names. For
42254** each child journal, it checks if:
42255**
42256**   * if the child journal exists, and if so
42257**   * if the child journal contains a reference to master journal
42258**     file zMaster
42259**
42260** If a child journal can be found that matches both of the criteria
42261** above, this function returns without doing anything. Otherwise, if
42262** no such child journal can be found, file zMaster is deleted from
42263** the file-system using sqlite3OsDelete().
42264**
42265** If an IO error within this function, an error code is returned. This
42266** function allocates memory by calling sqlite3Malloc(). If an allocation
42267** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
42268** occur, SQLITE_OK is returned.
42269**
42270** TODO: This function allocates a single block of memory to load
42271** the entire contents of the master journal file. This could be
42272** a couple of kilobytes or so - potentially larger than the page
42273** size.
42274*/
42275static int pager_delmaster(Pager *pPager, const char *zMaster){
42276  sqlite3_vfs *pVfs = pPager->pVfs;
42277  int rc;                   /* Return code */
42278  sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
42279  sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
42280  char *zMasterJournal = 0; /* Contents of master journal file */
42281  i64 nMasterJournal;       /* Size of master journal file */
42282  char *zJournal;           /* Pointer to one journal within MJ file */
42283  char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
42284  int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
42285
42286  /* Allocate space for both the pJournal and pMaster file descriptors.
42287  ** If successful, open the master journal file for reading.
42288  */
42289  pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
42290  pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
42291  if( !pMaster ){
42292    rc = SQLITE_NOMEM;
42293  }else{
42294    const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
42295    rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
42296  }
42297  if( rc!=SQLITE_OK ) goto delmaster_out;
42298
42299  /* Load the entire master journal file into space obtained from
42300  ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
42301  ** sufficient space (in zMasterPtr) to hold the names of master
42302  ** journal files extracted from regular rollback-journals.
42303  */
42304  rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
42305  if( rc!=SQLITE_OK ) goto delmaster_out;
42306  nMasterPtr = pVfs->mxPathname+1;
42307  zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
42308  if( !zMasterJournal ){
42309    rc = SQLITE_NOMEM;
42310    goto delmaster_out;
42311  }
42312  zMasterPtr = &zMasterJournal[nMasterJournal+1];
42313  rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
42314  if( rc!=SQLITE_OK ) goto delmaster_out;
42315  zMasterJournal[nMasterJournal] = 0;
42316
42317  zJournal = zMasterJournal;
42318  while( (zJournal-zMasterJournal)<nMasterJournal ){
42319    int exists;
42320    rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
42321    if( rc!=SQLITE_OK ){
42322      goto delmaster_out;
42323    }
42324    if( exists ){
42325      /* One of the journals pointed to by the master journal exists.
42326      ** Open it and check if it points at the master journal. If
42327      ** so, return without deleting the master journal file.
42328      */
42329      int c;
42330      int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
42331      rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
42332      if( rc!=SQLITE_OK ){
42333        goto delmaster_out;
42334      }
42335
42336      rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
42337      sqlite3OsClose(pJournal);
42338      if( rc!=SQLITE_OK ){
42339        goto delmaster_out;
42340      }
42341
42342      c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
42343      if( c ){
42344        /* We have a match. Do not delete the master journal file. */
42345        goto delmaster_out;
42346      }
42347    }
42348    zJournal += (sqlite3Strlen30(zJournal)+1);
42349  }
42350
42351  sqlite3OsClose(pMaster);
42352  rc = sqlite3OsDelete(pVfs, zMaster, 0);
42353
42354delmaster_out:
42355  sqlite3_free(zMasterJournal);
42356  if( pMaster ){
42357    sqlite3OsClose(pMaster);
42358    assert( !isOpen(pJournal) );
42359    sqlite3_free(pMaster);
42360  }
42361  return rc;
42362}
42363
42364
42365/*
42366** This function is used to change the actual size of the database
42367** file in the file-system. This only happens when committing a transaction,
42368** or rolling back a transaction (including rolling back a hot-journal).
42369**
42370** If the main database file is not open, or the pager is not in either
42371** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
42372** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
42373** If the file on disk is currently larger than nPage pages, then use the VFS
42374** xTruncate() method to truncate it.
42375**
42376** Or, it might might be the case that the file on disk is smaller than
42377** nPage pages. Some operating system implementations can get confused if
42378** you try to truncate a file to some size that is larger than it
42379** currently is, so detect this case and write a single zero byte to
42380** the end of the new file instead.
42381**
42382** If successful, return SQLITE_OK. If an IO error occurs while modifying
42383** the database file, return the error code to the caller.
42384*/
42385static int pager_truncate(Pager *pPager, Pgno nPage){
42386  int rc = SQLITE_OK;
42387  assert( pPager->eState!=PAGER_ERROR );
42388  assert( pPager->eState!=PAGER_READER );
42389
42390  if( isOpen(pPager->fd)
42391   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
42392  ){
42393    i64 currentSize, newSize;
42394    int szPage = pPager->pageSize;
42395    assert( pPager->eLock==EXCLUSIVE_LOCK );
42396    /* TODO: Is it safe to use Pager.dbFileSize here? */
42397    rc = sqlite3OsFileSize(pPager->fd, &currentSize);
42398    newSize = szPage*(i64)nPage;
42399    if( rc==SQLITE_OK && currentSize!=newSize ){
42400      if( currentSize>newSize ){
42401        rc = sqlite3OsTruncate(pPager->fd, newSize);
42402      }else if( (currentSize+szPage)<=newSize ){
42403        char *pTmp = pPager->pTmpSpace;
42404        memset(pTmp, 0, szPage);
42405        testcase( (newSize-szPage) == currentSize );
42406        testcase( (newSize-szPage) >  currentSize );
42407        rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
42408      }
42409      if( rc==SQLITE_OK ){
42410        pPager->dbFileSize = nPage;
42411      }
42412    }
42413  }
42414  return rc;
42415}
42416
42417/*
42418** Return a sanitized version of the sector-size of OS file pFile. The
42419** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
42420*/
42421SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
42422  int iRet = sqlite3OsSectorSize(pFile);
42423  if( iRet<32 ){
42424    iRet = 512;
42425  }else if( iRet>MAX_SECTOR_SIZE ){
42426    assert( MAX_SECTOR_SIZE>=512 );
42427    iRet = MAX_SECTOR_SIZE;
42428  }
42429  return iRet;
42430}
42431
42432/*
42433** Set the value of the Pager.sectorSize variable for the given
42434** pager based on the value returned by the xSectorSize method
42435** of the open database file. The sector size will be used used
42436** to determine the size and alignment of journal header and
42437** master journal pointers within created journal files.
42438**
42439** For temporary files the effective sector size is always 512 bytes.
42440**
42441** Otherwise, for non-temporary files, the effective sector size is
42442** the value returned by the xSectorSize() method rounded up to 32 if
42443** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
42444** is greater than MAX_SECTOR_SIZE.
42445**
42446** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
42447** the effective sector size to its minimum value (512).  The purpose of
42448** pPager->sectorSize is to define the "blast radius" of bytes that
42449** might change if a crash occurs while writing to a single byte in
42450** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
42451** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
42452** size.  For backwards compatibility of the rollback journal file format,
42453** we cannot reduce the effective sector size below 512.
42454*/
42455static void setSectorSize(Pager *pPager){
42456  assert( isOpen(pPager->fd) || pPager->tempFile );
42457
42458  if( pPager->tempFile
42459   || (sqlite3OsDeviceCharacteristics(pPager->fd) &
42460              SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
42461  ){
42462    /* Sector size doesn't matter for temporary files. Also, the file
42463    ** may not have been opened yet, in which case the OsSectorSize()
42464    ** call will segfault. */
42465    pPager->sectorSize = 512;
42466  }else{
42467    pPager->sectorSize = sqlite3SectorSize(pPager->fd);
42468  }
42469}
42470
42471/*
42472** Playback the journal and thus restore the database file to
42473** the state it was in before we started making changes.
42474**
42475** The journal file format is as follows:
42476**
42477**  (1)  8 byte prefix.  A copy of aJournalMagic[].
42478**  (2)  4 byte big-endian integer which is the number of valid page records
42479**       in the journal.  If this value is 0xffffffff, then compute the
42480**       number of page records from the journal size.
42481**  (3)  4 byte big-endian integer which is the initial value for the
42482**       sanity checksum.
42483**  (4)  4 byte integer which is the number of pages to truncate the
42484**       database to during a rollback.
42485**  (5)  4 byte big-endian integer which is the sector size.  The header
42486**       is this many bytes in size.
42487**  (6)  4 byte big-endian integer which is the page size.
42488**  (7)  zero padding out to the next sector size.
42489**  (8)  Zero or more pages instances, each as follows:
42490**        +  4 byte page number.
42491**        +  pPager->pageSize bytes of data.
42492**        +  4 byte checksum
42493**
42494** When we speak of the journal header, we mean the first 7 items above.
42495** Each entry in the journal is an instance of the 8th item.
42496**
42497** Call the value from the second bullet "nRec".  nRec is the number of
42498** valid page entries in the journal.  In most cases, you can compute the
42499** value of nRec from the size of the journal file.  But if a power
42500** failure occurred while the journal was being written, it could be the
42501** case that the size of the journal file had already been increased but
42502** the extra entries had not yet made it safely to disk.  In such a case,
42503** the value of nRec computed from the file size would be too large.  For
42504** that reason, we always use the nRec value in the header.
42505**
42506** If the nRec value is 0xffffffff it means that nRec should be computed
42507** from the file size.  This value is used when the user selects the
42508** no-sync option for the journal.  A power failure could lead to corruption
42509** in this case.  But for things like temporary table (which will be
42510** deleted when the power is restored) we don't care.
42511**
42512** If the file opened as the journal file is not a well-formed
42513** journal file then all pages up to the first corrupted page are rolled
42514** back (or no pages if the journal header is corrupted). The journal file
42515** is then deleted and SQLITE_OK returned, just as if no corruption had
42516** been encountered.
42517**
42518** If an I/O or malloc() error occurs, the journal-file is not deleted
42519** and an error code is returned.
42520**
42521** The isHot parameter indicates that we are trying to rollback a journal
42522** that might be a hot journal.  Or, it could be that the journal is
42523** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
42524** If the journal really is hot, reset the pager cache prior rolling
42525** back any content.  If the journal is merely persistent, no reset is
42526** needed.
42527*/
42528static int pager_playback(Pager *pPager, int isHot){
42529  sqlite3_vfs *pVfs = pPager->pVfs;
42530  i64 szJ;                 /* Size of the journal file in bytes */
42531  u32 nRec;                /* Number of Records in the journal */
42532  u32 u;                   /* Unsigned loop counter */
42533  Pgno mxPg = 0;           /* Size of the original file in pages */
42534  int rc;                  /* Result code of a subroutine */
42535  int res = 1;             /* Value returned by sqlite3OsAccess() */
42536  char *zMaster = 0;       /* Name of master journal file if any */
42537  int needPagerReset;      /* True to reset page prior to first page rollback */
42538  int nPlayback = 0;       /* Total number of pages restored from journal */
42539
42540  /* Figure out how many records are in the journal.  Abort early if
42541  ** the journal is empty.
42542  */
42543  assert( isOpen(pPager->jfd) );
42544  rc = sqlite3OsFileSize(pPager->jfd, &szJ);
42545  if( rc!=SQLITE_OK ){
42546    goto end_playback;
42547  }
42548
42549  /* Read the master journal name from the journal, if it is present.
42550  ** If a master journal file name is specified, but the file is not
42551  ** present on disk, then the journal is not hot and does not need to be
42552  ** played back.
42553  **
42554  ** TODO: Technically the following is an error because it assumes that
42555  ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
42556  ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
42557  **  mxPathname is 512, which is the same as the minimum allowable value
42558  ** for pageSize.
42559  */
42560  zMaster = pPager->pTmpSpace;
42561  rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
42562  if( rc==SQLITE_OK && zMaster[0] ){
42563    rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
42564  }
42565  zMaster = 0;
42566  if( rc!=SQLITE_OK || !res ){
42567    goto end_playback;
42568  }
42569  pPager->journalOff = 0;
42570  needPagerReset = isHot;
42571
42572  /* This loop terminates either when a readJournalHdr() or
42573  ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
42574  ** occurs.
42575  */
42576  while( 1 ){
42577    /* Read the next journal header from the journal file.  If there are
42578    ** not enough bytes left in the journal file for a complete header, or
42579    ** it is corrupted, then a process must have failed while writing it.
42580    ** This indicates nothing more needs to be rolled back.
42581    */
42582    rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
42583    if( rc!=SQLITE_OK ){
42584      if( rc==SQLITE_DONE ){
42585        rc = SQLITE_OK;
42586      }
42587      goto end_playback;
42588    }
42589
42590    /* If nRec is 0xffffffff, then this journal was created by a process
42591    ** working in no-sync mode. This means that the rest of the journal
42592    ** file consists of pages, there are no more journal headers. Compute
42593    ** the value of nRec based on this assumption.
42594    */
42595    if( nRec==0xffffffff ){
42596      assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
42597      nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
42598    }
42599
42600    /* If nRec is 0 and this rollback is of a transaction created by this
42601    ** process and if this is the final header in the journal, then it means
42602    ** that this part of the journal was being filled but has not yet been
42603    ** synced to disk.  Compute the number of pages based on the remaining
42604    ** size of the file.
42605    **
42606    ** The third term of the test was added to fix ticket #2565.
42607    ** When rolling back a hot journal, nRec==0 always means that the next
42608    ** chunk of the journal contains zero pages to be rolled back.  But
42609    ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
42610    ** the journal, it means that the journal might contain additional
42611    ** pages that need to be rolled back and that the number of pages
42612    ** should be computed based on the journal file size.
42613    */
42614    if( nRec==0 && !isHot &&
42615        pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
42616      nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
42617    }
42618
42619    /* If this is the first header read from the journal, truncate the
42620    ** database file back to its original size.
42621    */
42622    if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
42623      rc = pager_truncate(pPager, mxPg);
42624      if( rc!=SQLITE_OK ){
42625        goto end_playback;
42626      }
42627      pPager->dbSize = mxPg;
42628    }
42629
42630    /* Copy original pages out of the journal and back into the
42631    ** database file and/or page cache.
42632    */
42633    for(u=0; u<nRec; u++){
42634      if( needPagerReset ){
42635        pager_reset(pPager);
42636        needPagerReset = 0;
42637      }
42638      rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
42639      if( rc==SQLITE_OK ){
42640        nPlayback++;
42641      }else{
42642        if( rc==SQLITE_DONE ){
42643          pPager->journalOff = szJ;
42644          break;
42645        }else if( rc==SQLITE_IOERR_SHORT_READ ){
42646          /* If the journal has been truncated, simply stop reading and
42647          ** processing the journal. This might happen if the journal was
42648          ** not completely written and synced prior to a crash.  In that
42649          ** case, the database should have never been written in the
42650          ** first place so it is OK to simply abandon the rollback. */
42651          rc = SQLITE_OK;
42652          goto end_playback;
42653        }else{
42654          /* If we are unable to rollback, quit and return the error
42655          ** code.  This will cause the pager to enter the error state
42656          ** so that no further harm will be done.  Perhaps the next
42657          ** process to come along will be able to rollback the database.
42658          */
42659          goto end_playback;
42660        }
42661      }
42662    }
42663  }
42664  /*NOTREACHED*/
42665  assert( 0 );
42666
42667end_playback:
42668  /* Following a rollback, the database file should be back in its original
42669  ** state prior to the start of the transaction, so invoke the
42670  ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
42671  ** assertion that the transaction counter was modified.
42672  */
42673#ifdef SQLITE_DEBUG
42674  if( pPager->fd->pMethods ){
42675    sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
42676  }
42677#endif
42678
42679  /* If this playback is happening automatically as a result of an IO or
42680  ** malloc error that occurred after the change-counter was updated but
42681  ** before the transaction was committed, then the change-counter
42682  ** modification may just have been reverted. If this happens in exclusive
42683  ** mode, then subsequent transactions performed by the connection will not
42684  ** update the change-counter at all. This may lead to cache inconsistency
42685  ** problems for other processes at some point in the future. So, just
42686  ** in case this has happened, clear the changeCountDone flag now.
42687  */
42688  pPager->changeCountDone = pPager->tempFile;
42689
42690  if( rc==SQLITE_OK ){
42691    zMaster = pPager->pTmpSpace;
42692    rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
42693    testcase( rc!=SQLITE_OK );
42694  }
42695  if( rc==SQLITE_OK
42696   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
42697  ){
42698    rc = sqlite3PagerSync(pPager, 0);
42699  }
42700  if( rc==SQLITE_OK ){
42701    rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
42702    testcase( rc!=SQLITE_OK );
42703  }
42704  if( rc==SQLITE_OK && zMaster[0] && res ){
42705    /* If there was a master journal and this routine will return success,
42706    ** see if it is possible to delete the master journal.
42707    */
42708    rc = pager_delmaster(pPager, zMaster);
42709    testcase( rc!=SQLITE_OK );
42710  }
42711  if( isHot && nPlayback ){
42712    sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
42713                nPlayback, pPager->zJournal);
42714  }
42715
42716  /* The Pager.sectorSize variable may have been updated while rolling
42717  ** back a journal created by a process with a different sector size
42718  ** value. Reset it to the correct value for this process.
42719  */
42720  setSectorSize(pPager);
42721  return rc;
42722}
42723
42724
42725/*
42726** Read the content for page pPg out of the database file and into
42727** pPg->pData. A shared lock or greater must be held on the database
42728** file before this function is called.
42729**
42730** If page 1 is read, then the value of Pager.dbFileVers[] is set to
42731** the value read from the database file.
42732**
42733** If an IO error occurs, then the IO error is returned to the caller.
42734** Otherwise, SQLITE_OK is returned.
42735*/
42736static int readDbPage(PgHdr *pPg, u32 iFrame){
42737  Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
42738  Pgno pgno = pPg->pgno;       /* Page number to read */
42739  int rc = SQLITE_OK;          /* Return code */
42740  int pgsz = pPager->pageSize; /* Number of bytes to read */
42741
42742  assert( pPager->eState>=PAGER_READER && !MEMDB );
42743  assert( isOpen(pPager->fd) );
42744
42745#ifndef SQLITE_OMIT_WAL
42746  if( iFrame ){
42747    /* Try to pull the page from the write-ahead log. */
42748    rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
42749  }else
42750#endif
42751  {
42752    i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
42753    rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
42754    if( rc==SQLITE_IOERR_SHORT_READ ){
42755      rc = SQLITE_OK;
42756    }
42757  }
42758
42759  if( pgno==1 ){
42760    if( rc ){
42761      /* If the read is unsuccessful, set the dbFileVers[] to something
42762      ** that will never be a valid file version.  dbFileVers[] is a copy
42763      ** of bytes 24..39 of the database.  Bytes 28..31 should always be
42764      ** zero or the size of the database in page. Bytes 32..35 and 35..39
42765      ** should be page numbers which are never 0xffffffff.  So filling
42766      ** pPager->dbFileVers[] with all 0xff bytes should suffice.
42767      **
42768      ** For an encrypted database, the situation is more complex:  bytes
42769      ** 24..39 of the database are white noise.  But the probability of
42770      ** white noising equaling 16 bytes of 0xff is vanishingly small so
42771      ** we should still be ok.
42772      */
42773      memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
42774    }else{
42775      u8 *dbFileVers = &((u8*)pPg->pData)[24];
42776      memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
42777    }
42778  }
42779  CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
42780
42781  PAGER_INCR(sqlite3_pager_readdb_count);
42782  PAGER_INCR(pPager->nRead);
42783  IOTRACE(("PGIN %p %d\n", pPager, pgno));
42784  PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
42785               PAGERID(pPager), pgno, pager_pagehash(pPg)));
42786
42787  return rc;
42788}
42789
42790/*
42791** Update the value of the change-counter at offsets 24 and 92 in
42792** the header and the sqlite version number at offset 96.
42793**
42794** This is an unconditional update.  See also the pager_incr_changecounter()
42795** routine which only updates the change-counter if the update is actually
42796** needed, as determined by the pPager->changeCountDone state variable.
42797*/
42798static void pager_write_changecounter(PgHdr *pPg){
42799  u32 change_counter;
42800
42801  /* Increment the value just read and write it back to byte 24. */
42802  change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
42803  put32bits(((char*)pPg->pData)+24, change_counter);
42804
42805  /* Also store the SQLite version number in bytes 96..99 and in
42806  ** bytes 92..95 store the change counter for which the version number
42807  ** is valid. */
42808  put32bits(((char*)pPg->pData)+92, change_counter);
42809  put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
42810}
42811
42812#ifndef SQLITE_OMIT_WAL
42813/*
42814** This function is invoked once for each page that has already been
42815** written into the log file when a WAL transaction is rolled back.
42816** Parameter iPg is the page number of said page. The pCtx argument
42817** is actually a pointer to the Pager structure.
42818**
42819** If page iPg is present in the cache, and has no outstanding references,
42820** it is discarded. Otherwise, if there are one or more outstanding
42821** references, the page content is reloaded from the database. If the
42822** attempt to reload content from the database is required and fails,
42823** return an SQLite error code. Otherwise, SQLITE_OK.
42824*/
42825static int pagerUndoCallback(void *pCtx, Pgno iPg){
42826  int rc = SQLITE_OK;
42827  Pager *pPager = (Pager *)pCtx;
42828  PgHdr *pPg;
42829
42830  assert( pagerUseWal(pPager) );
42831  pPg = sqlite3PagerLookup(pPager, iPg);
42832  if( pPg ){
42833    if( sqlite3PcachePageRefcount(pPg)==1 ){
42834      sqlite3PcacheDrop(pPg);
42835    }else{
42836      u32 iFrame = 0;
42837      rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
42838      if( rc==SQLITE_OK ){
42839        rc = readDbPage(pPg, iFrame);
42840      }
42841      if( rc==SQLITE_OK ){
42842        pPager->xReiniter(pPg);
42843      }
42844      sqlite3PagerUnrefNotNull(pPg);
42845    }
42846  }
42847
42848  /* Normally, if a transaction is rolled back, any backup processes are
42849  ** updated as data is copied out of the rollback journal and into the
42850  ** database. This is not generally possible with a WAL database, as
42851  ** rollback involves simply truncating the log file. Therefore, if one
42852  ** or more frames have already been written to the log (and therefore
42853  ** also copied into the backup databases) as part of this transaction,
42854  ** the backups must be restarted.
42855  */
42856  sqlite3BackupRestart(pPager->pBackup);
42857
42858  return rc;
42859}
42860
42861/*
42862** This function is called to rollback a transaction on a WAL database.
42863*/
42864static int pagerRollbackWal(Pager *pPager){
42865  int rc;                         /* Return Code */
42866  PgHdr *pList;                   /* List of dirty pages to revert */
42867
42868  /* For all pages in the cache that are currently dirty or have already
42869  ** been written (but not committed) to the log file, do one of the
42870  ** following:
42871  **
42872  **   + Discard the cached page (if refcount==0), or
42873  **   + Reload page content from the database (if refcount>0).
42874  */
42875  pPager->dbSize = pPager->dbOrigSize;
42876  rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
42877  pList = sqlite3PcacheDirtyList(pPager->pPCache);
42878  while( pList && rc==SQLITE_OK ){
42879    PgHdr *pNext = pList->pDirty;
42880    rc = pagerUndoCallback((void *)pPager, pList->pgno);
42881    pList = pNext;
42882  }
42883
42884  return rc;
42885}
42886
42887/*
42888** This function is a wrapper around sqlite3WalFrames(). As well as logging
42889** the contents of the list of pages headed by pList (connected by pDirty),
42890** this function notifies any active backup processes that the pages have
42891** changed.
42892**
42893** The list of pages passed into this routine is always sorted by page number.
42894** Hence, if page 1 appears anywhere on the list, it will be the first page.
42895*/
42896static int pagerWalFrames(
42897  Pager *pPager,                  /* Pager object */
42898  PgHdr *pList,                   /* List of frames to log */
42899  Pgno nTruncate,                 /* Database size after this commit */
42900  int isCommit                    /* True if this is a commit */
42901){
42902  int rc;                         /* Return code */
42903  int nList;                      /* Number of pages in pList */
42904#if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
42905  PgHdr *p;                       /* For looping over pages */
42906#endif
42907
42908  assert( pPager->pWal );
42909  assert( pList );
42910#ifdef SQLITE_DEBUG
42911  /* Verify that the page list is in accending order */
42912  for(p=pList; p && p->pDirty; p=p->pDirty){
42913    assert( p->pgno < p->pDirty->pgno );
42914  }
42915#endif
42916
42917  assert( pList->pDirty==0 || isCommit );
42918  if( isCommit ){
42919    /* If a WAL transaction is being committed, there is no point in writing
42920    ** any pages with page numbers greater than nTruncate into the WAL file.
42921    ** They will never be read by any client. So remove them from the pDirty
42922    ** list here. */
42923    PgHdr *p;
42924    PgHdr **ppNext = &pList;
42925    nList = 0;
42926    for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
42927      if( p->pgno<=nTruncate ){
42928        ppNext = &p->pDirty;
42929        nList++;
42930      }
42931    }
42932    assert( pList );
42933  }else{
42934    nList = 1;
42935  }
42936  pPager->aStat[PAGER_STAT_WRITE] += nList;
42937
42938  if( pList->pgno==1 ) pager_write_changecounter(pList);
42939  rc = sqlite3WalFrames(pPager->pWal,
42940      pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
42941  );
42942  if( rc==SQLITE_OK && pPager->pBackup ){
42943    PgHdr *p;
42944    for(p=pList; p; p=p->pDirty){
42945      sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
42946    }
42947  }
42948
42949#ifdef SQLITE_CHECK_PAGES
42950  pList = sqlite3PcacheDirtyList(pPager->pPCache);
42951  for(p=pList; p; p=p->pDirty){
42952    pager_set_pagehash(p);
42953  }
42954#endif
42955
42956  return rc;
42957}
42958
42959/*
42960** Begin a read transaction on the WAL.
42961**
42962** This routine used to be called "pagerOpenSnapshot()" because it essentially
42963** makes a snapshot of the database at the current point in time and preserves
42964** that snapshot for use by the reader in spite of concurrently changes by
42965** other writers or checkpointers.
42966*/
42967static int pagerBeginReadTransaction(Pager *pPager){
42968  int rc;                         /* Return code */
42969  int changed = 0;                /* True if cache must be reset */
42970
42971  assert( pagerUseWal(pPager) );
42972  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
42973
42974  /* sqlite3WalEndReadTransaction() was not called for the previous
42975  ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
42976  ** are in locking_mode=NORMAL and EndRead() was previously called,
42977  ** the duplicate call is harmless.
42978  */
42979  sqlite3WalEndReadTransaction(pPager->pWal);
42980
42981  rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
42982  if( rc!=SQLITE_OK || changed ){
42983    pager_reset(pPager);
42984    if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
42985  }
42986
42987  return rc;
42988}
42989#endif
42990
42991/*
42992** This function is called as part of the transition from PAGER_OPEN
42993** to PAGER_READER state to determine the size of the database file
42994** in pages (assuming the page size currently stored in Pager.pageSize).
42995**
42996** If no error occurs, SQLITE_OK is returned and the size of the database
42997** in pages is stored in *pnPage. Otherwise, an error code (perhaps
42998** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
42999*/
43000static int pagerPagecount(Pager *pPager, Pgno *pnPage){
43001  Pgno nPage;                     /* Value to return via *pnPage */
43002
43003  /* Query the WAL sub-system for the database size. The WalDbsize()
43004  ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
43005  ** if the database size is not available. The database size is not
43006  ** available from the WAL sub-system if the log file is empty or
43007  ** contains no valid committed transactions.
43008  */
43009  assert( pPager->eState==PAGER_OPEN );
43010  assert( pPager->eLock>=SHARED_LOCK );
43011  nPage = sqlite3WalDbsize(pPager->pWal);
43012
43013  /* If the database size was not available from the WAL sub-system,
43014  ** determine it based on the size of the database file. If the size
43015  ** of the database file is not an integer multiple of the page-size,
43016  ** round down to the nearest page. Except, any file larger than 0
43017  ** bytes in size is considered to contain at least one page.
43018  */
43019  if( nPage==0 ){
43020    i64 n = 0;                    /* Size of db file in bytes */
43021    assert( isOpen(pPager->fd) || pPager->tempFile );
43022    if( isOpen(pPager->fd) ){
43023      int rc = sqlite3OsFileSize(pPager->fd, &n);
43024      if( rc!=SQLITE_OK ){
43025        return rc;
43026      }
43027    }
43028    nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
43029  }
43030
43031  /* If the current number of pages in the file is greater than the
43032  ** configured maximum pager number, increase the allowed limit so
43033  ** that the file can be read.
43034  */
43035  if( nPage>pPager->mxPgno ){
43036    pPager->mxPgno = (Pgno)nPage;
43037  }
43038
43039  *pnPage = nPage;
43040  return SQLITE_OK;
43041}
43042
43043#ifndef SQLITE_OMIT_WAL
43044/*
43045** Check if the *-wal file that corresponds to the database opened by pPager
43046** exists if the database is not empy, or verify that the *-wal file does
43047** not exist (by deleting it) if the database file is empty.
43048**
43049** If the database is not empty and the *-wal file exists, open the pager
43050** in WAL mode.  If the database is empty or if no *-wal file exists and
43051** if no error occurs, make sure Pager.journalMode is not set to
43052** PAGER_JOURNALMODE_WAL.
43053**
43054** Return SQLITE_OK or an error code.
43055**
43056** The caller must hold a SHARED lock on the database file to call this
43057** function. Because an EXCLUSIVE lock on the db file is required to delete
43058** a WAL on a none-empty database, this ensures there is no race condition
43059** between the xAccess() below and an xDelete() being executed by some
43060** other connection.
43061*/
43062static int pagerOpenWalIfPresent(Pager *pPager){
43063  int rc = SQLITE_OK;
43064  assert( pPager->eState==PAGER_OPEN );
43065  assert( pPager->eLock>=SHARED_LOCK );
43066
43067  if( !pPager->tempFile ){
43068    int isWal;                    /* True if WAL file exists */
43069    Pgno nPage;                   /* Size of the database file */
43070
43071    rc = pagerPagecount(pPager, &nPage);
43072    if( rc ) return rc;
43073    if( nPage==0 ){
43074      rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
43075      if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
43076      isWal = 0;
43077    }else{
43078      rc = sqlite3OsAccess(
43079          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
43080      );
43081    }
43082    if( rc==SQLITE_OK ){
43083      if( isWal ){
43084        testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
43085        rc = sqlite3PagerOpenWal(pPager, 0);
43086      }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
43087        pPager->journalMode = PAGER_JOURNALMODE_DELETE;
43088      }
43089    }
43090  }
43091  return rc;
43092}
43093#endif
43094
43095/*
43096** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
43097** the entire master journal file. The case pSavepoint==NULL occurs when
43098** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
43099** savepoint.
43100**
43101** When pSavepoint is not NULL (meaning a non-transaction savepoint is
43102** being rolled back), then the rollback consists of up to three stages,
43103** performed in the order specified:
43104**
43105**   * Pages are played back from the main journal starting at byte
43106**     offset PagerSavepoint.iOffset and continuing to
43107**     PagerSavepoint.iHdrOffset, or to the end of the main journal
43108**     file if PagerSavepoint.iHdrOffset is zero.
43109**
43110**   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
43111**     back starting from the journal header immediately following
43112**     PagerSavepoint.iHdrOffset to the end of the main journal file.
43113**
43114**   * Pages are then played back from the sub-journal file, starting
43115**     with the PagerSavepoint.iSubRec and continuing to the end of
43116**     the journal file.
43117**
43118** Throughout the rollback process, each time a page is rolled back, the
43119** corresponding bit is set in a bitvec structure (variable pDone in the
43120** implementation below). This is used to ensure that a page is only
43121** rolled back the first time it is encountered in either journal.
43122**
43123** If pSavepoint is NULL, then pages are only played back from the main
43124** journal file. There is no need for a bitvec in this case.
43125**
43126** In either case, before playback commences the Pager.dbSize variable
43127** is reset to the value that it held at the start of the savepoint
43128** (or transaction). No page with a page-number greater than this value
43129** is played back. If one is encountered it is simply skipped.
43130*/
43131static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
43132  i64 szJ;                 /* Effective size of the main journal */
43133  i64 iHdrOff;             /* End of first segment of main-journal records */
43134  int rc = SQLITE_OK;      /* Return code */
43135  Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
43136
43137  assert( pPager->eState!=PAGER_ERROR );
43138  assert( pPager->eState>=PAGER_WRITER_LOCKED );
43139
43140  /* Allocate a bitvec to use to store the set of pages rolled back */
43141  if( pSavepoint ){
43142    pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
43143    if( !pDone ){
43144      return SQLITE_NOMEM;
43145    }
43146  }
43147
43148  /* Set the database size back to the value it was before the savepoint
43149  ** being reverted was opened.
43150  */
43151  pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
43152  pPager->changeCountDone = pPager->tempFile;
43153
43154  if( !pSavepoint && pagerUseWal(pPager) ){
43155    return pagerRollbackWal(pPager);
43156  }
43157
43158  /* Use pPager->journalOff as the effective size of the main rollback
43159  ** journal.  The actual file might be larger than this in
43160  ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
43161  ** past pPager->journalOff is off-limits to us.
43162  */
43163  szJ = pPager->journalOff;
43164  assert( pagerUseWal(pPager)==0 || szJ==0 );
43165
43166  /* Begin by rolling back records from the main journal starting at
43167  ** PagerSavepoint.iOffset and continuing to the next journal header.
43168  ** There might be records in the main journal that have a page number
43169  ** greater than the current database size (pPager->dbSize) but those
43170  ** will be skipped automatically.  Pages are added to pDone as they
43171  ** are played back.
43172  */
43173  if( pSavepoint && !pagerUseWal(pPager) ){
43174    iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
43175    pPager->journalOff = pSavepoint->iOffset;
43176    while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
43177      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
43178    }
43179    assert( rc!=SQLITE_DONE );
43180  }else{
43181    pPager->journalOff = 0;
43182  }
43183
43184  /* Continue rolling back records out of the main journal starting at
43185  ** the first journal header seen and continuing until the effective end
43186  ** of the main journal file.  Continue to skip out-of-range pages and
43187  ** continue adding pages rolled back to pDone.
43188  */
43189  while( rc==SQLITE_OK && pPager->journalOff<szJ ){
43190    u32 ii;            /* Loop counter */
43191    u32 nJRec = 0;     /* Number of Journal Records */
43192    u32 dummy;
43193    rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
43194    assert( rc!=SQLITE_DONE );
43195
43196    /*
43197    ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
43198    ** test is related to ticket #2565.  See the discussion in the
43199    ** pager_playback() function for additional information.
43200    */
43201    if( nJRec==0
43202     && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
43203    ){
43204      nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
43205    }
43206    for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
43207      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
43208    }
43209    assert( rc!=SQLITE_DONE );
43210  }
43211  assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
43212
43213  /* Finally,  rollback pages from the sub-journal.  Page that were
43214  ** previously rolled back out of the main journal (and are hence in pDone)
43215  ** will be skipped.  Out-of-range pages are also skipped.
43216  */
43217  if( pSavepoint ){
43218    u32 ii;            /* Loop counter */
43219    i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
43220
43221    if( pagerUseWal(pPager) ){
43222      rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
43223    }
43224    for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
43225      assert( offset==(i64)ii*(4+pPager->pageSize) );
43226      rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
43227    }
43228    assert( rc!=SQLITE_DONE );
43229  }
43230
43231  sqlite3BitvecDestroy(pDone);
43232  if( rc==SQLITE_OK ){
43233    pPager->journalOff = szJ;
43234  }
43235
43236  return rc;
43237}
43238
43239/*
43240** Change the maximum number of in-memory pages that are allowed.
43241*/
43242SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
43243  sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
43244}
43245
43246/*
43247** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
43248*/
43249static void pagerFixMaplimit(Pager *pPager){
43250#if SQLITE_MAX_MMAP_SIZE>0
43251  sqlite3_file *fd = pPager->fd;
43252  if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
43253    sqlite3_int64 sz;
43254    sz = pPager->szMmap;
43255    pPager->bUseFetch = (sz>0);
43256    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
43257  }
43258#endif
43259}
43260
43261/*
43262** Change the maximum size of any memory mapping made of the database file.
43263*/
43264SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
43265  pPager->szMmap = szMmap;
43266  pagerFixMaplimit(pPager);
43267}
43268
43269/*
43270** Free as much memory as possible from the pager.
43271*/
43272SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
43273  sqlite3PcacheShrink(pPager->pPCache);
43274}
43275
43276/*
43277** Adjust settings of the pager to those specified in the pgFlags parameter.
43278**
43279** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
43280** of the database to damage due to OS crashes or power failures by
43281** changing the number of syncs()s when writing the journals.
43282** There are three levels:
43283**
43284**    OFF       sqlite3OsSync() is never called.  This is the default
43285**              for temporary and transient files.
43286**
43287**    NORMAL    The journal is synced once before writes begin on the
43288**              database.  This is normally adequate protection, but
43289**              it is theoretically possible, though very unlikely,
43290**              that an inopertune power failure could leave the journal
43291**              in a state which would cause damage to the database
43292**              when it is rolled back.
43293**
43294**    FULL      The journal is synced twice before writes begin on the
43295**              database (with some additional information - the nRec field
43296**              of the journal header - being written in between the two
43297**              syncs).  If we assume that writing a
43298**              single disk sector is atomic, then this mode provides
43299**              assurance that the journal will not be corrupted to the
43300**              point of causing damage to the database during rollback.
43301**
43302** The above is for a rollback-journal mode.  For WAL mode, OFF continues
43303** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
43304** prior to the start of checkpoint and that the database file is synced
43305** at the conclusion of the checkpoint if the entire content of the WAL
43306** was written back into the database.  But no sync operations occur for
43307** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
43308** file is synced following each commit operation, in addition to the
43309** syncs associated with NORMAL.
43310**
43311** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
43312** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
43313** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
43314** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
43315** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
43316** synchronous=FULL versus synchronous=NORMAL setting determines when
43317** the xSync primitive is called and is relevant to all platforms.
43318**
43319** Numeric values associated with these states are OFF==1, NORMAL=2,
43320** and FULL=3.
43321*/
43322#ifndef SQLITE_OMIT_PAGER_PRAGMAS
43323SQLITE_PRIVATE void sqlite3PagerSetFlags(
43324  Pager *pPager,        /* The pager to set safety level for */
43325  unsigned pgFlags      /* Various flags */
43326){
43327  unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
43328  assert( level>=1 && level<=3 );
43329  pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
43330  pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
43331  if( pPager->noSync ){
43332    pPager->syncFlags = 0;
43333    pPager->ckptSyncFlags = 0;
43334  }else if( pgFlags & PAGER_FULLFSYNC ){
43335    pPager->syncFlags = SQLITE_SYNC_FULL;
43336    pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
43337  }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
43338    pPager->syncFlags = SQLITE_SYNC_NORMAL;
43339    pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
43340  }else{
43341    pPager->syncFlags = SQLITE_SYNC_NORMAL;
43342    pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
43343  }
43344  pPager->walSyncFlags = pPager->syncFlags;
43345  if( pPager->fullSync ){
43346    pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
43347  }
43348  if( pgFlags & PAGER_CACHESPILL ){
43349    pPager->doNotSpill &= ~SPILLFLAG_OFF;
43350  }else{
43351    pPager->doNotSpill |= SPILLFLAG_OFF;
43352  }
43353}
43354#endif
43355
43356/*
43357** The following global variable is incremented whenever the library
43358** attempts to open a temporary file.  This information is used for
43359** testing and analysis only.
43360*/
43361#ifdef SQLITE_TEST
43362SQLITE_API int sqlite3_opentemp_count = 0;
43363#endif
43364
43365/*
43366** Open a temporary file.
43367**
43368** Write the file descriptor into *pFile. Return SQLITE_OK on success
43369** or some other error code if we fail. The OS will automatically
43370** delete the temporary file when it is closed.
43371**
43372** The flags passed to the VFS layer xOpen() call are those specified
43373** by parameter vfsFlags ORed with the following:
43374**
43375**     SQLITE_OPEN_READWRITE
43376**     SQLITE_OPEN_CREATE
43377**     SQLITE_OPEN_EXCLUSIVE
43378**     SQLITE_OPEN_DELETEONCLOSE
43379*/
43380static int pagerOpentemp(
43381  Pager *pPager,        /* The pager object */
43382  sqlite3_file *pFile,  /* Write the file descriptor here */
43383  int vfsFlags          /* Flags passed through to the VFS */
43384){
43385  int rc;               /* Return code */
43386
43387#ifdef SQLITE_TEST
43388  sqlite3_opentemp_count++;  /* Used for testing and analysis only */
43389#endif
43390
43391  vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
43392            SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
43393  rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
43394  assert( rc!=SQLITE_OK || isOpen(pFile) );
43395  return rc;
43396}
43397
43398/*
43399** Set the busy handler function.
43400**
43401** The pager invokes the busy-handler if sqlite3OsLock() returns
43402** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
43403** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
43404** lock. It does *not* invoke the busy handler when upgrading from
43405** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
43406** (which occurs during hot-journal rollback). Summary:
43407**
43408**   Transition                        | Invokes xBusyHandler
43409**   --------------------------------------------------------
43410**   NO_LOCK       -> SHARED_LOCK      | Yes
43411**   SHARED_LOCK   -> RESERVED_LOCK    | No
43412**   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
43413**   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
43414**
43415** If the busy-handler callback returns non-zero, the lock is
43416** retried. If it returns zero, then the SQLITE_BUSY error is
43417** returned to the caller of the pager API function.
43418*/
43419SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
43420  Pager *pPager,                       /* Pager object */
43421  int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
43422  void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
43423){
43424  pPager->xBusyHandler = xBusyHandler;
43425  pPager->pBusyHandlerArg = pBusyHandlerArg;
43426
43427  if( isOpen(pPager->fd) ){
43428    void **ap = (void **)&pPager->xBusyHandler;
43429    assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
43430    assert( ap[1]==pBusyHandlerArg );
43431    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
43432  }
43433}
43434
43435/*
43436** Change the page size used by the Pager object. The new page size
43437** is passed in *pPageSize.
43438**
43439** If the pager is in the error state when this function is called, it
43440** is a no-op. The value returned is the error state error code (i.e.
43441** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
43442**
43443** Otherwise, if all of the following are true:
43444**
43445**   * the new page size (value of *pPageSize) is valid (a power
43446**     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
43447**
43448**   * there are no outstanding page references, and
43449**
43450**   * the database is either not an in-memory database or it is
43451**     an in-memory database that currently consists of zero pages.
43452**
43453** then the pager object page size is set to *pPageSize.
43454**
43455** If the page size is changed, then this function uses sqlite3PagerMalloc()
43456** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
43457** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
43458** In all other cases, SQLITE_OK is returned.
43459**
43460** If the page size is not changed, either because one of the enumerated
43461** conditions above is not true, the pager was in error state when this
43462** function was called, or because the memory allocation attempt failed,
43463** then *pPageSize is set to the old, retained page size before returning.
43464*/
43465SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
43466  int rc = SQLITE_OK;
43467
43468  /* It is not possible to do a full assert_pager_state() here, as this
43469  ** function may be called from within PagerOpen(), before the state
43470  ** of the Pager object is internally consistent.
43471  **
43472  ** At one point this function returned an error if the pager was in
43473  ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
43474  ** there is at least one outstanding page reference, this function
43475  ** is a no-op for that case anyhow.
43476  */
43477
43478  u32 pageSize = *pPageSize;
43479  assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
43480  if( (pPager->memDb==0 || pPager->dbSize==0)
43481   && sqlite3PcacheRefCount(pPager->pPCache)==0
43482   && pageSize && pageSize!=(u32)pPager->pageSize
43483  ){
43484    char *pNew = NULL;             /* New temp space */
43485    i64 nByte = 0;
43486
43487    if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
43488      rc = sqlite3OsFileSize(pPager->fd, &nByte);
43489    }
43490    if( rc==SQLITE_OK ){
43491      pNew = (char *)sqlite3PageMalloc(pageSize);
43492      if( !pNew ) rc = SQLITE_NOMEM;
43493    }
43494
43495    if( rc==SQLITE_OK ){
43496      pager_reset(pPager);
43497      pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
43498      pPager->pageSize = pageSize;
43499      sqlite3PageFree(pPager->pTmpSpace);
43500      pPager->pTmpSpace = pNew;
43501      sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
43502    }
43503  }
43504
43505  *pPageSize = pPager->pageSize;
43506  if( rc==SQLITE_OK ){
43507    if( nReserve<0 ) nReserve = pPager->nReserve;
43508    assert( nReserve>=0 && nReserve<1000 );
43509    pPager->nReserve = (i16)nReserve;
43510    pagerReportSize(pPager);
43511    pagerFixMaplimit(pPager);
43512  }
43513  return rc;
43514}
43515
43516/*
43517** Return a pointer to the "temporary page" buffer held internally
43518** by the pager.  This is a buffer that is big enough to hold the
43519** entire content of a database page.  This buffer is used internally
43520** during rollback and will be overwritten whenever a rollback
43521** occurs.  But other modules are free to use it too, as long as
43522** no rollbacks are happening.
43523*/
43524SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
43525  return pPager->pTmpSpace;
43526}
43527
43528/*
43529** Attempt to set the maximum database page count if mxPage is positive.
43530** Make no changes if mxPage is zero or negative.  And never reduce the
43531** maximum page count below the current size of the database.
43532**
43533** Regardless of mxPage, return the current maximum page count.
43534*/
43535SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
43536  if( mxPage>0 ){
43537    pPager->mxPgno = mxPage;
43538  }
43539  assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
43540  assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
43541  return pPager->mxPgno;
43542}
43543
43544/*
43545** The following set of routines are used to disable the simulated
43546** I/O error mechanism.  These routines are used to avoid simulated
43547** errors in places where we do not care about errors.
43548**
43549** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
43550** and generate no code.
43551*/
43552#ifdef SQLITE_TEST
43553SQLITE_API extern int sqlite3_io_error_pending;
43554SQLITE_API extern int sqlite3_io_error_hit;
43555static int saved_cnt;
43556void disable_simulated_io_errors(void){
43557  saved_cnt = sqlite3_io_error_pending;
43558  sqlite3_io_error_pending = -1;
43559}
43560void enable_simulated_io_errors(void){
43561  sqlite3_io_error_pending = saved_cnt;
43562}
43563#else
43564# define disable_simulated_io_errors()
43565# define enable_simulated_io_errors()
43566#endif
43567
43568/*
43569** Read the first N bytes from the beginning of the file into memory
43570** that pDest points to.
43571**
43572** If the pager was opened on a transient file (zFilename==""), or
43573** opened on a file less than N bytes in size, the output buffer is
43574** zeroed and SQLITE_OK returned. The rationale for this is that this
43575** function is used to read database headers, and a new transient or
43576** zero sized database has a header than consists entirely of zeroes.
43577**
43578** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
43579** the error code is returned to the caller and the contents of the
43580** output buffer undefined.
43581*/
43582SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
43583  int rc = SQLITE_OK;
43584  memset(pDest, 0, N);
43585  assert( isOpen(pPager->fd) || pPager->tempFile );
43586
43587  /* This routine is only called by btree immediately after creating
43588  ** the Pager object.  There has not been an opportunity to transition
43589  ** to WAL mode yet.
43590  */
43591  assert( !pagerUseWal(pPager) );
43592
43593  if( isOpen(pPager->fd) ){
43594    IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
43595    rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
43596    if( rc==SQLITE_IOERR_SHORT_READ ){
43597      rc = SQLITE_OK;
43598    }
43599  }
43600  return rc;
43601}
43602
43603/*
43604** This function may only be called when a read-transaction is open on
43605** the pager. It returns the total number of pages in the database.
43606**
43607** However, if the file is between 1 and <page-size> bytes in size, then
43608** this is considered a 1 page file.
43609*/
43610SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
43611  assert( pPager->eState>=PAGER_READER );
43612  assert( pPager->eState!=PAGER_WRITER_FINISHED );
43613  *pnPage = (int)pPager->dbSize;
43614}
43615
43616
43617/*
43618** Try to obtain a lock of type locktype on the database file. If
43619** a similar or greater lock is already held, this function is a no-op
43620** (returning SQLITE_OK immediately).
43621**
43622** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
43623** the busy callback if the lock is currently not available. Repeat
43624** until the busy callback returns false or until the attempt to
43625** obtain the lock succeeds.
43626**
43627** Return SQLITE_OK on success and an error code if we cannot obtain
43628** the lock. If the lock is obtained successfully, set the Pager.state
43629** variable to locktype before returning.
43630*/
43631static int pager_wait_on_lock(Pager *pPager, int locktype){
43632  int rc;                              /* Return code */
43633
43634  /* Check that this is either a no-op (because the requested lock is
43635  ** already held, or one of the transistions that the busy-handler
43636  ** may be invoked during, according to the comment above
43637  ** sqlite3PagerSetBusyhandler().
43638  */
43639  assert( (pPager->eLock>=locktype)
43640       || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
43641       || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
43642  );
43643
43644  do {
43645    rc = pagerLockDb(pPager, locktype);
43646  }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
43647  return rc;
43648}
43649
43650/*
43651** Function assertTruncateConstraint(pPager) checks that one of the
43652** following is true for all dirty pages currently in the page-cache:
43653**
43654**   a) The page number is less than or equal to the size of the
43655**      current database image, in pages, OR
43656**
43657**   b) if the page content were written at this time, it would not
43658**      be necessary to write the current content out to the sub-journal
43659**      (as determined by function subjRequiresPage()).
43660**
43661** If the condition asserted by this function were not true, and the
43662** dirty page were to be discarded from the cache via the pagerStress()
43663** routine, pagerStress() would not write the current page content to
43664** the database file. If a savepoint transaction were rolled back after
43665** this happened, the correct behavior would be to restore the current
43666** content of the page. However, since this content is not present in either
43667** the database file or the portion of the rollback journal and
43668** sub-journal rolled back the content could not be restored and the
43669** database image would become corrupt. It is therefore fortunate that
43670** this circumstance cannot arise.
43671*/
43672#if defined(SQLITE_DEBUG)
43673static void assertTruncateConstraintCb(PgHdr *pPg){
43674  assert( pPg->flags&PGHDR_DIRTY );
43675  assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
43676}
43677static void assertTruncateConstraint(Pager *pPager){
43678  sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
43679}
43680#else
43681# define assertTruncateConstraint(pPager)
43682#endif
43683
43684/*
43685** Truncate the in-memory database file image to nPage pages. This
43686** function does not actually modify the database file on disk. It
43687** just sets the internal state of the pager object so that the
43688** truncation will be done when the current transaction is committed.
43689**
43690** This function is only called right before committing a transaction.
43691** Once this function has been called, the transaction must either be
43692** rolled back or committed. It is not safe to call this function and
43693** then continue writing to the database.
43694*/
43695SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
43696  assert( pPager->dbSize>=nPage );
43697  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
43698  pPager->dbSize = nPage;
43699
43700  /* At one point the code here called assertTruncateConstraint() to
43701  ** ensure that all pages being truncated away by this operation are,
43702  ** if one or more savepoints are open, present in the savepoint
43703  ** journal so that they can be restored if the savepoint is rolled
43704  ** back. This is no longer necessary as this function is now only
43705  ** called right before committing a transaction. So although the
43706  ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
43707  ** they cannot be rolled back. So the assertTruncateConstraint() call
43708  ** is no longer correct. */
43709}
43710
43711
43712/*
43713** This function is called before attempting a hot-journal rollback. It
43714** syncs the journal file to disk, then sets pPager->journalHdr to the
43715** size of the journal file so that the pager_playback() routine knows
43716** that the entire journal file has been synced.
43717**
43718** Syncing a hot-journal to disk before attempting to roll it back ensures
43719** that if a power-failure occurs during the rollback, the process that
43720** attempts rollback following system recovery sees the same journal
43721** content as this process.
43722**
43723** If everything goes as planned, SQLITE_OK is returned. Otherwise,
43724** an SQLite error code.
43725*/
43726static int pagerSyncHotJournal(Pager *pPager){
43727  int rc = SQLITE_OK;
43728  if( !pPager->noSync ){
43729    rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
43730  }
43731  if( rc==SQLITE_OK ){
43732    rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
43733  }
43734  return rc;
43735}
43736
43737/*
43738** Obtain a reference to a memory mapped page object for page number pgno.
43739** The new object will use the pointer pData, obtained from xFetch().
43740** If successful, set *ppPage to point to the new page reference
43741** and return SQLITE_OK. Otherwise, return an SQLite error code and set
43742** *ppPage to zero.
43743**
43744** Page references obtained by calling this function should be released
43745** by calling pagerReleaseMapPage().
43746*/
43747static int pagerAcquireMapPage(
43748  Pager *pPager,                  /* Pager object */
43749  Pgno pgno,                      /* Page number */
43750  void *pData,                    /* xFetch()'d data for this page */
43751  PgHdr **ppPage                  /* OUT: Acquired page object */
43752){
43753  PgHdr *p;                       /* Memory mapped page to return */
43754
43755  if( pPager->pMmapFreelist ){
43756    *ppPage = p = pPager->pMmapFreelist;
43757    pPager->pMmapFreelist = p->pDirty;
43758    p->pDirty = 0;
43759    memset(p->pExtra, 0, pPager->nExtra);
43760  }else{
43761    *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
43762    if( p==0 ){
43763      sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
43764      return SQLITE_NOMEM;
43765    }
43766    p->pExtra = (void *)&p[1];
43767    p->flags = PGHDR_MMAP;
43768    p->nRef = 1;
43769    p->pPager = pPager;
43770  }
43771
43772  assert( p->pExtra==(void *)&p[1] );
43773  assert( p->pPage==0 );
43774  assert( p->flags==PGHDR_MMAP );
43775  assert( p->pPager==pPager );
43776  assert( p->nRef==1 );
43777
43778  p->pgno = pgno;
43779  p->pData = pData;
43780  pPager->nMmapOut++;
43781
43782  return SQLITE_OK;
43783}
43784
43785/*
43786** Release a reference to page pPg. pPg must have been returned by an
43787** earlier call to pagerAcquireMapPage().
43788*/
43789static void pagerReleaseMapPage(PgHdr *pPg){
43790  Pager *pPager = pPg->pPager;
43791  pPager->nMmapOut--;
43792  pPg->pDirty = pPager->pMmapFreelist;
43793  pPager->pMmapFreelist = pPg;
43794
43795  assert( pPager->fd->pMethods->iVersion>=3 );
43796  sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
43797}
43798
43799/*
43800** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
43801*/
43802static void pagerFreeMapHdrs(Pager *pPager){
43803  PgHdr *p;
43804  PgHdr *pNext;
43805  for(p=pPager->pMmapFreelist; p; p=pNext){
43806    pNext = p->pDirty;
43807    sqlite3_free(p);
43808  }
43809}
43810
43811
43812/*
43813** Shutdown the page cache.  Free all memory and close all files.
43814**
43815** If a transaction was in progress when this routine is called, that
43816** transaction is rolled back.  All outstanding pages are invalidated
43817** and their memory is freed.  Any attempt to use a page associated
43818** with this page cache after this function returns will likely
43819** result in a coredump.
43820**
43821** This function always succeeds. If a transaction is active an attempt
43822** is made to roll it back. If an error occurs during the rollback
43823** a hot journal may be left in the filesystem but no error is returned
43824** to the caller.
43825*/
43826SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
43827  u8 *pTmp = (u8 *)pPager->pTmpSpace;
43828
43829  assert( assert_pager_state(pPager) );
43830  disable_simulated_io_errors();
43831  sqlite3BeginBenignMalloc();
43832  pagerFreeMapHdrs(pPager);
43833  /* pPager->errCode = 0; */
43834  pPager->exclusiveMode = 0;
43835#ifndef SQLITE_OMIT_WAL
43836  sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
43837  pPager->pWal = 0;
43838#endif
43839  pager_reset(pPager);
43840  if( MEMDB ){
43841    pager_unlock(pPager);
43842  }else{
43843    /* If it is open, sync the journal file before calling UnlockAndRollback.
43844    ** If this is not done, then an unsynced portion of the open journal
43845    ** file may be played back into the database. If a power failure occurs
43846    ** while this is happening, the database could become corrupt.
43847    **
43848    ** If an error occurs while trying to sync the journal, shift the pager
43849    ** into the ERROR state. This causes UnlockAndRollback to unlock the
43850    ** database and close the journal file without attempting to roll it
43851    ** back or finalize it. The next database user will have to do hot-journal
43852    ** rollback before accessing the database file.
43853    */
43854    if( isOpen(pPager->jfd) ){
43855      pager_error(pPager, pagerSyncHotJournal(pPager));
43856    }
43857    pagerUnlockAndRollback(pPager);
43858  }
43859  sqlite3EndBenignMalloc();
43860  enable_simulated_io_errors();
43861  PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
43862  IOTRACE(("CLOSE %p\n", pPager))
43863  sqlite3OsClose(pPager->jfd);
43864  sqlite3OsClose(pPager->fd);
43865  sqlite3PageFree(pTmp);
43866  sqlite3PcacheClose(pPager->pPCache);
43867
43868#ifdef SQLITE_HAS_CODEC
43869  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
43870#endif
43871
43872  assert( !pPager->aSavepoint && !pPager->pInJournal );
43873  assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
43874
43875  sqlite3_free(pPager);
43876  return SQLITE_OK;
43877}
43878
43879#if !defined(NDEBUG) || defined(SQLITE_TEST)
43880/*
43881** Return the page number for page pPg.
43882*/
43883SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
43884  return pPg->pgno;
43885}
43886#endif
43887
43888/*
43889** Increment the reference count for page pPg.
43890*/
43891SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
43892  sqlite3PcacheRef(pPg);
43893}
43894
43895/*
43896** Sync the journal. In other words, make sure all the pages that have
43897** been written to the journal have actually reached the surface of the
43898** disk and can be restored in the event of a hot-journal rollback.
43899**
43900** If the Pager.noSync flag is set, then this function is a no-op.
43901** Otherwise, the actions required depend on the journal-mode and the
43902** device characteristics of the file-system, as follows:
43903**
43904**   * If the journal file is an in-memory journal file, no action need
43905**     be taken.
43906**
43907**   * Otherwise, if the device does not support the SAFE_APPEND property,
43908**     then the nRec field of the most recently written journal header
43909**     is updated to contain the number of journal records that have
43910**     been written following it. If the pager is operating in full-sync
43911**     mode, then the journal file is synced before this field is updated.
43912**
43913**   * If the device does not support the SEQUENTIAL property, then
43914**     journal file is synced.
43915**
43916** Or, in pseudo-code:
43917**
43918**   if( NOT <in-memory journal> ){
43919**     if( NOT SAFE_APPEND ){
43920**       if( <full-sync mode> ) xSync(<journal file>);
43921**       <update nRec field>
43922**     }
43923**     if( NOT SEQUENTIAL ) xSync(<journal file>);
43924**   }
43925**
43926** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
43927** page currently held in memory before returning SQLITE_OK. If an IO
43928** error is encountered, then the IO error code is returned to the caller.
43929*/
43930static int syncJournal(Pager *pPager, int newHdr){
43931  int rc;                         /* Return code */
43932
43933  assert( pPager->eState==PAGER_WRITER_CACHEMOD
43934       || pPager->eState==PAGER_WRITER_DBMOD
43935  );
43936  assert( assert_pager_state(pPager) );
43937  assert( !pagerUseWal(pPager) );
43938
43939  rc = sqlite3PagerExclusiveLock(pPager);
43940  if( rc!=SQLITE_OK ) return rc;
43941
43942  if( !pPager->noSync ){
43943    assert( !pPager->tempFile );
43944    if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
43945      const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
43946      assert( isOpen(pPager->jfd) );
43947
43948      if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
43949        /* This block deals with an obscure problem. If the last connection
43950        ** that wrote to this database was operating in persistent-journal
43951        ** mode, then the journal file may at this point actually be larger
43952        ** than Pager.journalOff bytes. If the next thing in the journal
43953        ** file happens to be a journal-header (written as part of the
43954        ** previous connection's transaction), and a crash or power-failure
43955        ** occurs after nRec is updated but before this connection writes
43956        ** anything else to the journal file (or commits/rolls back its
43957        ** transaction), then SQLite may become confused when doing the
43958        ** hot-journal rollback following recovery. It may roll back all
43959        ** of this connections data, then proceed to rolling back the old,
43960        ** out-of-date data that follows it. Database corruption.
43961        **
43962        ** To work around this, if the journal file does appear to contain
43963        ** a valid header following Pager.journalOff, then write a 0x00
43964        ** byte to the start of it to prevent it from being recognized.
43965        **
43966        ** Variable iNextHdrOffset is set to the offset at which this
43967        ** problematic header will occur, if it exists. aMagic is used
43968        ** as a temporary buffer to inspect the first couple of bytes of
43969        ** the potential journal header.
43970        */
43971        i64 iNextHdrOffset;
43972        u8 aMagic[8];
43973        u8 zHeader[sizeof(aJournalMagic)+4];
43974
43975        memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
43976        put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
43977
43978        iNextHdrOffset = journalHdrOffset(pPager);
43979        rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
43980        if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
43981          static const u8 zerobyte = 0;
43982          rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
43983        }
43984        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
43985          return rc;
43986        }
43987
43988        /* Write the nRec value into the journal file header. If in
43989        ** full-synchronous mode, sync the journal first. This ensures that
43990        ** all data has really hit the disk before nRec is updated to mark
43991        ** it as a candidate for rollback.
43992        **
43993        ** This is not required if the persistent media supports the
43994        ** SAFE_APPEND property. Because in this case it is not possible
43995        ** for garbage data to be appended to the file, the nRec field
43996        ** is populated with 0xFFFFFFFF when the journal header is written
43997        ** and never needs to be updated.
43998        */
43999        if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
44000          PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
44001          IOTRACE(("JSYNC %p\n", pPager))
44002          rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
44003          if( rc!=SQLITE_OK ) return rc;
44004        }
44005        IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
44006        rc = sqlite3OsWrite(
44007            pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
44008        );
44009        if( rc!=SQLITE_OK ) return rc;
44010      }
44011      if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
44012        PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
44013        IOTRACE(("JSYNC %p\n", pPager))
44014        rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
44015          (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
44016        );
44017        if( rc!=SQLITE_OK ) return rc;
44018      }
44019
44020      pPager->journalHdr = pPager->journalOff;
44021      if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
44022        pPager->nRec = 0;
44023        rc = writeJournalHdr(pPager);
44024        if( rc!=SQLITE_OK ) return rc;
44025      }
44026    }else{
44027      pPager->journalHdr = pPager->journalOff;
44028    }
44029  }
44030
44031  /* Unless the pager is in noSync mode, the journal file was just
44032  ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
44033  ** all pages.
44034  */
44035  sqlite3PcacheClearSyncFlags(pPager->pPCache);
44036  pPager->eState = PAGER_WRITER_DBMOD;
44037  assert( assert_pager_state(pPager) );
44038  return SQLITE_OK;
44039}
44040
44041/*
44042** The argument is the first in a linked list of dirty pages connected
44043** by the PgHdr.pDirty pointer. This function writes each one of the
44044** in-memory pages in the list to the database file. The argument may
44045** be NULL, representing an empty list. In this case this function is
44046** a no-op.
44047**
44048** The pager must hold at least a RESERVED lock when this function
44049** is called. Before writing anything to the database file, this lock
44050** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
44051** SQLITE_BUSY is returned and no data is written to the database file.
44052**
44053** If the pager is a temp-file pager and the actual file-system file
44054** is not yet open, it is created and opened before any data is
44055** written out.
44056**
44057** Once the lock has been upgraded and, if necessary, the file opened,
44058** the pages are written out to the database file in list order. Writing
44059** a page is skipped if it meets either of the following criteria:
44060**
44061**   * The page number is greater than Pager.dbSize, or
44062**   * The PGHDR_DONT_WRITE flag is set on the page.
44063**
44064** If writing out a page causes the database file to grow, Pager.dbFileSize
44065** is updated accordingly. If page 1 is written out, then the value cached
44066** in Pager.dbFileVers[] is updated to match the new value stored in
44067** the database file.
44068**
44069** If everything is successful, SQLITE_OK is returned. If an IO error
44070** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
44071** be obtained, SQLITE_BUSY is returned.
44072*/
44073static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
44074  int rc = SQLITE_OK;                  /* Return code */
44075
44076  /* This function is only called for rollback pagers in WRITER_DBMOD state. */
44077  assert( !pagerUseWal(pPager) );
44078  assert( pPager->eState==PAGER_WRITER_DBMOD );
44079  assert( pPager->eLock==EXCLUSIVE_LOCK );
44080
44081  /* If the file is a temp-file has not yet been opened, open it now. It
44082  ** is not possible for rc to be other than SQLITE_OK if this branch
44083  ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
44084  */
44085  if( !isOpen(pPager->fd) ){
44086    assert( pPager->tempFile && rc==SQLITE_OK );
44087    rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
44088  }
44089
44090  /* Before the first write, give the VFS a hint of what the final
44091  ** file size will be.
44092  */
44093  assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
44094  if( rc==SQLITE_OK
44095   && pPager->dbHintSize<pPager->dbSize
44096   && (pList->pDirty || pList->pgno>pPager->dbHintSize)
44097  ){
44098    sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
44099    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
44100    pPager->dbHintSize = pPager->dbSize;
44101  }
44102
44103  while( rc==SQLITE_OK && pList ){
44104    Pgno pgno = pList->pgno;
44105
44106    /* If there are dirty pages in the page cache with page numbers greater
44107    ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
44108    ** make the file smaller (presumably by auto-vacuum code). Do not write
44109    ** any such pages to the file.
44110    **
44111    ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
44112    ** set (set by sqlite3PagerDontWrite()).
44113    */
44114    if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
44115      i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
44116      char *pData;                                   /* Data to write */
44117
44118      assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
44119      if( pList->pgno==1 ) pager_write_changecounter(pList);
44120
44121      /* Encode the database */
44122      CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
44123
44124      /* Write out the page data. */
44125      rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
44126
44127      /* If page 1 was just written, update Pager.dbFileVers to match
44128      ** the value now stored in the database file. If writing this
44129      ** page caused the database file to grow, update dbFileSize.
44130      */
44131      if( pgno==1 ){
44132        memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
44133      }
44134      if( pgno>pPager->dbFileSize ){
44135        pPager->dbFileSize = pgno;
44136      }
44137      pPager->aStat[PAGER_STAT_WRITE]++;
44138
44139      /* Update any backup objects copying the contents of this pager. */
44140      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
44141
44142      PAGERTRACE(("STORE %d page %d hash(%08x)\n",
44143                   PAGERID(pPager), pgno, pager_pagehash(pList)));
44144      IOTRACE(("PGOUT %p %d\n", pPager, pgno));
44145      PAGER_INCR(sqlite3_pager_writedb_count);
44146    }else{
44147      PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
44148    }
44149    pager_set_pagehash(pList);
44150    pList = pList->pDirty;
44151  }
44152
44153  return rc;
44154}
44155
44156/*
44157** Ensure that the sub-journal file is open. If it is already open, this
44158** function is a no-op.
44159**
44160** SQLITE_OK is returned if everything goes according to plan. An
44161** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
44162** fails.
44163*/
44164static int openSubJournal(Pager *pPager){
44165  int rc = SQLITE_OK;
44166  if( !isOpen(pPager->sjfd) ){
44167    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
44168      sqlite3MemJournalOpen(pPager->sjfd);
44169    }else{
44170      rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
44171    }
44172  }
44173  return rc;
44174}
44175
44176/*
44177** Append a record of the current state of page pPg to the sub-journal.
44178** It is the callers responsibility to use subjRequiresPage() to check
44179** that it is really required before calling this function.
44180**
44181** If successful, set the bit corresponding to pPg->pgno in the bitvecs
44182** for all open savepoints before returning.
44183**
44184** This function returns SQLITE_OK if everything is successful, an IO
44185** error code if the attempt to write to the sub-journal fails, or
44186** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
44187** bitvec.
44188*/
44189static int subjournalPage(PgHdr *pPg){
44190  int rc = SQLITE_OK;
44191  Pager *pPager = pPg->pPager;
44192  if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
44193
44194    /* Open the sub-journal, if it has not already been opened */
44195    assert( pPager->useJournal );
44196    assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
44197    assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
44198    assert( pagerUseWal(pPager)
44199         || pageInJournal(pPager, pPg)
44200         || pPg->pgno>pPager->dbOrigSize
44201    );
44202    rc = openSubJournal(pPager);
44203
44204    /* If the sub-journal was opened successfully (or was already open),
44205    ** write the journal record into the file.  */
44206    if( rc==SQLITE_OK ){
44207      void *pData = pPg->pData;
44208      i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
44209      char *pData2;
44210
44211      CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
44212      PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
44213      rc = write32bits(pPager->sjfd, offset, pPg->pgno);
44214      if( rc==SQLITE_OK ){
44215        rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
44216      }
44217    }
44218  }
44219  if( rc==SQLITE_OK ){
44220    pPager->nSubRec++;
44221    assert( pPager->nSavepoint>0 );
44222    rc = addToSavepointBitvecs(pPager, pPg->pgno);
44223  }
44224  return rc;
44225}
44226
44227/*
44228** This function is called by the pcache layer when it has reached some
44229** soft memory limit. The first argument is a pointer to a Pager object
44230** (cast as a void*). The pager is always 'purgeable' (not an in-memory
44231** database). The second argument is a reference to a page that is
44232** currently dirty but has no outstanding references. The page
44233** is always associated with the Pager object passed as the first
44234** argument.
44235**
44236** The job of this function is to make pPg clean by writing its contents
44237** out to the database file, if possible. This may involve syncing the
44238** journal file.
44239**
44240** If successful, sqlite3PcacheMakeClean() is called on the page and
44241** SQLITE_OK returned. If an IO error occurs while trying to make the
44242** page clean, the IO error code is returned. If the page cannot be
44243** made clean for some other reason, but no error occurs, then SQLITE_OK
44244** is returned by sqlite3PcacheMakeClean() is not called.
44245*/
44246static int pagerStress(void *p, PgHdr *pPg){
44247  Pager *pPager = (Pager *)p;
44248  int rc = SQLITE_OK;
44249
44250  assert( pPg->pPager==pPager );
44251  assert( pPg->flags&PGHDR_DIRTY );
44252
44253  /* The doNotSpill NOSYNC bit is set during times when doing a sync of
44254  ** journal (and adding a new header) is not allowed.  This occurs
44255  ** during calls to sqlite3PagerWrite() while trying to journal multiple
44256  ** pages belonging to the same sector.
44257  **
44258  ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
44259  ** regardless of whether or not a sync is required.  This is set during
44260  ** a rollback or by user request, respectively.
44261  **
44262  ** Spilling is also prohibited when in an error state since that could
44263  ** lead to database corruption.   In the current implementaton it
44264  ** is impossible for sqlite3PcacheFetch() to be called with createFlag==1
44265  ** while in the error state, hence it is impossible for this routine to
44266  ** be called in the error state.  Nevertheless, we include a NEVER()
44267  ** test for the error state as a safeguard against future changes.
44268  */
44269  if( NEVER(pPager->errCode) ) return SQLITE_OK;
44270  testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
44271  testcase( pPager->doNotSpill & SPILLFLAG_OFF );
44272  testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
44273  if( pPager->doNotSpill
44274   && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
44275      || (pPg->flags & PGHDR_NEED_SYNC)!=0)
44276  ){
44277    return SQLITE_OK;
44278  }
44279
44280  pPg->pDirty = 0;
44281  if( pagerUseWal(pPager) ){
44282    /* Write a single frame for this page to the log. */
44283    if( subjRequiresPage(pPg) ){
44284      rc = subjournalPage(pPg);
44285    }
44286    if( rc==SQLITE_OK ){
44287      rc = pagerWalFrames(pPager, pPg, 0, 0);
44288    }
44289  }else{
44290
44291    /* Sync the journal file if required. */
44292    if( pPg->flags&PGHDR_NEED_SYNC
44293     || pPager->eState==PAGER_WRITER_CACHEMOD
44294    ){
44295      rc = syncJournal(pPager, 1);
44296    }
44297
44298    /* If the page number of this page is larger than the current size of
44299    ** the database image, it may need to be written to the sub-journal.
44300    ** This is because the call to pager_write_pagelist() below will not
44301    ** actually write data to the file in this case.
44302    **
44303    ** Consider the following sequence of events:
44304    **
44305    **   BEGIN;
44306    **     <journal page X>
44307    **     <modify page X>
44308    **     SAVEPOINT sp;
44309    **       <shrink database file to Y pages>
44310    **       pagerStress(page X)
44311    **     ROLLBACK TO sp;
44312    **
44313    ** If (X>Y), then when pagerStress is called page X will not be written
44314    ** out to the database file, but will be dropped from the cache. Then,
44315    ** following the "ROLLBACK TO sp" statement, reading page X will read
44316    ** data from the database file. This will be the copy of page X as it
44317    ** was when the transaction started, not as it was when "SAVEPOINT sp"
44318    ** was executed.
44319    **
44320    ** The solution is to write the current data for page X into the
44321    ** sub-journal file now (if it is not already there), so that it will
44322    ** be restored to its current value when the "ROLLBACK TO sp" is
44323    ** executed.
44324    */
44325    if( NEVER(
44326        rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
44327    ) ){
44328      rc = subjournalPage(pPg);
44329    }
44330
44331    /* Write the contents of the page out to the database file. */
44332    if( rc==SQLITE_OK ){
44333      assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
44334      rc = pager_write_pagelist(pPager, pPg);
44335    }
44336  }
44337
44338  /* Mark the page as clean. */
44339  if( rc==SQLITE_OK ){
44340    PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
44341    sqlite3PcacheMakeClean(pPg);
44342  }
44343
44344  return pager_error(pPager, rc);
44345}
44346
44347
44348/*
44349** Allocate and initialize a new Pager object and put a pointer to it
44350** in *ppPager. The pager should eventually be freed by passing it
44351** to sqlite3PagerClose().
44352**
44353** The zFilename argument is the path to the database file to open.
44354** If zFilename is NULL then a randomly-named temporary file is created
44355** and used as the file to be cached. Temporary files are be deleted
44356** automatically when they are closed. If zFilename is ":memory:" then
44357** all information is held in cache. It is never written to disk.
44358** This can be used to implement an in-memory database.
44359**
44360** The nExtra parameter specifies the number of bytes of space allocated
44361** along with each page reference. This space is available to the user
44362** via the sqlite3PagerGetExtra() API.
44363**
44364** The flags argument is used to specify properties that affect the
44365** operation of the pager. It should be passed some bitwise combination
44366** of the PAGER_* flags.
44367**
44368** The vfsFlags parameter is a bitmask to pass to the flags parameter
44369** of the xOpen() method of the supplied VFS when opening files.
44370**
44371** If the pager object is allocated and the specified file opened
44372** successfully, SQLITE_OK is returned and *ppPager set to point to
44373** the new pager object. If an error occurs, *ppPager is set to NULL
44374** and error code returned. This function may return SQLITE_NOMEM
44375** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
44376** various SQLITE_IO_XXX errors.
44377*/
44378SQLITE_PRIVATE int sqlite3PagerOpen(
44379  sqlite3_vfs *pVfs,       /* The virtual file system to use */
44380  Pager **ppPager,         /* OUT: Return the Pager structure here */
44381  const char *zFilename,   /* Name of the database file to open */
44382  int nExtra,              /* Extra bytes append to each in-memory page */
44383  int flags,               /* flags controlling this file */
44384  int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
44385  void (*xReinit)(DbPage*) /* Function to reinitialize pages */
44386){
44387  u8 *pPtr;
44388  Pager *pPager = 0;       /* Pager object to allocate and return */
44389  int rc = SQLITE_OK;      /* Return code */
44390  int tempFile = 0;        /* True for temp files (incl. in-memory files) */
44391  int memDb = 0;           /* True if this is an in-memory file */
44392  int readOnly = 0;        /* True if this is a read-only file */
44393  int journalFileSize;     /* Bytes to allocate for each journal fd */
44394  char *zPathname = 0;     /* Full path to database file */
44395  int nPathname = 0;       /* Number of bytes in zPathname */
44396  int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
44397  int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
44398  u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
44399  const char *zUri = 0;    /* URI args to copy */
44400  int nUri = 0;            /* Number of bytes of URI args at *zUri */
44401
44402  /* Figure out how much space is required for each journal file-handle
44403  ** (there are two of them, the main journal and the sub-journal). This
44404  ** is the maximum space required for an in-memory journal file handle
44405  ** and a regular journal file-handle. Note that a "regular journal-handle"
44406  ** may be a wrapper capable of caching the first portion of the journal
44407  ** file in memory to implement the atomic-write optimization (see
44408  ** source file journal.c).
44409  */
44410  if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
44411    journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
44412  }else{
44413    journalFileSize = ROUND8(sqlite3MemJournalSize());
44414  }
44415
44416  /* Set the output variable to NULL in case an error occurs. */
44417  *ppPager = 0;
44418
44419#ifndef SQLITE_OMIT_MEMORYDB
44420  if( flags & PAGER_MEMORY ){
44421    memDb = 1;
44422    if( zFilename && zFilename[0] ){
44423      zPathname = sqlite3DbStrDup(0, zFilename);
44424      if( zPathname==0  ) return SQLITE_NOMEM;
44425      nPathname = sqlite3Strlen30(zPathname);
44426      zFilename = 0;
44427    }
44428  }
44429#endif
44430
44431  /* Compute and store the full pathname in an allocated buffer pointed
44432  ** to by zPathname, length nPathname. Or, if this is a temporary file,
44433  ** leave both nPathname and zPathname set to 0.
44434  */
44435  if( zFilename && zFilename[0] ){
44436    const char *z;
44437    nPathname = pVfs->mxPathname+1;
44438    zPathname = sqlite3DbMallocRaw(0, nPathname*2);
44439    if( zPathname==0 ){
44440      return SQLITE_NOMEM;
44441    }
44442    zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
44443    rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
44444    nPathname = sqlite3Strlen30(zPathname);
44445    z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
44446    while( *z ){
44447      z += sqlite3Strlen30(z)+1;
44448      z += sqlite3Strlen30(z)+1;
44449    }
44450    nUri = (int)(&z[1] - zUri);
44451    assert( nUri>=0 );
44452    if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
44453      /* This branch is taken when the journal path required by
44454      ** the database being opened will be more than pVfs->mxPathname
44455      ** bytes in length. This means the database cannot be opened,
44456      ** as it will not be possible to open the journal file or even
44457      ** check for a hot-journal before reading.
44458      */
44459      rc = SQLITE_CANTOPEN_BKPT;
44460    }
44461    if( rc!=SQLITE_OK ){
44462      sqlite3DbFree(0, zPathname);
44463      return rc;
44464    }
44465  }
44466
44467  /* Allocate memory for the Pager structure, PCache object, the
44468  ** three file descriptors, the database file name and the journal
44469  ** file name. The layout in memory is as follows:
44470  **
44471  **     Pager object                    (sizeof(Pager) bytes)
44472  **     PCache object                   (sqlite3PcacheSize() bytes)
44473  **     Database file handle            (pVfs->szOsFile bytes)
44474  **     Sub-journal file handle         (journalFileSize bytes)
44475  **     Main journal file handle        (journalFileSize bytes)
44476  **     Database file name              (nPathname+1 bytes)
44477  **     Journal file name               (nPathname+8+1 bytes)
44478  */
44479  pPtr = (u8 *)sqlite3MallocZero(
44480    ROUND8(sizeof(*pPager)) +      /* Pager structure */
44481    ROUND8(pcacheSize) +           /* PCache object */
44482    ROUND8(pVfs->szOsFile) +       /* The main db file */
44483    journalFileSize * 2 +          /* The two journal files */
44484    nPathname + 1 + nUri +         /* zFilename */
44485    nPathname + 8 + 2              /* zJournal */
44486#ifndef SQLITE_OMIT_WAL
44487    + nPathname + 4 + 2            /* zWal */
44488#endif
44489  );
44490  assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
44491  if( !pPtr ){
44492    sqlite3DbFree(0, zPathname);
44493    return SQLITE_NOMEM;
44494  }
44495  pPager =              (Pager*)(pPtr);
44496  pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
44497  pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
44498  pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
44499  pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
44500  pPager->zFilename =    (char*)(pPtr += journalFileSize);
44501  assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
44502
44503  /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
44504  if( zPathname ){
44505    assert( nPathname>0 );
44506    pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
44507    memcpy(pPager->zFilename, zPathname, nPathname);
44508    if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
44509    memcpy(pPager->zJournal, zPathname, nPathname);
44510    memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
44511    sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
44512#ifndef SQLITE_OMIT_WAL
44513    pPager->zWal = &pPager->zJournal[nPathname+8+1];
44514    memcpy(pPager->zWal, zPathname, nPathname);
44515    memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
44516    sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
44517#endif
44518    sqlite3DbFree(0, zPathname);
44519  }
44520  pPager->pVfs = pVfs;
44521  pPager->vfsFlags = vfsFlags;
44522
44523  /* Open the pager file.
44524  */
44525  if( zFilename && zFilename[0] ){
44526    int fout = 0;                    /* VFS flags returned by xOpen() */
44527    rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
44528    assert( !memDb );
44529    readOnly = (fout&SQLITE_OPEN_READONLY);
44530
44531    /* If the file was successfully opened for read/write access,
44532    ** choose a default page size in case we have to create the
44533    ** database file. The default page size is the maximum of:
44534    **
44535    **    + SQLITE_DEFAULT_PAGE_SIZE,
44536    **    + The value returned by sqlite3OsSectorSize()
44537    **    + The largest page size that can be written atomically.
44538    */
44539    if( rc==SQLITE_OK ){
44540      int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
44541      if( !readOnly ){
44542        setSectorSize(pPager);
44543        assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
44544        if( szPageDflt<pPager->sectorSize ){
44545          if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
44546            szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
44547          }else{
44548            szPageDflt = (u32)pPager->sectorSize;
44549          }
44550        }
44551#ifdef SQLITE_ENABLE_ATOMIC_WRITE
44552        {
44553          int ii;
44554          assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
44555          assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
44556          assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
44557          for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
44558            if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
44559              szPageDflt = ii;
44560            }
44561          }
44562        }
44563#endif
44564      }
44565      pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
44566      if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
44567       || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
44568          vfsFlags |= SQLITE_OPEN_READONLY;
44569          goto act_like_temp_file;
44570      }
44571    }
44572  }else{
44573    /* If a temporary file is requested, it is not opened immediately.
44574    ** In this case we accept the default page size and delay actually
44575    ** opening the file until the first call to OsWrite().
44576    **
44577    ** This branch is also run for an in-memory database. An in-memory
44578    ** database is the same as a temp-file that is never written out to
44579    ** disk and uses an in-memory rollback journal.
44580    **
44581    ** This branch also runs for files marked as immutable.
44582    */
44583act_like_temp_file:
44584    tempFile = 1;
44585    pPager->eState = PAGER_READER;     /* Pretend we already have a lock */
44586    pPager->eLock = EXCLUSIVE_LOCK;    /* Pretend we are in EXCLUSIVE locking mode */
44587    pPager->noLock = 1;                /* Do no locking */
44588    readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
44589  }
44590
44591  /* The following call to PagerSetPagesize() serves to set the value of
44592  ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
44593  */
44594  if( rc==SQLITE_OK ){
44595    assert( pPager->memDb==0 );
44596    rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
44597    testcase( rc!=SQLITE_OK );
44598  }
44599
44600  /* If an error occurred in either of the blocks above, free the
44601  ** Pager structure and close the file.
44602  */
44603  if( rc!=SQLITE_OK ){
44604    assert( !pPager->pTmpSpace );
44605    sqlite3OsClose(pPager->fd);
44606    sqlite3_free(pPager);
44607    return rc;
44608  }
44609
44610  /* Initialize the PCache object. */
44611  assert( nExtra<1000 );
44612  nExtra = ROUND8(nExtra);
44613  sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
44614                    !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
44615
44616  PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
44617  IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
44618
44619  pPager->useJournal = (u8)useJournal;
44620  /* pPager->stmtOpen = 0; */
44621  /* pPager->stmtInUse = 0; */
44622  /* pPager->nRef = 0; */
44623  /* pPager->stmtSize = 0; */
44624  /* pPager->stmtJSize = 0; */
44625  /* pPager->nPage = 0; */
44626  pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
44627  /* pPager->state = PAGER_UNLOCK; */
44628  /* pPager->errMask = 0; */
44629  pPager->tempFile = (u8)tempFile;
44630  assert( tempFile==PAGER_LOCKINGMODE_NORMAL
44631          || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
44632  assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
44633  pPager->exclusiveMode = (u8)tempFile;
44634  pPager->changeCountDone = pPager->tempFile;
44635  pPager->memDb = (u8)memDb;
44636  pPager->readOnly = (u8)readOnly;
44637  assert( useJournal || pPager->tempFile );
44638  pPager->noSync = pPager->tempFile;
44639  if( pPager->noSync ){
44640    assert( pPager->fullSync==0 );
44641    assert( pPager->syncFlags==0 );
44642    assert( pPager->walSyncFlags==0 );
44643    assert( pPager->ckptSyncFlags==0 );
44644  }else{
44645    pPager->fullSync = 1;
44646    pPager->syncFlags = SQLITE_SYNC_NORMAL;
44647    pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
44648    pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
44649  }
44650  /* pPager->pFirst = 0; */
44651  /* pPager->pFirstSynced = 0; */
44652  /* pPager->pLast = 0; */
44653  pPager->nExtra = (u16)nExtra;
44654  pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
44655  assert( isOpen(pPager->fd) || tempFile );
44656  setSectorSize(pPager);
44657  if( !useJournal ){
44658    pPager->journalMode = PAGER_JOURNALMODE_OFF;
44659  }else if( memDb ){
44660    pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
44661  }
44662  /* pPager->xBusyHandler = 0; */
44663  /* pPager->pBusyHandlerArg = 0; */
44664  pPager->xReiniter = xReinit;
44665  /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
44666  /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
44667
44668  *ppPager = pPager;
44669  return SQLITE_OK;
44670}
44671
44672
44673/* Verify that the database file has not be deleted or renamed out from
44674** under the pager.  Return SQLITE_OK if the database is still were it ought
44675** to be on disk.  Return non-zero (SQLITE_READONLY_DBMOVED or some other error
44676** code from sqlite3OsAccess()) if the database has gone missing.
44677*/
44678static int databaseIsUnmoved(Pager *pPager){
44679  int bHasMoved = 0;
44680  int rc;
44681
44682  if( pPager->tempFile ) return SQLITE_OK;
44683  if( pPager->dbSize==0 ) return SQLITE_OK;
44684  assert( pPager->zFilename && pPager->zFilename[0] );
44685  rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
44686  if( rc==SQLITE_NOTFOUND ){
44687    /* If the HAS_MOVED file-control is unimplemented, assume that the file
44688    ** has not been moved.  That is the historical behavior of SQLite: prior to
44689    ** version 3.8.3, it never checked */
44690    rc = SQLITE_OK;
44691  }else if( rc==SQLITE_OK && bHasMoved ){
44692    rc = SQLITE_READONLY_DBMOVED;
44693  }
44694  return rc;
44695}
44696
44697
44698/*
44699** This function is called after transitioning from PAGER_UNLOCK to
44700** PAGER_SHARED state. It tests if there is a hot journal present in
44701** the file-system for the given pager. A hot journal is one that
44702** needs to be played back. According to this function, a hot-journal
44703** file exists if the following criteria are met:
44704**
44705**   * The journal file exists in the file system, and
44706**   * No process holds a RESERVED or greater lock on the database file, and
44707**   * The database file itself is greater than 0 bytes in size, and
44708**   * The first byte of the journal file exists and is not 0x00.
44709**
44710** If the current size of the database file is 0 but a journal file
44711** exists, that is probably an old journal left over from a prior
44712** database with the same name. In this case the journal file is
44713** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
44714** is returned.
44715**
44716** This routine does not check if there is a master journal filename
44717** at the end of the file. If there is, and that master journal file
44718** does not exist, then the journal file is not really hot. In this
44719** case this routine will return a false-positive. The pager_playback()
44720** routine will discover that the journal file is not really hot and
44721** will not roll it back.
44722**
44723** If a hot-journal file is found to exist, *pExists is set to 1 and
44724** SQLITE_OK returned. If no hot-journal file is present, *pExists is
44725** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
44726** to determine whether or not a hot-journal file exists, the IO error
44727** code is returned and the value of *pExists is undefined.
44728*/
44729static int hasHotJournal(Pager *pPager, int *pExists){
44730  sqlite3_vfs * const pVfs = pPager->pVfs;
44731  int rc = SQLITE_OK;           /* Return code */
44732  int exists = 1;               /* True if a journal file is present */
44733  int jrnlOpen = !!isOpen(pPager->jfd);
44734
44735  assert( pPager->useJournal );
44736  assert( isOpen(pPager->fd) );
44737  assert( pPager->eState==PAGER_OPEN );
44738
44739  assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
44740    SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
44741  ));
44742
44743  *pExists = 0;
44744  if( !jrnlOpen ){
44745    rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
44746  }
44747  if( rc==SQLITE_OK && exists ){
44748    int locked = 0;             /* True if some process holds a RESERVED lock */
44749
44750    /* Race condition here:  Another process might have been holding the
44751    ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
44752    ** call above, but then delete the journal and drop the lock before
44753    ** we get to the following sqlite3OsCheckReservedLock() call.  If that
44754    ** is the case, this routine might think there is a hot journal when
44755    ** in fact there is none.  This results in a false-positive which will
44756    ** be dealt with by the playback routine.  Ticket #3883.
44757    */
44758    rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
44759    if( rc==SQLITE_OK && !locked ){
44760      Pgno nPage;                 /* Number of pages in database file */
44761
44762      rc = pagerPagecount(pPager, &nPage);
44763      if( rc==SQLITE_OK ){
44764        /* If the database is zero pages in size, that means that either (1) the
44765        ** journal is a remnant from a prior database with the same name where
44766        ** the database file but not the journal was deleted, or (2) the initial
44767        ** transaction that populates a new database is being rolled back.
44768        ** In either case, the journal file can be deleted.  However, take care
44769        ** not to delete the journal file if it is already open due to
44770        ** journal_mode=PERSIST.
44771        */
44772        if( nPage==0 && !jrnlOpen ){
44773          sqlite3BeginBenignMalloc();
44774          if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
44775            sqlite3OsDelete(pVfs, pPager->zJournal, 0);
44776            if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
44777          }
44778          sqlite3EndBenignMalloc();
44779        }else{
44780          /* The journal file exists and no other connection has a reserved
44781          ** or greater lock on the database file. Now check that there is
44782          ** at least one non-zero bytes at the start of the journal file.
44783          ** If there is, then we consider this journal to be hot. If not,
44784          ** it can be ignored.
44785          */
44786          if( !jrnlOpen ){
44787            int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
44788            rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
44789          }
44790          if( rc==SQLITE_OK ){
44791            u8 first = 0;
44792            rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
44793            if( rc==SQLITE_IOERR_SHORT_READ ){
44794              rc = SQLITE_OK;
44795            }
44796            if( !jrnlOpen ){
44797              sqlite3OsClose(pPager->jfd);
44798            }
44799            *pExists = (first!=0);
44800          }else if( rc==SQLITE_CANTOPEN ){
44801            /* If we cannot open the rollback journal file in order to see if
44802            ** its has a zero header, that might be due to an I/O error, or
44803            ** it might be due to the race condition described above and in
44804            ** ticket #3883.  Either way, assume that the journal is hot.
44805            ** This might be a false positive.  But if it is, then the
44806            ** automatic journal playback and recovery mechanism will deal
44807            ** with it under an EXCLUSIVE lock where we do not need to
44808            ** worry so much with race conditions.
44809            */
44810            *pExists = 1;
44811            rc = SQLITE_OK;
44812          }
44813        }
44814      }
44815    }
44816  }
44817
44818  return rc;
44819}
44820
44821/*
44822** This function is called to obtain a shared lock on the database file.
44823** It is illegal to call sqlite3PagerAcquire() until after this function
44824** has been successfully called. If a shared-lock is already held when
44825** this function is called, it is a no-op.
44826**
44827** The following operations are also performed by this function.
44828**
44829**   1) If the pager is currently in PAGER_OPEN state (no lock held
44830**      on the database file), then an attempt is made to obtain a
44831**      SHARED lock on the database file. Immediately after obtaining
44832**      the SHARED lock, the file-system is checked for a hot-journal,
44833**      which is played back if present. Following any hot-journal
44834**      rollback, the contents of the cache are validated by checking
44835**      the 'change-counter' field of the database file header and
44836**      discarded if they are found to be invalid.
44837**
44838**   2) If the pager is running in exclusive-mode, and there are currently
44839**      no outstanding references to any pages, and is in the error state,
44840**      then an attempt is made to clear the error state by discarding
44841**      the contents of the page cache and rolling back any open journal
44842**      file.
44843**
44844** If everything is successful, SQLITE_OK is returned. If an IO error
44845** occurs while locking the database, checking for a hot-journal file or
44846** rolling back a journal file, the IO error code is returned.
44847*/
44848SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
44849  int rc = SQLITE_OK;                /* Return code */
44850
44851  /* This routine is only called from b-tree and only when there are no
44852  ** outstanding pages. This implies that the pager state should either
44853  ** be OPEN or READER. READER is only possible if the pager is or was in
44854  ** exclusive access mode.
44855  */
44856  assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
44857  assert( assert_pager_state(pPager) );
44858  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
44859  if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
44860
44861  if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
44862    int bHotJournal = 1;          /* True if there exists a hot journal-file */
44863
44864    assert( !MEMDB );
44865
44866    rc = pager_wait_on_lock(pPager, SHARED_LOCK);
44867    if( rc!=SQLITE_OK ){
44868      assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
44869      goto failed;
44870    }
44871
44872    /* If a journal file exists, and there is no RESERVED lock on the
44873    ** database file, then it either needs to be played back or deleted.
44874    */
44875    if( pPager->eLock<=SHARED_LOCK ){
44876      rc = hasHotJournal(pPager, &bHotJournal);
44877    }
44878    if( rc!=SQLITE_OK ){
44879      goto failed;
44880    }
44881    if( bHotJournal ){
44882      if( pPager->readOnly ){
44883        rc = SQLITE_READONLY_ROLLBACK;
44884        goto failed;
44885      }
44886
44887      /* Get an EXCLUSIVE lock on the database file. At this point it is
44888      ** important that a RESERVED lock is not obtained on the way to the
44889      ** EXCLUSIVE lock. If it were, another process might open the
44890      ** database file, detect the RESERVED lock, and conclude that the
44891      ** database is safe to read while this process is still rolling the
44892      ** hot-journal back.
44893      **
44894      ** Because the intermediate RESERVED lock is not requested, any
44895      ** other process attempting to access the database file will get to
44896      ** this point in the code and fail to obtain its own EXCLUSIVE lock
44897      ** on the database file.
44898      **
44899      ** Unless the pager is in locking_mode=exclusive mode, the lock is
44900      ** downgraded to SHARED_LOCK before this function returns.
44901      */
44902      rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
44903      if( rc!=SQLITE_OK ){
44904        goto failed;
44905      }
44906
44907      /* If it is not already open and the file exists on disk, open the
44908      ** journal for read/write access. Write access is required because
44909      ** in exclusive-access mode the file descriptor will be kept open
44910      ** and possibly used for a transaction later on. Also, write-access
44911      ** is usually required to finalize the journal in journal_mode=persist
44912      ** mode (and also for journal_mode=truncate on some systems).
44913      **
44914      ** If the journal does not exist, it usually means that some
44915      ** other connection managed to get in and roll it back before
44916      ** this connection obtained the exclusive lock above. Or, it
44917      ** may mean that the pager was in the error-state when this
44918      ** function was called and the journal file does not exist.
44919      */
44920      if( !isOpen(pPager->jfd) ){
44921        sqlite3_vfs * const pVfs = pPager->pVfs;
44922        int bExists;              /* True if journal file exists */
44923        rc = sqlite3OsAccess(
44924            pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
44925        if( rc==SQLITE_OK && bExists ){
44926          int fout = 0;
44927          int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
44928          assert( !pPager->tempFile );
44929          rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
44930          assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
44931          if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
44932            rc = SQLITE_CANTOPEN_BKPT;
44933            sqlite3OsClose(pPager->jfd);
44934          }
44935        }
44936      }
44937
44938      /* Playback and delete the journal.  Drop the database write
44939      ** lock and reacquire the read lock. Purge the cache before
44940      ** playing back the hot-journal so that we don't end up with
44941      ** an inconsistent cache.  Sync the hot journal before playing
44942      ** it back since the process that crashed and left the hot journal
44943      ** probably did not sync it and we are required to always sync
44944      ** the journal before playing it back.
44945      */
44946      if( isOpen(pPager->jfd) ){
44947        assert( rc==SQLITE_OK );
44948        rc = pagerSyncHotJournal(pPager);
44949        if( rc==SQLITE_OK ){
44950          rc = pager_playback(pPager, 1);
44951          pPager->eState = PAGER_OPEN;
44952        }
44953      }else if( !pPager->exclusiveMode ){
44954        pagerUnlockDb(pPager, SHARED_LOCK);
44955      }
44956
44957      if( rc!=SQLITE_OK ){
44958        /* This branch is taken if an error occurs while trying to open
44959        ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
44960        ** pager_unlock() routine will be called before returning to unlock
44961        ** the file. If the unlock attempt fails, then Pager.eLock must be
44962        ** set to UNKNOWN_LOCK (see the comment above the #define for
44963        ** UNKNOWN_LOCK above for an explanation).
44964        **
44965        ** In order to get pager_unlock() to do this, set Pager.eState to
44966        ** PAGER_ERROR now. This is not actually counted as a transition
44967        ** to ERROR state in the state diagram at the top of this file,
44968        ** since we know that the same call to pager_unlock() will very
44969        ** shortly transition the pager object to the OPEN state. Calling
44970        ** assert_pager_state() would fail now, as it should not be possible
44971        ** to be in ERROR state when there are zero outstanding page
44972        ** references.
44973        */
44974        pager_error(pPager, rc);
44975        goto failed;
44976      }
44977
44978      assert( pPager->eState==PAGER_OPEN );
44979      assert( (pPager->eLock==SHARED_LOCK)
44980           || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
44981      );
44982    }
44983
44984    if( !pPager->tempFile && (
44985        pPager->pBackup
44986     || sqlite3PcachePagecount(pPager->pPCache)>0
44987     || USEFETCH(pPager)
44988    )){
44989      /* The shared-lock has just been acquired on the database file
44990      ** and there are already pages in the cache (from a previous
44991      ** read or write transaction).  Check to see if the database
44992      ** has been modified.  If the database has changed, flush the
44993      ** cache.
44994      **
44995      ** Database changes is detected by looking at 15 bytes beginning
44996      ** at offset 24 into the file.  The first 4 of these 16 bytes are
44997      ** a 32-bit counter that is incremented with each change.  The
44998      ** other bytes change randomly with each file change when
44999      ** a codec is in use.
45000      **
45001      ** There is a vanishingly small chance that a change will not be
45002      ** detected.  The chance of an undetected change is so small that
45003      ** it can be neglected.
45004      */
45005      Pgno nPage = 0;
45006      char dbFileVers[sizeof(pPager->dbFileVers)];
45007
45008      rc = pagerPagecount(pPager, &nPage);
45009      if( rc ) goto failed;
45010
45011      if( nPage>0 ){
45012        IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
45013        rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
45014        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
45015          goto failed;
45016        }
45017      }else{
45018        memset(dbFileVers, 0, sizeof(dbFileVers));
45019      }
45020
45021      if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
45022        pager_reset(pPager);
45023
45024        /* Unmap the database file. It is possible that external processes
45025        ** may have truncated the database file and then extended it back
45026        ** to its original size while this process was not holding a lock.
45027        ** In this case there may exist a Pager.pMap mapping that appears
45028        ** to be the right size but is not actually valid. Avoid this
45029        ** possibility by unmapping the db here. */
45030        if( USEFETCH(pPager) ){
45031          sqlite3OsUnfetch(pPager->fd, 0, 0);
45032        }
45033      }
45034    }
45035
45036    /* If there is a WAL file in the file-system, open this database in WAL
45037    ** mode. Otherwise, the following function call is a no-op.
45038    */
45039    rc = pagerOpenWalIfPresent(pPager);
45040#ifndef SQLITE_OMIT_WAL
45041    assert( pPager->pWal==0 || rc==SQLITE_OK );
45042#endif
45043  }
45044
45045  if( pagerUseWal(pPager) ){
45046    assert( rc==SQLITE_OK );
45047    rc = pagerBeginReadTransaction(pPager);
45048  }
45049
45050  if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
45051    rc = pagerPagecount(pPager, &pPager->dbSize);
45052  }
45053
45054 failed:
45055  if( rc!=SQLITE_OK ){
45056    assert( !MEMDB );
45057    pager_unlock(pPager);
45058    assert( pPager->eState==PAGER_OPEN );
45059  }else{
45060    pPager->eState = PAGER_READER;
45061  }
45062  return rc;
45063}
45064
45065/*
45066** If the reference count has reached zero, rollback any active
45067** transaction and unlock the pager.
45068**
45069** Except, in locking_mode=EXCLUSIVE when there is nothing to in
45070** the rollback journal, the unlock is not performed and there is
45071** nothing to rollback, so this routine is a no-op.
45072*/
45073static void pagerUnlockIfUnused(Pager *pPager){
45074  if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
45075    pagerUnlockAndRollback(pPager);
45076  }
45077}
45078
45079/*
45080** Acquire a reference to page number pgno in pager pPager (a page
45081** reference has type DbPage*). If the requested reference is
45082** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
45083**
45084** If the requested page is already in the cache, it is returned.
45085** Otherwise, a new page object is allocated and populated with data
45086** read from the database file. In some cases, the pcache module may
45087** choose not to allocate a new page object and may reuse an existing
45088** object with no outstanding references.
45089**
45090** The extra data appended to a page is always initialized to zeros the
45091** first time a page is loaded into memory. If the page requested is
45092** already in the cache when this function is called, then the extra
45093** data is left as it was when the page object was last used.
45094**
45095** If the database image is smaller than the requested page or if a
45096** non-zero value is passed as the noContent parameter and the
45097** requested page is not already stored in the cache, then no
45098** actual disk read occurs. In this case the memory image of the
45099** page is initialized to all zeros.
45100**
45101** If noContent is true, it means that we do not care about the contents
45102** of the page. This occurs in two scenarios:
45103**
45104**   a) When reading a free-list leaf page from the database, and
45105**
45106**   b) When a savepoint is being rolled back and we need to load
45107**      a new page into the cache to be filled with the data read
45108**      from the savepoint journal.
45109**
45110** If noContent is true, then the data returned is zeroed instead of
45111** being read from the database. Additionally, the bits corresponding
45112** to pgno in Pager.pInJournal (bitvec of pages already written to the
45113** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
45114** savepoints are set. This means if the page is made writable at any
45115** point in the future, using a call to sqlite3PagerWrite(), its contents
45116** will not be journaled. This saves IO.
45117**
45118** The acquisition might fail for several reasons.  In all cases,
45119** an appropriate error code is returned and *ppPage is set to NULL.
45120**
45121** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
45122** to find a page in the in-memory cache first.  If the page is not already
45123** in memory, this routine goes to disk to read it in whereas Lookup()
45124** just returns 0.  This routine acquires a read-lock the first time it
45125** has to go to disk, and could also playback an old journal if necessary.
45126** Since Lookup() never goes to disk, it never has to deal with locks
45127** or journal files.
45128*/
45129SQLITE_PRIVATE int sqlite3PagerAcquire(
45130  Pager *pPager,      /* The pager open on the database file */
45131  Pgno pgno,          /* Page number to fetch */
45132  DbPage **ppPage,    /* Write a pointer to the page here */
45133  int flags           /* PAGER_GET_XXX flags */
45134){
45135  int rc = SQLITE_OK;
45136  PgHdr *pPg = 0;
45137  u32 iFrame = 0;                 /* Frame to read from WAL file */
45138  const int noContent = (flags & PAGER_GET_NOCONTENT);
45139
45140  /* It is acceptable to use a read-only (mmap) page for any page except
45141  ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
45142  ** flag was specified by the caller. And so long as the db is not a
45143  ** temporary or in-memory database.  */
45144  const int bMmapOk = (pgno!=1 && USEFETCH(pPager)
45145   && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
45146#ifdef SQLITE_HAS_CODEC
45147   && pPager->xCodec==0
45148#endif
45149  );
45150
45151  assert( pPager->eState>=PAGER_READER );
45152  assert( assert_pager_state(pPager) );
45153  assert( noContent==0 || bMmapOk==0 );
45154
45155  if( pgno==0 ){
45156    return SQLITE_CORRUPT_BKPT;
45157  }
45158
45159  /* If the pager is in the error state, return an error immediately.
45160  ** Otherwise, request the page from the PCache layer. */
45161  if( pPager->errCode!=SQLITE_OK ){
45162    rc = pPager->errCode;
45163  }else{
45164
45165    if( bMmapOk && pagerUseWal(pPager) ){
45166      rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
45167      if( rc!=SQLITE_OK ) goto pager_acquire_err;
45168    }
45169
45170    if( bMmapOk && iFrame==0 ){
45171      void *pData = 0;
45172
45173      rc = sqlite3OsFetch(pPager->fd,
45174          (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
45175      );
45176
45177      if( rc==SQLITE_OK && pData ){
45178        if( pPager->eState>PAGER_READER ){
45179          (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
45180        }
45181        if( pPg==0 ){
45182          rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
45183        }else{
45184          sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
45185        }
45186        if( pPg ){
45187          assert( rc==SQLITE_OK );
45188          *ppPage = pPg;
45189          return SQLITE_OK;
45190        }
45191      }
45192      if( rc!=SQLITE_OK ){
45193        goto pager_acquire_err;
45194      }
45195    }
45196
45197    rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
45198  }
45199
45200  if( rc!=SQLITE_OK ){
45201    /* Either the call to sqlite3PcacheFetch() returned an error or the
45202    ** pager was already in the error-state when this function was called.
45203    ** Set pPg to 0 and jump to the exception handler.  */
45204    pPg = 0;
45205    goto pager_acquire_err;
45206  }
45207  assert( (*ppPage)->pgno==pgno );
45208  assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
45209
45210  if( (*ppPage)->pPager && !noContent ){
45211    /* In this case the pcache already contains an initialized copy of
45212    ** the page. Return without further ado.  */
45213    assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
45214    pPager->aStat[PAGER_STAT_HIT]++;
45215    return SQLITE_OK;
45216
45217  }else{
45218    /* The pager cache has created a new page. Its content needs to
45219    ** be initialized.  */
45220
45221    pPg = *ppPage;
45222    pPg->pPager = pPager;
45223
45224    /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
45225    ** number greater than this, or the unused locking-page, is requested. */
45226    if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
45227      rc = SQLITE_CORRUPT_BKPT;
45228      goto pager_acquire_err;
45229    }
45230
45231    if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
45232      if( pgno>pPager->mxPgno ){
45233        rc = SQLITE_FULL;
45234        goto pager_acquire_err;
45235      }
45236      if( noContent ){
45237        /* Failure to set the bits in the InJournal bit-vectors is benign.
45238        ** It merely means that we might do some extra work to journal a
45239        ** page that does not need to be journaled.  Nevertheless, be sure
45240        ** to test the case where a malloc error occurs while trying to set
45241        ** a bit in a bit vector.
45242        */
45243        sqlite3BeginBenignMalloc();
45244        if( pgno<=pPager->dbOrigSize ){
45245          TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
45246          testcase( rc==SQLITE_NOMEM );
45247        }
45248        TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
45249        testcase( rc==SQLITE_NOMEM );
45250        sqlite3EndBenignMalloc();
45251      }
45252      memset(pPg->pData, 0, pPager->pageSize);
45253      IOTRACE(("ZERO %p %d\n", pPager, pgno));
45254    }else{
45255      if( pagerUseWal(pPager) && bMmapOk==0 ){
45256        rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
45257        if( rc!=SQLITE_OK ) goto pager_acquire_err;
45258      }
45259      assert( pPg->pPager==pPager );
45260      pPager->aStat[PAGER_STAT_MISS]++;
45261      rc = readDbPage(pPg, iFrame);
45262      if( rc!=SQLITE_OK ){
45263        goto pager_acquire_err;
45264      }
45265    }
45266    pager_set_pagehash(pPg);
45267  }
45268
45269  return SQLITE_OK;
45270
45271pager_acquire_err:
45272  assert( rc!=SQLITE_OK );
45273  if( pPg ){
45274    sqlite3PcacheDrop(pPg);
45275  }
45276  pagerUnlockIfUnused(pPager);
45277
45278  *ppPage = 0;
45279  return rc;
45280}
45281
45282/*
45283** Acquire a page if it is already in the in-memory cache.  Do
45284** not read the page from disk.  Return a pointer to the page,
45285** or 0 if the page is not in cache.
45286**
45287** See also sqlite3PagerGet().  The difference between this routine
45288** and sqlite3PagerGet() is that _get() will go to the disk and read
45289** in the page if the page is not already in cache.  This routine
45290** returns NULL if the page is not in cache or if a disk I/O error
45291** has ever happened.
45292*/
45293SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
45294  PgHdr *pPg = 0;
45295  assert( pPager!=0 );
45296  assert( pgno!=0 );
45297  assert( pPager->pPCache!=0 );
45298  assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
45299  sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
45300  return pPg;
45301}
45302
45303/*
45304** Release a page reference.
45305**
45306** If the number of references to the page drop to zero, then the
45307** page is added to the LRU list.  When all references to all pages
45308** are released, a rollback occurs and the lock on the database is
45309** removed.
45310*/
45311SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
45312  Pager *pPager;
45313  assert( pPg!=0 );
45314  pPager = pPg->pPager;
45315  if( pPg->flags & PGHDR_MMAP ){
45316    pagerReleaseMapPage(pPg);
45317  }else{
45318    sqlite3PcacheRelease(pPg);
45319  }
45320  pagerUnlockIfUnused(pPager);
45321}
45322SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
45323  if( pPg ) sqlite3PagerUnrefNotNull(pPg);
45324}
45325
45326/*
45327** This function is called at the start of every write transaction.
45328** There must already be a RESERVED or EXCLUSIVE lock on the database
45329** file when this routine is called.
45330**
45331** Open the journal file for pager pPager and write a journal header
45332** to the start of it. If there are active savepoints, open the sub-journal
45333** as well. This function is only used when the journal file is being
45334** opened to write a rollback log for a transaction. It is not used
45335** when opening a hot journal file to roll it back.
45336**
45337** If the journal file is already open (as it may be in exclusive mode),
45338** then this function just writes a journal header to the start of the
45339** already open file.
45340**
45341** Whether or not the journal file is opened by this function, the
45342** Pager.pInJournal bitvec structure is allocated.
45343**
45344** Return SQLITE_OK if everything is successful. Otherwise, return
45345** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
45346** an IO error code if opening or writing the journal file fails.
45347*/
45348static int pager_open_journal(Pager *pPager){
45349  int rc = SQLITE_OK;                        /* Return code */
45350  sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
45351
45352  assert( pPager->eState==PAGER_WRITER_LOCKED );
45353  assert( assert_pager_state(pPager) );
45354  assert( pPager->pInJournal==0 );
45355
45356  /* If already in the error state, this function is a no-op.  But on
45357  ** the other hand, this routine is never called if we are already in
45358  ** an error state. */
45359  if( NEVER(pPager->errCode) ) return pPager->errCode;
45360
45361  if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
45362    pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
45363    if( pPager->pInJournal==0 ){
45364      return SQLITE_NOMEM;
45365    }
45366
45367    /* Open the journal file if it is not already open. */
45368    if( !isOpen(pPager->jfd) ){
45369      if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
45370        sqlite3MemJournalOpen(pPager->jfd);
45371      }else{
45372        const int flags =                   /* VFS flags to open journal file */
45373          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
45374          (pPager->tempFile ?
45375            (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
45376            (SQLITE_OPEN_MAIN_JOURNAL)
45377          );
45378
45379        /* Verify that the database still has the same name as it did when
45380        ** it was originally opened. */
45381        rc = databaseIsUnmoved(pPager);
45382        if( rc==SQLITE_OK ){
45383#ifdef SQLITE_ENABLE_ATOMIC_WRITE
45384          rc = sqlite3JournalOpen(
45385              pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
45386          );
45387#else
45388          rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
45389#endif
45390        }
45391      }
45392      assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
45393    }
45394
45395
45396    /* Write the first journal header to the journal file and open
45397    ** the sub-journal if necessary.
45398    */
45399    if( rc==SQLITE_OK ){
45400      /* TODO: Check if all of these are really required. */
45401      pPager->nRec = 0;
45402      pPager->journalOff = 0;
45403      pPager->setMaster = 0;
45404      pPager->journalHdr = 0;
45405      rc = writeJournalHdr(pPager);
45406    }
45407  }
45408
45409  if( rc!=SQLITE_OK ){
45410    sqlite3BitvecDestroy(pPager->pInJournal);
45411    pPager->pInJournal = 0;
45412  }else{
45413    assert( pPager->eState==PAGER_WRITER_LOCKED );
45414    pPager->eState = PAGER_WRITER_CACHEMOD;
45415  }
45416
45417  return rc;
45418}
45419
45420/*
45421** Begin a write-transaction on the specified pager object. If a
45422** write-transaction has already been opened, this function is a no-op.
45423**
45424** If the exFlag argument is false, then acquire at least a RESERVED
45425** lock on the database file. If exFlag is true, then acquire at least
45426** an EXCLUSIVE lock. If such a lock is already held, no locking
45427** functions need be called.
45428**
45429** If the subjInMemory argument is non-zero, then any sub-journal opened
45430** within this transaction will be opened as an in-memory file. This
45431** has no effect if the sub-journal is already opened (as it may be when
45432** running in exclusive mode) or if the transaction does not require a
45433** sub-journal. If the subjInMemory argument is zero, then any required
45434** sub-journal is implemented in-memory if pPager is an in-memory database,
45435** or using a temporary file otherwise.
45436*/
45437SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
45438  int rc = SQLITE_OK;
45439
45440  if( pPager->errCode ) return pPager->errCode;
45441  assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
45442  pPager->subjInMemory = (u8)subjInMemory;
45443
45444  if( ALWAYS(pPager->eState==PAGER_READER) ){
45445    assert( pPager->pInJournal==0 );
45446
45447    if( pagerUseWal(pPager) ){
45448      /* If the pager is configured to use locking_mode=exclusive, and an
45449      ** exclusive lock on the database is not already held, obtain it now.
45450      */
45451      if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
45452        rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
45453        if( rc!=SQLITE_OK ){
45454          return rc;
45455        }
45456        sqlite3WalExclusiveMode(pPager->pWal, 1);
45457      }
45458
45459      /* Grab the write lock on the log file. If successful, upgrade to
45460      ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
45461      ** The busy-handler is not invoked if another connection already
45462      ** holds the write-lock. If possible, the upper layer will call it.
45463      */
45464      rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
45465    }else{
45466      /* Obtain a RESERVED lock on the database file. If the exFlag parameter
45467      ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
45468      ** busy-handler callback can be used when upgrading to the EXCLUSIVE
45469      ** lock, but not when obtaining the RESERVED lock.
45470      */
45471      rc = pagerLockDb(pPager, RESERVED_LOCK);
45472      if( rc==SQLITE_OK && exFlag ){
45473        rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
45474      }
45475    }
45476
45477    if( rc==SQLITE_OK ){
45478      /* Change to WRITER_LOCKED state.
45479      **
45480      ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
45481      ** when it has an open transaction, but never to DBMOD or FINISHED.
45482      ** This is because in those states the code to roll back savepoint
45483      ** transactions may copy data from the sub-journal into the database
45484      ** file as well as into the page cache. Which would be incorrect in
45485      ** WAL mode.
45486      */
45487      pPager->eState = PAGER_WRITER_LOCKED;
45488      pPager->dbHintSize = pPager->dbSize;
45489      pPager->dbFileSize = pPager->dbSize;
45490      pPager->dbOrigSize = pPager->dbSize;
45491      pPager->journalOff = 0;
45492    }
45493
45494    assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
45495    assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
45496    assert( assert_pager_state(pPager) );
45497  }
45498
45499  PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
45500  return rc;
45501}
45502
45503/*
45504** Mark a single data page as writeable. The page is written into the
45505** main journal or sub-journal as required. If the page is written into
45506** one of the journals, the corresponding bit is set in the
45507** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
45508** of any open savepoints as appropriate.
45509*/
45510static int pager_write(PgHdr *pPg){
45511  Pager *pPager = pPg->pPager;
45512  int rc = SQLITE_OK;
45513  int inJournal;
45514
45515  /* This routine is not called unless a write-transaction has already
45516  ** been started. The journal file may or may not be open at this point.
45517  ** It is never called in the ERROR state.
45518  */
45519  assert( pPager->eState==PAGER_WRITER_LOCKED
45520       || pPager->eState==PAGER_WRITER_CACHEMOD
45521       || pPager->eState==PAGER_WRITER_DBMOD
45522  );
45523  assert( assert_pager_state(pPager) );
45524  assert( pPager->errCode==0 );
45525  assert( pPager->readOnly==0 );
45526
45527  CHECK_PAGE(pPg);
45528
45529  /* The journal file needs to be opened. Higher level routines have already
45530  ** obtained the necessary locks to begin the write-transaction, but the
45531  ** rollback journal might not yet be open. Open it now if this is the case.
45532  **
45533  ** This is done before calling sqlite3PcacheMakeDirty() on the page.
45534  ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
45535  ** an error might occur and the pager would end up in WRITER_LOCKED state
45536  ** with pages marked as dirty in the cache.
45537  */
45538  if( pPager->eState==PAGER_WRITER_LOCKED ){
45539    rc = pager_open_journal(pPager);
45540    if( rc!=SQLITE_OK ) return rc;
45541  }
45542  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
45543  assert( assert_pager_state(pPager) );
45544
45545  /* Mark the page as dirty.  If the page has already been written
45546  ** to the journal then we can return right away.
45547  */
45548  sqlite3PcacheMakeDirty(pPg);
45549  inJournal = pageInJournal(pPager, pPg);
45550  if( inJournal && (pPager->nSavepoint==0 || !subjRequiresPage(pPg)) ){
45551    assert( !pagerUseWal(pPager) );
45552  }else{
45553
45554    /* The transaction journal now exists and we have a RESERVED or an
45555    ** EXCLUSIVE lock on the main database file.  Write the current page to
45556    ** the transaction journal if it is not there already.
45557    */
45558    if( !inJournal && !pagerUseWal(pPager) ){
45559      assert( pagerUseWal(pPager)==0 );
45560      if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
45561        u32 cksum;
45562        char *pData2;
45563        i64 iOff = pPager->journalOff;
45564
45565        /* We should never write to the journal file the page that
45566        ** contains the database locks.  The following assert verifies
45567        ** that we do not. */
45568        assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
45569
45570        assert( pPager->journalHdr<=pPager->journalOff );
45571        CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
45572        cksum = pager_cksum(pPager, (u8*)pData2);
45573
45574        /* Even if an IO or diskfull error occurs while journalling the
45575        ** page in the block above, set the need-sync flag for the page.
45576        ** Otherwise, when the transaction is rolled back, the logic in
45577        ** playback_one_page() will think that the page needs to be restored
45578        ** in the database file. And if an IO error occurs while doing so,
45579        ** then corruption may follow.
45580        */
45581        pPg->flags |= PGHDR_NEED_SYNC;
45582
45583        rc = write32bits(pPager->jfd, iOff, pPg->pgno);
45584        if( rc!=SQLITE_OK ) return rc;
45585        rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
45586        if( rc!=SQLITE_OK ) return rc;
45587        rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
45588        if( rc!=SQLITE_OK ) return rc;
45589
45590        IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
45591                 pPager->journalOff, pPager->pageSize));
45592        PAGER_INCR(sqlite3_pager_writej_count);
45593        PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
45594             PAGERID(pPager), pPg->pgno,
45595             ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
45596
45597        pPager->journalOff += 8 + pPager->pageSize;
45598        pPager->nRec++;
45599        assert( pPager->pInJournal!=0 );
45600        rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
45601        testcase( rc==SQLITE_NOMEM );
45602        assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
45603        rc |= addToSavepointBitvecs(pPager, pPg->pgno);
45604        if( rc!=SQLITE_OK ){
45605          assert( rc==SQLITE_NOMEM );
45606          return rc;
45607        }
45608      }else{
45609        if( pPager->eState!=PAGER_WRITER_DBMOD ){
45610          pPg->flags |= PGHDR_NEED_SYNC;
45611        }
45612        PAGERTRACE(("APPEND %d page %d needSync=%d\n",
45613                PAGERID(pPager), pPg->pgno,
45614               ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
45615      }
45616    }
45617
45618    /* If the statement journal is open and the page is not in it,
45619    ** then write the current page to the statement journal.  Note that
45620    ** the statement journal format differs from the standard journal format
45621    ** in that it omits the checksums and the header.
45622    */
45623    if( pPager->nSavepoint>0 && subjRequiresPage(pPg) ){
45624      rc = subjournalPage(pPg);
45625    }
45626  }
45627
45628  /* Update the database size and return.
45629  */
45630  if( pPager->dbSize<pPg->pgno ){
45631    pPager->dbSize = pPg->pgno;
45632  }
45633  return rc;
45634}
45635
45636/*
45637** Mark a data page as writeable. This routine must be called before
45638** making changes to a page. The caller must check the return value
45639** of this function and be careful not to change any page data unless
45640** this routine returns SQLITE_OK.
45641**
45642** The difference between this function and pager_write() is that this
45643** function also deals with the special case where 2 or more pages
45644** fit on a single disk sector. In this case all co-resident pages
45645** must have been written to the journal file before returning.
45646**
45647** If an error occurs, SQLITE_NOMEM or an IO error code is returned
45648** as appropriate. Otherwise, SQLITE_OK.
45649*/
45650SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
45651  int rc = SQLITE_OK;
45652
45653  PgHdr *pPg = pDbPage;
45654  Pager *pPager = pPg->pPager;
45655
45656  assert( (pPg->flags & PGHDR_MMAP)==0 );
45657  assert( pPager->eState>=PAGER_WRITER_LOCKED );
45658  assert( pPager->eState!=PAGER_ERROR );
45659  assert( assert_pager_state(pPager) );
45660
45661  if( pPager->sectorSize > (u32)pPager->pageSize ){
45662    Pgno nPageCount;          /* Total number of pages in database file */
45663    Pgno pg1;                 /* First page of the sector pPg is located on. */
45664    int nPage = 0;            /* Number of pages starting at pg1 to journal */
45665    int ii;                   /* Loop counter */
45666    int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
45667    Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
45668
45669    /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
45670    ** a journal header to be written between the pages journaled by
45671    ** this function.
45672    */
45673    assert( !MEMDB );
45674    assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
45675    pPager->doNotSpill |= SPILLFLAG_NOSYNC;
45676
45677    /* This trick assumes that both the page-size and sector-size are
45678    ** an integer power of 2. It sets variable pg1 to the identifier
45679    ** of the first page of the sector pPg is located on.
45680    */
45681    pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
45682
45683    nPageCount = pPager->dbSize;
45684    if( pPg->pgno>nPageCount ){
45685      nPage = (pPg->pgno - pg1)+1;
45686    }else if( (pg1+nPagePerSector-1)>nPageCount ){
45687      nPage = nPageCount+1-pg1;
45688    }else{
45689      nPage = nPagePerSector;
45690    }
45691    assert(nPage>0);
45692    assert(pg1<=pPg->pgno);
45693    assert((pg1+nPage)>pPg->pgno);
45694
45695    for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
45696      Pgno pg = pg1+ii;
45697      PgHdr *pPage;
45698      if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
45699        if( pg!=PAGER_MJ_PGNO(pPager) ){
45700          rc = sqlite3PagerGet(pPager, pg, &pPage);
45701          if( rc==SQLITE_OK ){
45702            rc = pager_write(pPage);
45703            if( pPage->flags&PGHDR_NEED_SYNC ){
45704              needSync = 1;
45705            }
45706            sqlite3PagerUnrefNotNull(pPage);
45707          }
45708        }
45709      }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
45710        if( pPage->flags&PGHDR_NEED_SYNC ){
45711          needSync = 1;
45712        }
45713        sqlite3PagerUnrefNotNull(pPage);
45714      }
45715    }
45716
45717    /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
45718    ** starting at pg1, then it needs to be set for all of them. Because
45719    ** writing to any of these nPage pages may damage the others, the
45720    ** journal file must contain sync()ed copies of all of them
45721    ** before any of them can be written out to the database file.
45722    */
45723    if( rc==SQLITE_OK && needSync ){
45724      assert( !MEMDB );
45725      for(ii=0; ii<nPage; ii++){
45726        PgHdr *pPage = pager_lookup(pPager, pg1+ii);
45727        if( pPage ){
45728          pPage->flags |= PGHDR_NEED_SYNC;
45729          sqlite3PagerUnrefNotNull(pPage);
45730        }
45731      }
45732    }
45733
45734    assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
45735    pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
45736  }else{
45737    rc = pager_write(pDbPage);
45738  }
45739  return rc;
45740}
45741
45742/*
45743** Return TRUE if the page given in the argument was previously passed
45744** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
45745** to change the content of the page.
45746*/
45747#ifndef NDEBUG
45748SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
45749  return pPg->flags&PGHDR_DIRTY;
45750}
45751#endif
45752
45753/*
45754** A call to this routine tells the pager that it is not necessary to
45755** write the information on page pPg back to the disk, even though
45756** that page might be marked as dirty.  This happens, for example, when
45757** the page has been added as a leaf of the freelist and so its
45758** content no longer matters.
45759**
45760** The overlying software layer calls this routine when all of the data
45761** on the given page is unused. The pager marks the page as clean so
45762** that it does not get written to disk.
45763**
45764** Tests show that this optimization can quadruple the speed of large
45765** DELETE operations.
45766*/
45767SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
45768  Pager *pPager = pPg->pPager;
45769  if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
45770    PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
45771    IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
45772    pPg->flags |= PGHDR_DONT_WRITE;
45773    pager_set_pagehash(pPg);
45774  }
45775}
45776
45777/*
45778** This routine is called to increment the value of the database file
45779** change-counter, stored as a 4-byte big-endian integer starting at
45780** byte offset 24 of the pager file.  The secondary change counter at
45781** 92 is also updated, as is the SQLite version number at offset 96.
45782**
45783** But this only happens if the pPager->changeCountDone flag is false.
45784** To avoid excess churning of page 1, the update only happens once.
45785** See also the pager_write_changecounter() routine that does an
45786** unconditional update of the change counters.
45787**
45788** If the isDirectMode flag is zero, then this is done by calling
45789** sqlite3PagerWrite() on page 1, then modifying the contents of the
45790** page data. In this case the file will be updated when the current
45791** transaction is committed.
45792**
45793** The isDirectMode flag may only be non-zero if the library was compiled
45794** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
45795** if isDirect is non-zero, then the database file is updated directly
45796** by writing an updated version of page 1 using a call to the
45797** sqlite3OsWrite() function.
45798*/
45799static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
45800  int rc = SQLITE_OK;
45801
45802  assert( pPager->eState==PAGER_WRITER_CACHEMOD
45803       || pPager->eState==PAGER_WRITER_DBMOD
45804  );
45805  assert( assert_pager_state(pPager) );
45806
45807  /* Declare and initialize constant integer 'isDirect'. If the
45808  ** atomic-write optimization is enabled in this build, then isDirect
45809  ** is initialized to the value passed as the isDirectMode parameter
45810  ** to this function. Otherwise, it is always set to zero.
45811  **
45812  ** The idea is that if the atomic-write optimization is not
45813  ** enabled at compile time, the compiler can omit the tests of
45814  ** 'isDirect' below, as well as the block enclosed in the
45815  ** "if( isDirect )" condition.
45816  */
45817#ifndef SQLITE_ENABLE_ATOMIC_WRITE
45818# define DIRECT_MODE 0
45819  assert( isDirectMode==0 );
45820  UNUSED_PARAMETER(isDirectMode);
45821#else
45822# define DIRECT_MODE isDirectMode
45823#endif
45824
45825  if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
45826    PgHdr *pPgHdr;                /* Reference to page 1 */
45827
45828    assert( !pPager->tempFile && isOpen(pPager->fd) );
45829
45830    /* Open page 1 of the file for writing. */
45831    rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
45832    assert( pPgHdr==0 || rc==SQLITE_OK );
45833
45834    /* If page one was fetched successfully, and this function is not
45835    ** operating in direct-mode, make page 1 writable.  When not in
45836    ** direct mode, page 1 is always held in cache and hence the PagerGet()
45837    ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
45838    */
45839    if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
45840      rc = sqlite3PagerWrite(pPgHdr);
45841    }
45842
45843    if( rc==SQLITE_OK ){
45844      /* Actually do the update of the change counter */
45845      pager_write_changecounter(pPgHdr);
45846
45847      /* If running in direct mode, write the contents of page 1 to the file. */
45848      if( DIRECT_MODE ){
45849        const void *zBuf;
45850        assert( pPager->dbFileSize>0 );
45851        CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
45852        if( rc==SQLITE_OK ){
45853          rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
45854          pPager->aStat[PAGER_STAT_WRITE]++;
45855        }
45856        if( rc==SQLITE_OK ){
45857          /* Update the pager's copy of the change-counter. Otherwise, the
45858          ** next time a read transaction is opened the cache will be
45859          ** flushed (as the change-counter values will not match).  */
45860          const void *pCopy = (const void *)&((const char *)zBuf)[24];
45861          memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
45862          pPager->changeCountDone = 1;
45863        }
45864      }else{
45865        pPager->changeCountDone = 1;
45866      }
45867    }
45868
45869    /* Release the page reference. */
45870    sqlite3PagerUnref(pPgHdr);
45871  }
45872  return rc;
45873}
45874
45875/*
45876** Sync the database file to disk. This is a no-op for in-memory databases
45877** or pages with the Pager.noSync flag set.
45878**
45879** If successful, or if called on a pager for which it is a no-op, this
45880** function returns SQLITE_OK. Otherwise, an IO error code is returned.
45881*/
45882SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
45883  int rc = SQLITE_OK;
45884
45885  if( isOpen(pPager->fd) ){
45886    void *pArg = (void*)zMaster;
45887    rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
45888    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
45889  }
45890  if( rc==SQLITE_OK && !pPager->noSync ){
45891    assert( !MEMDB );
45892    rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
45893  }
45894  return rc;
45895}
45896
45897/*
45898** This function may only be called while a write-transaction is active in
45899** rollback. If the connection is in WAL mode, this call is a no-op.
45900** Otherwise, if the connection does not already have an EXCLUSIVE lock on
45901** the database file, an attempt is made to obtain one.
45902**
45903** If the EXCLUSIVE lock is already held or the attempt to obtain it is
45904** successful, or the connection is in WAL mode, SQLITE_OK is returned.
45905** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
45906** returned.
45907*/
45908SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
45909  int rc = SQLITE_OK;
45910  assert( pPager->eState==PAGER_WRITER_CACHEMOD
45911       || pPager->eState==PAGER_WRITER_DBMOD
45912       || pPager->eState==PAGER_WRITER_LOCKED
45913  );
45914  assert( assert_pager_state(pPager) );
45915  if( 0==pagerUseWal(pPager) ){
45916    rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
45917  }
45918  return rc;
45919}
45920
45921/*
45922** Sync the database file for the pager pPager. zMaster points to the name
45923** of a master journal file that should be written into the individual
45924** journal file. zMaster may be NULL, which is interpreted as no master
45925** journal (a single database transaction).
45926**
45927** This routine ensures that:
45928**
45929**   * The database file change-counter is updated,
45930**   * the journal is synced (unless the atomic-write optimization is used),
45931**   * all dirty pages are written to the database file,
45932**   * the database file is truncated (if required), and
45933**   * the database file synced.
45934**
45935** The only thing that remains to commit the transaction is to finalize
45936** (delete, truncate or zero the first part of) the journal file (or
45937** delete the master journal file if specified).
45938**
45939** Note that if zMaster==NULL, this does not overwrite a previous value
45940** passed to an sqlite3PagerCommitPhaseOne() call.
45941**
45942** If the final parameter - noSync - is true, then the database file itself
45943** is not synced. The caller must call sqlite3PagerSync() directly to
45944** sync the database file before calling CommitPhaseTwo() to delete the
45945** journal file in this case.
45946*/
45947SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
45948  Pager *pPager,                  /* Pager object */
45949  const char *zMaster,            /* If not NULL, the master journal name */
45950  int noSync                      /* True to omit the xSync on the db file */
45951){
45952  int rc = SQLITE_OK;             /* Return code */
45953
45954  assert( pPager->eState==PAGER_WRITER_LOCKED
45955       || pPager->eState==PAGER_WRITER_CACHEMOD
45956       || pPager->eState==PAGER_WRITER_DBMOD
45957       || pPager->eState==PAGER_ERROR
45958  );
45959  assert( assert_pager_state(pPager) );
45960
45961  /* If a prior error occurred, report that error again. */
45962  if( NEVER(pPager->errCode) ) return pPager->errCode;
45963
45964  PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
45965      pPager->zFilename, zMaster, pPager->dbSize));
45966
45967  /* If no database changes have been made, return early. */
45968  if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
45969
45970  if( MEMDB ){
45971    /* If this is an in-memory db, or no pages have been written to, or this
45972    ** function has already been called, it is mostly a no-op.  However, any
45973    ** backup in progress needs to be restarted.
45974    */
45975    sqlite3BackupRestart(pPager->pBackup);
45976  }else{
45977    if( pagerUseWal(pPager) ){
45978      PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
45979      PgHdr *pPageOne = 0;
45980      if( pList==0 ){
45981        /* Must have at least one page for the WAL commit flag.
45982        ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
45983        rc = sqlite3PagerGet(pPager, 1, &pPageOne);
45984        pList = pPageOne;
45985        pList->pDirty = 0;
45986      }
45987      assert( rc==SQLITE_OK );
45988      if( ALWAYS(pList) ){
45989        rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
45990      }
45991      sqlite3PagerUnref(pPageOne);
45992      if( rc==SQLITE_OK ){
45993        sqlite3PcacheCleanAll(pPager->pPCache);
45994      }
45995    }else{
45996      /* The following block updates the change-counter. Exactly how it
45997      ** does this depends on whether or not the atomic-update optimization
45998      ** was enabled at compile time, and if this transaction meets the
45999      ** runtime criteria to use the operation:
46000      **
46001      **    * The file-system supports the atomic-write property for
46002      **      blocks of size page-size, and
46003      **    * This commit is not part of a multi-file transaction, and
46004      **    * Exactly one page has been modified and store in the journal file.
46005      **
46006      ** If the optimization was not enabled at compile time, then the
46007      ** pager_incr_changecounter() function is called to update the change
46008      ** counter in 'indirect-mode'. If the optimization is compiled in but
46009      ** is not applicable to this transaction, call sqlite3JournalCreate()
46010      ** to make sure the journal file has actually been created, then call
46011      ** pager_incr_changecounter() to update the change-counter in indirect
46012      ** mode.
46013      **
46014      ** Otherwise, if the optimization is both enabled and applicable,
46015      ** then call pager_incr_changecounter() to update the change-counter
46016      ** in 'direct' mode. In this case the journal file will never be
46017      ** created for this transaction.
46018      */
46019  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
46020      PgHdr *pPg;
46021      assert( isOpen(pPager->jfd)
46022           || pPager->journalMode==PAGER_JOURNALMODE_OFF
46023           || pPager->journalMode==PAGER_JOURNALMODE_WAL
46024      );
46025      if( !zMaster && isOpen(pPager->jfd)
46026       && pPager->journalOff==jrnlBufferSize(pPager)
46027       && pPager->dbSize>=pPager->dbOrigSize
46028       && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
46029      ){
46030        /* Update the db file change counter via the direct-write method. The
46031        ** following call will modify the in-memory representation of page 1
46032        ** to include the updated change counter and then write page 1
46033        ** directly to the database file. Because of the atomic-write
46034        ** property of the host file-system, this is safe.
46035        */
46036        rc = pager_incr_changecounter(pPager, 1);
46037      }else{
46038        rc = sqlite3JournalCreate(pPager->jfd);
46039        if( rc==SQLITE_OK ){
46040          rc = pager_incr_changecounter(pPager, 0);
46041        }
46042      }
46043  #else
46044      rc = pager_incr_changecounter(pPager, 0);
46045  #endif
46046      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
46047
46048      /* Write the master journal name into the journal file. If a master
46049      ** journal file name has already been written to the journal file,
46050      ** or if zMaster is NULL (no master journal), then this call is a no-op.
46051      */
46052      rc = writeMasterJournal(pPager, zMaster);
46053      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
46054
46055      /* Sync the journal file and write all dirty pages to the database.
46056      ** If the atomic-update optimization is being used, this sync will not
46057      ** create the journal file or perform any real IO.
46058      **
46059      ** Because the change-counter page was just modified, unless the
46060      ** atomic-update optimization is used it is almost certain that the
46061      ** journal requires a sync here. However, in locking_mode=exclusive
46062      ** on a system under memory pressure it is just possible that this is
46063      ** not the case. In this case it is likely enough that the redundant
46064      ** xSync() call will be changed to a no-op by the OS anyhow.
46065      */
46066      rc = syncJournal(pPager, 0);
46067      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
46068
46069      rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
46070      if( rc!=SQLITE_OK ){
46071        assert( rc!=SQLITE_IOERR_BLOCKED );
46072        goto commit_phase_one_exit;
46073      }
46074      sqlite3PcacheCleanAll(pPager->pPCache);
46075
46076      /* If the file on disk is smaller than the database image, use
46077      ** pager_truncate to grow the file here. This can happen if the database
46078      ** image was extended as part of the current transaction and then the
46079      ** last page in the db image moved to the free-list. In this case the
46080      ** last page is never written out to disk, leaving the database file
46081      ** undersized. Fix this now if it is the case.  */
46082      if( pPager->dbSize>pPager->dbFileSize ){
46083        Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
46084        assert( pPager->eState==PAGER_WRITER_DBMOD );
46085        rc = pager_truncate(pPager, nNew);
46086        if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
46087      }
46088
46089      /* Finally, sync the database file. */
46090      if( !noSync ){
46091        rc = sqlite3PagerSync(pPager, zMaster);
46092      }
46093      IOTRACE(("DBSYNC %p\n", pPager))
46094    }
46095  }
46096
46097commit_phase_one_exit:
46098  if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
46099    pPager->eState = PAGER_WRITER_FINISHED;
46100  }
46101  return rc;
46102}
46103
46104
46105/*
46106** When this function is called, the database file has been completely
46107** updated to reflect the changes made by the current transaction and
46108** synced to disk. The journal file still exists in the file-system
46109** though, and if a failure occurs at this point it will eventually
46110** be used as a hot-journal and the current transaction rolled back.
46111**
46112** This function finalizes the journal file, either by deleting,
46113** truncating or partially zeroing it, so that it cannot be used
46114** for hot-journal rollback. Once this is done the transaction is
46115** irrevocably committed.
46116**
46117** If an error occurs, an IO error code is returned and the pager
46118** moves into the error state. Otherwise, SQLITE_OK is returned.
46119*/
46120SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
46121  int rc = SQLITE_OK;                  /* Return code */
46122
46123  /* This routine should not be called if a prior error has occurred.
46124  ** But if (due to a coding error elsewhere in the system) it does get
46125  ** called, just return the same error code without doing anything. */
46126  if( NEVER(pPager->errCode) ) return pPager->errCode;
46127
46128  assert( pPager->eState==PAGER_WRITER_LOCKED
46129       || pPager->eState==PAGER_WRITER_FINISHED
46130       || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
46131  );
46132  assert( assert_pager_state(pPager) );
46133
46134  /* An optimization. If the database was not actually modified during
46135  ** this transaction, the pager is running in exclusive-mode and is
46136  ** using persistent journals, then this function is a no-op.
46137  **
46138  ** The start of the journal file currently contains a single journal
46139  ** header with the nRec field set to 0. If such a journal is used as
46140  ** a hot-journal during hot-journal rollback, 0 changes will be made
46141  ** to the database file. So there is no need to zero the journal
46142  ** header. Since the pager is in exclusive mode, there is no need
46143  ** to drop any locks either.
46144  */
46145  if( pPager->eState==PAGER_WRITER_LOCKED
46146   && pPager->exclusiveMode
46147   && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
46148  ){
46149    assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
46150    pPager->eState = PAGER_READER;
46151    return SQLITE_OK;
46152  }
46153
46154  PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
46155  rc = pager_end_transaction(pPager, pPager->setMaster, 1);
46156  return pager_error(pPager, rc);
46157}
46158
46159/*
46160** If a write transaction is open, then all changes made within the
46161** transaction are reverted and the current write-transaction is closed.
46162** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
46163** state if an error occurs.
46164**
46165** If the pager is already in PAGER_ERROR state when this function is called,
46166** it returns Pager.errCode immediately. No work is performed in this case.
46167**
46168** Otherwise, in rollback mode, this function performs two functions:
46169**
46170**   1) It rolls back the journal file, restoring all database file and
46171**      in-memory cache pages to the state they were in when the transaction
46172**      was opened, and
46173**
46174**   2) It finalizes the journal file, so that it is not used for hot
46175**      rollback at any point in the future.
46176**
46177** Finalization of the journal file (task 2) is only performed if the
46178** rollback is successful.
46179**
46180** In WAL mode, all cache-entries containing data modified within the
46181** current transaction are either expelled from the cache or reverted to
46182** their pre-transaction state by re-reading data from the database or
46183** WAL files. The WAL transaction is then closed.
46184*/
46185SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
46186  int rc = SQLITE_OK;                  /* Return code */
46187  PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
46188
46189  /* PagerRollback() is a no-op if called in READER or OPEN state. If
46190  ** the pager is already in the ERROR state, the rollback is not
46191  ** attempted here. Instead, the error code is returned to the caller.
46192  */
46193  assert( assert_pager_state(pPager) );
46194  if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
46195  if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
46196
46197  if( pagerUseWal(pPager) ){
46198    int rc2;
46199    rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
46200    rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
46201    if( rc==SQLITE_OK ) rc = rc2;
46202  }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
46203    int eState = pPager->eState;
46204    rc = pager_end_transaction(pPager, 0, 0);
46205    if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
46206      /* This can happen using journal_mode=off. Move the pager to the error
46207      ** state to indicate that the contents of the cache may not be trusted.
46208      ** Any active readers will get SQLITE_ABORT.
46209      */
46210      pPager->errCode = SQLITE_ABORT;
46211      pPager->eState = PAGER_ERROR;
46212      return rc;
46213    }
46214  }else{
46215    rc = pager_playback(pPager, 0);
46216  }
46217
46218  assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
46219  assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
46220          || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
46221          || rc==SQLITE_CANTOPEN
46222  );
46223
46224  /* If an error occurs during a ROLLBACK, we can no longer trust the pager
46225  ** cache. So call pager_error() on the way out to make any error persistent.
46226  */
46227  return pager_error(pPager, rc);
46228}
46229
46230/*
46231** Return TRUE if the database file is opened read-only.  Return FALSE
46232** if the database is (in theory) writable.
46233*/
46234SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
46235  return pPager->readOnly;
46236}
46237
46238/*
46239** Return the number of references to the pager.
46240*/
46241SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
46242  return sqlite3PcacheRefCount(pPager->pPCache);
46243}
46244
46245/*
46246** Return the approximate number of bytes of memory currently
46247** used by the pager and its associated cache.
46248*/
46249SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
46250  int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
46251                                     + 5*sizeof(void*);
46252  return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
46253           + sqlite3MallocSize(pPager)
46254           + pPager->pageSize;
46255}
46256
46257/*
46258** Return the number of references to the specified page.
46259*/
46260SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
46261  return sqlite3PcachePageRefcount(pPage);
46262}
46263
46264#ifdef SQLITE_TEST
46265/*
46266** This routine is used for testing and analysis only.
46267*/
46268SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
46269  static int a[11];
46270  a[0] = sqlite3PcacheRefCount(pPager->pPCache);
46271  a[1] = sqlite3PcachePagecount(pPager->pPCache);
46272  a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
46273  a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
46274  a[4] = pPager->eState;
46275  a[5] = pPager->errCode;
46276  a[6] = pPager->aStat[PAGER_STAT_HIT];
46277  a[7] = pPager->aStat[PAGER_STAT_MISS];
46278  a[8] = 0;  /* Used to be pPager->nOvfl */
46279  a[9] = pPager->nRead;
46280  a[10] = pPager->aStat[PAGER_STAT_WRITE];
46281  return a;
46282}
46283#endif
46284
46285/*
46286** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
46287** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
46288** current cache hit or miss count, according to the value of eStat. If the
46289** reset parameter is non-zero, the cache hit or miss count is zeroed before
46290** returning.
46291*/
46292SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
46293
46294  assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
46295       || eStat==SQLITE_DBSTATUS_CACHE_MISS
46296       || eStat==SQLITE_DBSTATUS_CACHE_WRITE
46297  );
46298
46299  assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
46300  assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
46301  assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
46302
46303  *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
46304  if( reset ){
46305    pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
46306  }
46307}
46308
46309/*
46310** Return true if this is an in-memory pager.
46311*/
46312SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
46313  return MEMDB;
46314}
46315
46316/*
46317** Check that there are at least nSavepoint savepoints open. If there are
46318** currently less than nSavepoints open, then open one or more savepoints
46319** to make up the difference. If the number of savepoints is already
46320** equal to nSavepoint, then this function is a no-op.
46321**
46322** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
46323** occurs while opening the sub-journal file, then an IO error code is
46324** returned. Otherwise, SQLITE_OK.
46325*/
46326SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
46327  int rc = SQLITE_OK;                       /* Return code */
46328  int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
46329
46330  assert( pPager->eState>=PAGER_WRITER_LOCKED );
46331  assert( assert_pager_state(pPager) );
46332
46333  if( nSavepoint>nCurrent && pPager->useJournal ){
46334    int ii;                                 /* Iterator variable */
46335    PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
46336
46337    /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
46338    ** if the allocation fails. Otherwise, zero the new portion in case a
46339    ** malloc failure occurs while populating it in the for(...) loop below.
46340    */
46341    aNew = (PagerSavepoint *)sqlite3Realloc(
46342        pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
46343    );
46344    if( !aNew ){
46345      return SQLITE_NOMEM;
46346    }
46347    memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
46348    pPager->aSavepoint = aNew;
46349
46350    /* Populate the PagerSavepoint structures just allocated. */
46351    for(ii=nCurrent; ii<nSavepoint; ii++){
46352      aNew[ii].nOrig = pPager->dbSize;
46353      if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
46354        aNew[ii].iOffset = pPager->journalOff;
46355      }else{
46356        aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
46357      }
46358      aNew[ii].iSubRec = pPager->nSubRec;
46359      aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
46360      if( !aNew[ii].pInSavepoint ){
46361        return SQLITE_NOMEM;
46362      }
46363      if( pagerUseWal(pPager) ){
46364        sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
46365      }
46366      pPager->nSavepoint = ii+1;
46367    }
46368    assert( pPager->nSavepoint==nSavepoint );
46369    assertTruncateConstraint(pPager);
46370  }
46371
46372  return rc;
46373}
46374
46375/*
46376** This function is called to rollback or release (commit) a savepoint.
46377** The savepoint to release or rollback need not be the most recently
46378** created savepoint.
46379**
46380** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
46381** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
46382** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
46383** that have occurred since the specified savepoint was created.
46384**
46385** The savepoint to rollback or release is identified by parameter
46386** iSavepoint. A value of 0 means to operate on the outermost savepoint
46387** (the first created). A value of (Pager.nSavepoint-1) means operate
46388** on the most recently created savepoint. If iSavepoint is greater than
46389** (Pager.nSavepoint-1), then this function is a no-op.
46390**
46391** If a negative value is passed to this function, then the current
46392** transaction is rolled back. This is different to calling
46393** sqlite3PagerRollback() because this function does not terminate
46394** the transaction or unlock the database, it just restores the
46395** contents of the database to its original state.
46396**
46397** In any case, all savepoints with an index greater than iSavepoint
46398** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
46399** then savepoint iSavepoint is also destroyed.
46400**
46401** This function may return SQLITE_NOMEM if a memory allocation fails,
46402** or an IO error code if an IO error occurs while rolling back a
46403** savepoint. If no errors occur, SQLITE_OK is returned.
46404*/
46405SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
46406  int rc = pPager->errCode;       /* Return code */
46407
46408  assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
46409  assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
46410
46411  if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
46412    int ii;            /* Iterator variable */
46413    int nNew;          /* Number of remaining savepoints after this op. */
46414
46415    /* Figure out how many savepoints will still be active after this
46416    ** operation. Store this value in nNew. Then free resources associated
46417    ** with any savepoints that are destroyed by this operation.
46418    */
46419    nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
46420    for(ii=nNew; ii<pPager->nSavepoint; ii++){
46421      sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
46422    }
46423    pPager->nSavepoint = nNew;
46424
46425    /* If this is a release of the outermost savepoint, truncate
46426    ** the sub-journal to zero bytes in size. */
46427    if( op==SAVEPOINT_RELEASE ){
46428      if( nNew==0 && isOpen(pPager->sjfd) ){
46429        /* Only truncate if it is an in-memory sub-journal. */
46430        if( sqlite3IsMemJournal(pPager->sjfd) ){
46431          rc = sqlite3OsTruncate(pPager->sjfd, 0);
46432          assert( rc==SQLITE_OK );
46433        }
46434        pPager->nSubRec = 0;
46435      }
46436    }
46437    /* Else this is a rollback operation, playback the specified savepoint.
46438    ** If this is a temp-file, it is possible that the journal file has
46439    ** not yet been opened. In this case there have been no changes to
46440    ** the database file, so the playback operation can be skipped.
46441    */
46442    else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
46443      PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
46444      rc = pagerPlaybackSavepoint(pPager, pSavepoint);
46445      assert(rc!=SQLITE_DONE);
46446    }
46447  }
46448
46449  return rc;
46450}
46451
46452/*
46453** Return the full pathname of the database file.
46454**
46455** Except, if the pager is in-memory only, then return an empty string if
46456** nullIfMemDb is true.  This routine is called with nullIfMemDb==1 when
46457** used to report the filename to the user, for compatibility with legacy
46458** behavior.  But when the Btree needs to know the filename for matching to
46459** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
46460** participate in shared-cache.
46461*/
46462SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
46463  return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
46464}
46465
46466/*
46467** Return the VFS structure for the pager.
46468*/
46469SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
46470  return pPager->pVfs;
46471}
46472
46473/*
46474** Return the file handle for the database file associated
46475** with the pager.  This might return NULL if the file has
46476** not yet been opened.
46477*/
46478SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
46479  return pPager->fd;
46480}
46481
46482/*
46483** Return the full pathname of the journal file.
46484*/
46485SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
46486  return pPager->zJournal;
46487}
46488
46489/*
46490** Return true if fsync() calls are disabled for this pager.  Return FALSE
46491** if fsync()s are executed normally.
46492*/
46493SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
46494  return pPager->noSync;
46495}
46496
46497#ifdef SQLITE_HAS_CODEC
46498/*
46499** Set or retrieve the codec for this pager
46500*/
46501SQLITE_PRIVATE void sqlite3PagerSetCodec(
46502  Pager *pPager,
46503  void *(*xCodec)(void*,void*,Pgno,int),
46504  void (*xCodecSizeChng)(void*,int,int),
46505  void (*xCodecFree)(void*),
46506  void *pCodec
46507){
46508  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
46509  pPager->xCodec = pPager->memDb ? 0 : xCodec;
46510  pPager->xCodecSizeChng = xCodecSizeChng;
46511  pPager->xCodecFree = xCodecFree;
46512  pPager->pCodec = pCodec;
46513  pagerReportSize(pPager);
46514}
46515SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
46516  return pPager->pCodec;
46517}
46518
46519/*
46520** This function is called by the wal module when writing page content
46521** into the log file.
46522**
46523** This function returns a pointer to a buffer containing the encrypted
46524** page content. If a malloc fails, this function may return NULL.
46525*/
46526SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
46527  void *aData = 0;
46528  CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
46529  return aData;
46530}
46531
46532/*
46533** Return the current pager state
46534*/
46535SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
46536  return pPager->eState;
46537}
46538#endif /* SQLITE_HAS_CODEC */
46539
46540#ifndef SQLITE_OMIT_AUTOVACUUM
46541/*
46542** Move the page pPg to location pgno in the file.
46543**
46544** There must be no references to the page previously located at
46545** pgno (which we call pPgOld) though that page is allowed to be
46546** in cache.  If the page previously located at pgno is not already
46547** in the rollback journal, it is not put there by by this routine.
46548**
46549** References to the page pPg remain valid. Updating any
46550** meta-data associated with pPg (i.e. data stored in the nExtra bytes
46551** allocated along with the page) is the responsibility of the caller.
46552**
46553** A transaction must be active when this routine is called. It used to be
46554** required that a statement transaction was not active, but this restriction
46555** has been removed (CREATE INDEX needs to move a page when a statement
46556** transaction is active).
46557**
46558** If the fourth argument, isCommit, is non-zero, then this page is being
46559** moved as part of a database reorganization just before the transaction
46560** is being committed. In this case, it is guaranteed that the database page
46561** pPg refers to will not be written to again within this transaction.
46562**
46563** This function may return SQLITE_NOMEM or an IO error code if an error
46564** occurs. Otherwise, it returns SQLITE_OK.
46565*/
46566SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
46567  PgHdr *pPgOld;               /* The page being overwritten. */
46568  Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
46569  int rc;                      /* Return code */
46570  Pgno origPgno;               /* The original page number */
46571
46572  assert( pPg->nRef>0 );
46573  assert( pPager->eState==PAGER_WRITER_CACHEMOD
46574       || pPager->eState==PAGER_WRITER_DBMOD
46575  );
46576  assert( assert_pager_state(pPager) );
46577
46578  /* In order to be able to rollback, an in-memory database must journal
46579  ** the page we are moving from.
46580  */
46581  if( MEMDB ){
46582    rc = sqlite3PagerWrite(pPg);
46583    if( rc ) return rc;
46584  }
46585
46586  /* If the page being moved is dirty and has not been saved by the latest
46587  ** savepoint, then save the current contents of the page into the
46588  ** sub-journal now. This is required to handle the following scenario:
46589  **
46590  **   BEGIN;
46591  **     <journal page X, then modify it in memory>
46592  **     SAVEPOINT one;
46593  **       <Move page X to location Y>
46594  **     ROLLBACK TO one;
46595  **
46596  ** If page X were not written to the sub-journal here, it would not
46597  ** be possible to restore its contents when the "ROLLBACK TO one"
46598  ** statement were is processed.
46599  **
46600  ** subjournalPage() may need to allocate space to store pPg->pgno into
46601  ** one or more savepoint bitvecs. This is the reason this function
46602  ** may return SQLITE_NOMEM.
46603  */
46604  if( pPg->flags&PGHDR_DIRTY
46605   && subjRequiresPage(pPg)
46606   && SQLITE_OK!=(rc = subjournalPage(pPg))
46607  ){
46608    return rc;
46609  }
46610
46611  PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
46612      PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
46613  IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
46614
46615  /* If the journal needs to be sync()ed before page pPg->pgno can
46616  ** be written to, store pPg->pgno in local variable needSyncPgno.
46617  **
46618  ** If the isCommit flag is set, there is no need to remember that
46619  ** the journal needs to be sync()ed before database page pPg->pgno
46620  ** can be written to. The caller has already promised not to write to it.
46621  */
46622  if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
46623    needSyncPgno = pPg->pgno;
46624    assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
46625            pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
46626    assert( pPg->flags&PGHDR_DIRTY );
46627  }
46628
46629  /* If the cache contains a page with page-number pgno, remove it
46630  ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
46631  ** page pgno before the 'move' operation, it needs to be retained
46632  ** for the page moved there.
46633  */
46634  pPg->flags &= ~PGHDR_NEED_SYNC;
46635  pPgOld = pager_lookup(pPager, pgno);
46636  assert( !pPgOld || pPgOld->nRef==1 );
46637  if( pPgOld ){
46638    pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
46639    if( MEMDB ){
46640      /* Do not discard pages from an in-memory database since we might
46641      ** need to rollback later.  Just move the page out of the way. */
46642      sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
46643    }else{
46644      sqlite3PcacheDrop(pPgOld);
46645    }
46646  }
46647
46648  origPgno = pPg->pgno;
46649  sqlite3PcacheMove(pPg, pgno);
46650  sqlite3PcacheMakeDirty(pPg);
46651
46652  /* For an in-memory database, make sure the original page continues
46653  ** to exist, in case the transaction needs to roll back.  Use pPgOld
46654  ** as the original page since it has already been allocated.
46655  */
46656  if( MEMDB ){
46657    assert( pPgOld );
46658    sqlite3PcacheMove(pPgOld, origPgno);
46659    sqlite3PagerUnrefNotNull(pPgOld);
46660  }
46661
46662  if( needSyncPgno ){
46663    /* If needSyncPgno is non-zero, then the journal file needs to be
46664    ** sync()ed before any data is written to database file page needSyncPgno.
46665    ** Currently, no such page exists in the page-cache and the
46666    ** "is journaled" bitvec flag has been set. This needs to be remedied by
46667    ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
46668    ** flag.
46669    **
46670    ** If the attempt to load the page into the page-cache fails, (due
46671    ** to a malloc() or IO failure), clear the bit in the pInJournal[]
46672    ** array. Otherwise, if the page is loaded and written again in
46673    ** this transaction, it may be written to the database file before
46674    ** it is synced into the journal file. This way, it may end up in
46675    ** the journal file twice, but that is not a problem.
46676    */
46677    PgHdr *pPgHdr;
46678    rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
46679    if( rc!=SQLITE_OK ){
46680      if( needSyncPgno<=pPager->dbOrigSize ){
46681        assert( pPager->pTmpSpace!=0 );
46682        sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
46683      }
46684      return rc;
46685    }
46686    pPgHdr->flags |= PGHDR_NEED_SYNC;
46687    sqlite3PcacheMakeDirty(pPgHdr);
46688    sqlite3PagerUnrefNotNull(pPgHdr);
46689  }
46690
46691  return SQLITE_OK;
46692}
46693#endif
46694
46695/*
46696** Return a pointer to the data for the specified page.
46697*/
46698SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
46699  assert( pPg->nRef>0 || pPg->pPager->memDb );
46700  return pPg->pData;
46701}
46702
46703/*
46704** Return a pointer to the Pager.nExtra bytes of "extra" space
46705** allocated along with the specified page.
46706*/
46707SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
46708  return pPg->pExtra;
46709}
46710
46711/*
46712** Get/set the locking-mode for this pager. Parameter eMode must be one
46713** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
46714** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
46715** the locking-mode is set to the value specified.
46716**
46717** The returned value is either PAGER_LOCKINGMODE_NORMAL or
46718** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
46719** locking-mode.
46720*/
46721SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
46722  assert( eMode==PAGER_LOCKINGMODE_QUERY
46723            || eMode==PAGER_LOCKINGMODE_NORMAL
46724            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
46725  assert( PAGER_LOCKINGMODE_QUERY<0 );
46726  assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
46727  assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
46728  if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
46729    pPager->exclusiveMode = (u8)eMode;
46730  }
46731  return (int)pPager->exclusiveMode;
46732}
46733
46734/*
46735** Set the journal-mode for this pager. Parameter eMode must be one of:
46736**
46737**    PAGER_JOURNALMODE_DELETE
46738**    PAGER_JOURNALMODE_TRUNCATE
46739**    PAGER_JOURNALMODE_PERSIST
46740**    PAGER_JOURNALMODE_OFF
46741**    PAGER_JOURNALMODE_MEMORY
46742**    PAGER_JOURNALMODE_WAL
46743**
46744** The journalmode is set to the value specified if the change is allowed.
46745** The change may be disallowed for the following reasons:
46746**
46747**   *  An in-memory database can only have its journal_mode set to _OFF
46748**      or _MEMORY.
46749**
46750**   *  Temporary databases cannot have _WAL journalmode.
46751**
46752** The returned indicate the current (possibly updated) journal-mode.
46753*/
46754SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
46755  u8 eOld = pPager->journalMode;    /* Prior journalmode */
46756
46757#ifdef SQLITE_DEBUG
46758  /* The print_pager_state() routine is intended to be used by the debugger
46759  ** only.  We invoke it once here to suppress a compiler warning. */
46760  print_pager_state(pPager);
46761#endif
46762
46763
46764  /* The eMode parameter is always valid */
46765  assert(      eMode==PAGER_JOURNALMODE_DELETE
46766            || eMode==PAGER_JOURNALMODE_TRUNCATE
46767            || eMode==PAGER_JOURNALMODE_PERSIST
46768            || eMode==PAGER_JOURNALMODE_OFF
46769            || eMode==PAGER_JOURNALMODE_WAL
46770            || eMode==PAGER_JOURNALMODE_MEMORY );
46771
46772  /* This routine is only called from the OP_JournalMode opcode, and
46773  ** the logic there will never allow a temporary file to be changed
46774  ** to WAL mode.
46775  */
46776  assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
46777
46778  /* Do allow the journalmode of an in-memory database to be set to
46779  ** anything other than MEMORY or OFF
46780  */
46781  if( MEMDB ){
46782    assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
46783    if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
46784      eMode = eOld;
46785    }
46786  }
46787
46788  if( eMode!=eOld ){
46789
46790    /* Change the journal mode. */
46791    assert( pPager->eState!=PAGER_ERROR );
46792    pPager->journalMode = (u8)eMode;
46793
46794    /* When transistioning from TRUNCATE or PERSIST to any other journal
46795    ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
46796    ** delete the journal file.
46797    */
46798    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
46799    assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
46800    assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
46801    assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
46802    assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
46803    assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
46804
46805    assert( isOpen(pPager->fd) || pPager->exclusiveMode );
46806    if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
46807
46808      /* In this case we would like to delete the journal file. If it is
46809      ** not possible, then that is not a problem. Deleting the journal file
46810      ** here is an optimization only.
46811      **
46812      ** Before deleting the journal file, obtain a RESERVED lock on the
46813      ** database file. This ensures that the journal file is not deleted
46814      ** while it is in use by some other client.
46815      */
46816      sqlite3OsClose(pPager->jfd);
46817      if( pPager->eLock>=RESERVED_LOCK ){
46818        sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
46819      }else{
46820        int rc = SQLITE_OK;
46821        int state = pPager->eState;
46822        assert( state==PAGER_OPEN || state==PAGER_READER );
46823        if( state==PAGER_OPEN ){
46824          rc = sqlite3PagerSharedLock(pPager);
46825        }
46826        if( pPager->eState==PAGER_READER ){
46827          assert( rc==SQLITE_OK );
46828          rc = pagerLockDb(pPager, RESERVED_LOCK);
46829        }
46830        if( rc==SQLITE_OK ){
46831          sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
46832        }
46833        if( rc==SQLITE_OK && state==PAGER_READER ){
46834          pagerUnlockDb(pPager, SHARED_LOCK);
46835        }else if( state==PAGER_OPEN ){
46836          pager_unlock(pPager);
46837        }
46838        assert( state==pPager->eState );
46839      }
46840    }
46841  }
46842
46843  /* Return the new journal mode */
46844  return (int)pPager->journalMode;
46845}
46846
46847/*
46848** Return the current journal mode.
46849*/
46850SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
46851  return (int)pPager->journalMode;
46852}
46853
46854/*
46855** Return TRUE if the pager is in a state where it is OK to change the
46856** journalmode.  Journalmode changes can only happen when the database
46857** is unmodified.
46858*/
46859SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
46860  assert( assert_pager_state(pPager) );
46861  if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
46862  if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
46863  return 1;
46864}
46865
46866/*
46867** Get/set the size-limit used for persistent journal files.
46868**
46869** Setting the size limit to -1 means no limit is enforced.
46870** An attempt to set a limit smaller than -1 is a no-op.
46871*/
46872SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
46873  if( iLimit>=-1 ){
46874    pPager->journalSizeLimit = iLimit;
46875    sqlite3WalLimit(pPager->pWal, iLimit);
46876  }
46877  return pPager->journalSizeLimit;
46878}
46879
46880/*
46881** Return a pointer to the pPager->pBackup variable. The backup module
46882** in backup.c maintains the content of this variable. This module
46883** uses it opaquely as an argument to sqlite3BackupRestart() and
46884** sqlite3BackupUpdate() only.
46885*/
46886SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
46887  return &pPager->pBackup;
46888}
46889
46890#ifndef SQLITE_OMIT_VACUUM
46891/*
46892** Unless this is an in-memory or temporary database, clear the pager cache.
46893*/
46894SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
46895  if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
46896}
46897#endif
46898
46899#ifndef SQLITE_OMIT_WAL
46900/*
46901** This function is called when the user invokes "PRAGMA wal_checkpoint",
46902** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
46903** or wal_blocking_checkpoint() API functions.
46904**
46905** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
46906*/
46907SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
46908  int rc = SQLITE_OK;
46909  if( pPager->pWal ){
46910    rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
46911        pPager->xBusyHandler, pPager->pBusyHandlerArg,
46912        pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
46913        pnLog, pnCkpt
46914    );
46915  }
46916  return rc;
46917}
46918
46919SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
46920  return sqlite3WalCallback(pPager->pWal);
46921}
46922
46923/*
46924** Return true if the underlying VFS for the given pager supports the
46925** primitives necessary for write-ahead logging.
46926*/
46927SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
46928  const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
46929  return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
46930}
46931
46932/*
46933** Attempt to take an exclusive lock on the database file. If a PENDING lock
46934** is obtained instead, immediately release it.
46935*/
46936static int pagerExclusiveLock(Pager *pPager){
46937  int rc;                         /* Return code */
46938
46939  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
46940  rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
46941  if( rc!=SQLITE_OK ){
46942    /* If the attempt to grab the exclusive lock failed, release the
46943    ** pending lock that may have been obtained instead.  */
46944    pagerUnlockDb(pPager, SHARED_LOCK);
46945  }
46946
46947  return rc;
46948}
46949
46950/*
46951** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
46952** exclusive-locking mode when this function is called, take an EXCLUSIVE
46953** lock on the database file and use heap-memory to store the wal-index
46954** in. Otherwise, use the normal shared-memory.
46955*/
46956static int pagerOpenWal(Pager *pPager){
46957  int rc = SQLITE_OK;
46958
46959  assert( pPager->pWal==0 && pPager->tempFile==0 );
46960  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
46961
46962  /* If the pager is already in exclusive-mode, the WAL module will use
46963  ** heap-memory for the wal-index instead of the VFS shared-memory
46964  ** implementation. Take the exclusive lock now, before opening the WAL
46965  ** file, to make sure this is safe.
46966  */
46967  if( pPager->exclusiveMode ){
46968    rc = pagerExclusiveLock(pPager);
46969  }
46970
46971  /* Open the connection to the log file. If this operation fails,
46972  ** (e.g. due to malloc() failure), return an error code.
46973  */
46974  if( rc==SQLITE_OK ){
46975    rc = sqlite3WalOpen(pPager->pVfs,
46976        pPager->fd, pPager->zWal, pPager->exclusiveMode,
46977        pPager->journalSizeLimit, &pPager->pWal
46978    );
46979  }
46980  pagerFixMaplimit(pPager);
46981
46982  return rc;
46983}
46984
46985
46986/*
46987** The caller must be holding a SHARED lock on the database file to call
46988** this function.
46989**
46990** If the pager passed as the first argument is open on a real database
46991** file (not a temp file or an in-memory database), and the WAL file
46992** is not already open, make an attempt to open it now. If successful,
46993** return SQLITE_OK. If an error occurs or the VFS used by the pager does
46994** not support the xShmXXX() methods, return an error code. *pbOpen is
46995** not modified in either case.
46996**
46997** If the pager is open on a temp-file (or in-memory database), or if
46998** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
46999** without doing anything.
47000*/
47001SQLITE_PRIVATE int sqlite3PagerOpenWal(
47002  Pager *pPager,                  /* Pager object */
47003  int *pbOpen                     /* OUT: Set to true if call is a no-op */
47004){
47005  int rc = SQLITE_OK;             /* Return code */
47006
47007  assert( assert_pager_state(pPager) );
47008  assert( pPager->eState==PAGER_OPEN   || pbOpen );
47009  assert( pPager->eState==PAGER_READER || !pbOpen );
47010  assert( pbOpen==0 || *pbOpen==0 );
47011  assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
47012
47013  if( !pPager->tempFile && !pPager->pWal ){
47014    if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
47015
47016    /* Close any rollback journal previously open */
47017    sqlite3OsClose(pPager->jfd);
47018
47019    rc = pagerOpenWal(pPager);
47020    if( rc==SQLITE_OK ){
47021      pPager->journalMode = PAGER_JOURNALMODE_WAL;
47022      pPager->eState = PAGER_OPEN;
47023    }
47024  }else{
47025    *pbOpen = 1;
47026  }
47027
47028  return rc;
47029}
47030
47031/*
47032** This function is called to close the connection to the log file prior
47033** to switching from WAL to rollback mode.
47034**
47035** Before closing the log file, this function attempts to take an
47036** EXCLUSIVE lock on the database file. If this cannot be obtained, an
47037** error (SQLITE_BUSY) is returned and the log connection is not closed.
47038** If successful, the EXCLUSIVE lock is not released before returning.
47039*/
47040SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
47041  int rc = SQLITE_OK;
47042
47043  assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
47044
47045  /* If the log file is not already open, but does exist in the file-system,
47046  ** it may need to be checkpointed before the connection can switch to
47047  ** rollback mode. Open it now so this can happen.
47048  */
47049  if( !pPager->pWal ){
47050    int logexists = 0;
47051    rc = pagerLockDb(pPager, SHARED_LOCK);
47052    if( rc==SQLITE_OK ){
47053      rc = sqlite3OsAccess(
47054          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
47055      );
47056    }
47057    if( rc==SQLITE_OK && logexists ){
47058      rc = pagerOpenWal(pPager);
47059    }
47060  }
47061
47062  /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
47063  ** the database file, the log and log-summary files will be deleted.
47064  */
47065  if( rc==SQLITE_OK && pPager->pWal ){
47066    rc = pagerExclusiveLock(pPager);
47067    if( rc==SQLITE_OK ){
47068      rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
47069                           pPager->pageSize, (u8*)pPager->pTmpSpace);
47070      pPager->pWal = 0;
47071      pagerFixMaplimit(pPager);
47072    }
47073  }
47074  return rc;
47075}
47076
47077#endif /* !SQLITE_OMIT_WAL */
47078
47079#ifdef SQLITE_ENABLE_ZIPVFS
47080/*
47081** A read-lock must be held on the pager when this function is called. If
47082** the pager is in WAL mode and the WAL file currently contains one or more
47083** frames, return the size in bytes of the page images stored within the
47084** WAL frames. Otherwise, if this is not a WAL database or the WAL file
47085** is empty, return 0.
47086*/
47087SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
47088  assert( pPager->eState==PAGER_READER );
47089  return sqlite3WalFramesize(pPager->pWal);
47090}
47091#endif
47092
47093#endif /* SQLITE_OMIT_DISKIO */
47094
47095/************** End of pager.c ***********************************************/
47096/************** Begin file wal.c *********************************************/
47097/*
47098** 2010 February 1
47099**
47100** The author disclaims copyright to this source code.  In place of
47101** a legal notice, here is a blessing:
47102**
47103**    May you do good and not evil.
47104**    May you find forgiveness for yourself and forgive others.
47105**    May you share freely, never taking more than you give.
47106**
47107*************************************************************************
47108**
47109** This file contains the implementation of a write-ahead log (WAL) used in
47110** "journal_mode=WAL" mode.
47111**
47112** WRITE-AHEAD LOG (WAL) FILE FORMAT
47113**
47114** A WAL file consists of a header followed by zero or more "frames".
47115** Each frame records the revised content of a single page from the
47116** database file.  All changes to the database are recorded by writing
47117** frames into the WAL.  Transactions commit when a frame is written that
47118** contains a commit marker.  A single WAL can and usually does record
47119** multiple transactions.  Periodically, the content of the WAL is
47120** transferred back into the database file in an operation called a
47121** "checkpoint".
47122**
47123** A single WAL file can be used multiple times.  In other words, the
47124** WAL can fill up with frames and then be checkpointed and then new
47125** frames can overwrite the old ones.  A WAL always grows from beginning
47126** toward the end.  Checksums and counters attached to each frame are
47127** used to determine which frames within the WAL are valid and which
47128** are leftovers from prior checkpoints.
47129**
47130** The WAL header is 32 bytes in size and consists of the following eight
47131** big-endian 32-bit unsigned integer values:
47132**
47133**     0: Magic number.  0x377f0682 or 0x377f0683
47134**     4: File format version.  Currently 3007000
47135**     8: Database page size.  Example: 1024
47136**    12: Checkpoint sequence number
47137**    16: Salt-1, random integer incremented with each checkpoint
47138**    20: Salt-2, a different random integer changing with each ckpt
47139**    24: Checksum-1 (first part of checksum for first 24 bytes of header).
47140**    28: Checksum-2 (second part of checksum for first 24 bytes of header).
47141**
47142** Immediately following the wal-header are zero or more frames. Each
47143** frame consists of a 24-byte frame-header followed by a <page-size> bytes
47144** of page data. The frame-header is six big-endian 32-bit unsigned
47145** integer values, as follows:
47146**
47147**     0: Page number.
47148**     4: For commit records, the size of the database image in pages
47149**        after the commit. For all other records, zero.
47150**     8: Salt-1 (copied from the header)
47151**    12: Salt-2 (copied from the header)
47152**    16: Checksum-1.
47153**    20: Checksum-2.
47154**
47155** A frame is considered valid if and only if the following conditions are
47156** true:
47157**
47158**    (1) The salt-1 and salt-2 values in the frame-header match
47159**        salt values in the wal-header
47160**
47161**    (2) The checksum values in the final 8 bytes of the frame-header
47162**        exactly match the checksum computed consecutively on the
47163**        WAL header and the first 8 bytes and the content of all frames
47164**        up to and including the current frame.
47165**
47166** The checksum is computed using 32-bit big-endian integers if the
47167** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
47168** is computed using little-endian if the magic number is 0x377f0682.
47169** The checksum values are always stored in the frame header in a
47170** big-endian format regardless of which byte order is used to compute
47171** the checksum.  The checksum is computed by interpreting the input as
47172** an even number of unsigned 32-bit integers: x[0] through x[N].  The
47173** algorithm used for the checksum is as follows:
47174**
47175**   for i from 0 to n-1 step 2:
47176**     s0 += x[i] + s1;
47177**     s1 += x[i+1] + s0;
47178**   endfor
47179**
47180** Note that s0 and s1 are both weighted checksums using fibonacci weights
47181** in reverse order (the largest fibonacci weight occurs on the first element
47182** of the sequence being summed.)  The s1 value spans all 32-bit
47183** terms of the sequence whereas s0 omits the final term.
47184**
47185** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
47186** WAL is transferred into the database, then the database is VFS.xSync-ed.
47187** The VFS.xSync operations serve as write barriers - all writes launched
47188** before the xSync must complete before any write that launches after the
47189** xSync begins.
47190**
47191** After each checkpoint, the salt-1 value is incremented and the salt-2
47192** value is randomized.  This prevents old and new frames in the WAL from
47193** being considered valid at the same time and being checkpointing together
47194** following a crash.
47195**
47196** READER ALGORITHM
47197**
47198** To read a page from the database (call it page number P), a reader
47199** first checks the WAL to see if it contains page P.  If so, then the
47200** last valid instance of page P that is a followed by a commit frame
47201** or is a commit frame itself becomes the value read.  If the WAL
47202** contains no copies of page P that are valid and which are a commit
47203** frame or are followed by a commit frame, then page P is read from
47204** the database file.
47205**
47206** To start a read transaction, the reader records the index of the last
47207** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
47208** for all subsequent read operations.  New transactions can be appended
47209** to the WAL, but as long as the reader uses its original mxFrame value
47210** and ignores the newly appended content, it will see a consistent snapshot
47211** of the database from a single point in time.  This technique allows
47212** multiple concurrent readers to view different versions of the database
47213** content simultaneously.
47214**
47215** The reader algorithm in the previous paragraphs works correctly, but
47216** because frames for page P can appear anywhere within the WAL, the
47217** reader has to scan the entire WAL looking for page P frames.  If the
47218** WAL is large (multiple megabytes is typical) that scan can be slow,
47219** and read performance suffers.  To overcome this problem, a separate
47220** data structure called the wal-index is maintained to expedite the
47221** search for frames of a particular page.
47222**
47223** WAL-INDEX FORMAT
47224**
47225** Conceptually, the wal-index is shared memory, though VFS implementations
47226** might choose to implement the wal-index using a mmapped file.  Because
47227** the wal-index is shared memory, SQLite does not support journal_mode=WAL
47228** on a network filesystem.  All users of the database must be able to
47229** share memory.
47230**
47231** The wal-index is transient.  After a crash, the wal-index can (and should
47232** be) reconstructed from the original WAL file.  In fact, the VFS is required
47233** to either truncate or zero the header of the wal-index when the last
47234** connection to it closes.  Because the wal-index is transient, it can
47235** use an architecture-specific format; it does not have to be cross-platform.
47236** Hence, unlike the database and WAL file formats which store all values
47237** as big endian, the wal-index can store multi-byte values in the native
47238** byte order of the host computer.
47239**
47240** The purpose of the wal-index is to answer this question quickly:  Given
47241** a page number P and a maximum frame index M, return the index of the
47242** last frame in the wal before frame M for page P in the WAL, or return
47243** NULL if there are no frames for page P in the WAL prior to M.
47244**
47245** The wal-index consists of a header region, followed by an one or
47246** more index blocks.
47247**
47248** The wal-index header contains the total number of frames within the WAL
47249** in the mxFrame field.
47250**
47251** Each index block except for the first contains information on
47252** HASHTABLE_NPAGE frames. The first index block contains information on
47253** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
47254** HASHTABLE_NPAGE are selected so that together the wal-index header and
47255** first index block are the same size as all other index blocks in the
47256** wal-index.
47257**
47258** Each index block contains two sections, a page-mapping that contains the
47259** database page number associated with each wal frame, and a hash-table
47260** that allows readers to query an index block for a specific page number.
47261** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
47262** for the first index block) 32-bit page numbers. The first entry in the
47263** first index-block contains the database page number corresponding to the
47264** first frame in the WAL file. The first entry in the second index block
47265** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
47266** the log, and so on.
47267**
47268** The last index block in a wal-index usually contains less than the full
47269** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
47270** depending on the contents of the WAL file. This does not change the
47271** allocated size of the page-mapping array - the page-mapping array merely
47272** contains unused entries.
47273**
47274** Even without using the hash table, the last frame for page P
47275** can be found by scanning the page-mapping sections of each index block
47276** starting with the last index block and moving toward the first, and
47277** within each index block, starting at the end and moving toward the
47278** beginning.  The first entry that equals P corresponds to the frame
47279** holding the content for that page.
47280**
47281** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
47282** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
47283** hash table for each page number in the mapping section, so the hash
47284** table is never more than half full.  The expected number of collisions
47285** prior to finding a match is 1.  Each entry of the hash table is an
47286** 1-based index of an entry in the mapping section of the same
47287** index block.   Let K be the 1-based index of the largest entry in
47288** the mapping section.  (For index blocks other than the last, K will
47289** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
47290** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
47291** contain a value of 0.
47292**
47293** To look for page P in the hash table, first compute a hash iKey on
47294** P as follows:
47295**
47296**      iKey = (P * 383) % HASHTABLE_NSLOT
47297**
47298** Then start scanning entries of the hash table, starting with iKey
47299** (wrapping around to the beginning when the end of the hash table is
47300** reached) until an unused hash slot is found. Let the first unused slot
47301** be at index iUnused.  (iUnused might be less than iKey if there was
47302** wrap-around.) Because the hash table is never more than half full,
47303** the search is guaranteed to eventually hit an unused entry.  Let
47304** iMax be the value between iKey and iUnused, closest to iUnused,
47305** where aHash[iMax]==P.  If there is no iMax entry (if there exists
47306** no hash slot such that aHash[i]==p) then page P is not in the
47307** current index block.  Otherwise the iMax-th mapping entry of the
47308** current index block corresponds to the last entry that references
47309** page P.
47310**
47311** A hash search begins with the last index block and moves toward the
47312** first index block, looking for entries corresponding to page P.  On
47313** average, only two or three slots in each index block need to be
47314** examined in order to either find the last entry for page P, or to
47315** establish that no such entry exists in the block.  Each index block
47316** holds over 4000 entries.  So two or three index blocks are sufficient
47317** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
47318** comparisons (on average) suffice to either locate a frame in the
47319** WAL or to establish that the frame does not exist in the WAL.  This
47320** is much faster than scanning the entire 10MB WAL.
47321**
47322** Note that entries are added in order of increasing K.  Hence, one
47323** reader might be using some value K0 and a second reader that started
47324** at a later time (after additional transactions were added to the WAL
47325** and to the wal-index) might be using a different value K1, where K1>K0.
47326** Both readers can use the same hash table and mapping section to get
47327** the correct result.  There may be entries in the hash table with
47328** K>K0 but to the first reader, those entries will appear to be unused
47329** slots in the hash table and so the first reader will get an answer as
47330** if no values greater than K0 had ever been inserted into the hash table
47331** in the first place - which is what reader one wants.  Meanwhile, the
47332** second reader using K1 will see additional values that were inserted
47333** later, which is exactly what reader two wants.
47334**
47335** When a rollback occurs, the value of K is decreased. Hash table entries
47336** that correspond to frames greater than the new K value are removed
47337** from the hash table at this point.
47338*/
47339#ifndef SQLITE_OMIT_WAL
47340
47341
47342/*
47343** Trace output macros
47344*/
47345#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
47346SQLITE_PRIVATE int sqlite3WalTrace = 0;
47347# define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
47348#else
47349# define WALTRACE(X)
47350#endif
47351
47352/*
47353** The maximum (and only) versions of the wal and wal-index formats
47354** that may be interpreted by this version of SQLite.
47355**
47356** If a client begins recovering a WAL file and finds that (a) the checksum
47357** values in the wal-header are correct and (b) the version field is not
47358** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
47359**
47360** Similarly, if a client successfully reads a wal-index header (i.e. the
47361** checksum test is successful) and finds that the version field is not
47362** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
47363** returns SQLITE_CANTOPEN.
47364*/
47365#define WAL_MAX_VERSION      3007000
47366#define WALINDEX_MAX_VERSION 3007000
47367
47368/*
47369** Indices of various locking bytes.   WAL_NREADER is the number
47370** of available reader locks and should be at least 3.
47371*/
47372#define WAL_WRITE_LOCK         0
47373#define WAL_ALL_BUT_WRITE      1
47374#define WAL_CKPT_LOCK          1
47375#define WAL_RECOVER_LOCK       2
47376#define WAL_READ_LOCK(I)       (3+(I))
47377#define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
47378
47379
47380/* Object declarations */
47381typedef struct WalIndexHdr WalIndexHdr;
47382typedef struct WalIterator WalIterator;
47383typedef struct WalCkptInfo WalCkptInfo;
47384
47385
47386/*
47387** The following object holds a copy of the wal-index header content.
47388**
47389** The actual header in the wal-index consists of two copies of this
47390** object.
47391**
47392** The szPage value can be any power of 2 between 512 and 32768, inclusive.
47393** Or it can be 1 to represent a 65536-byte page.  The latter case was
47394** added in 3.7.1 when support for 64K pages was added.
47395*/
47396struct WalIndexHdr {
47397  u32 iVersion;                   /* Wal-index version */
47398  u32 unused;                     /* Unused (padding) field */
47399  u32 iChange;                    /* Counter incremented each transaction */
47400  u8 isInit;                      /* 1 when initialized */
47401  u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
47402  u16 szPage;                     /* Database page size in bytes. 1==64K */
47403  u32 mxFrame;                    /* Index of last valid frame in the WAL */
47404  u32 nPage;                      /* Size of database in pages */
47405  u32 aFrameCksum[2];             /* Checksum of last frame in log */
47406  u32 aSalt[2];                   /* Two salt values copied from WAL header */
47407  u32 aCksum[2];                  /* Checksum over all prior fields */
47408};
47409
47410/*
47411** A copy of the following object occurs in the wal-index immediately
47412** following the second copy of the WalIndexHdr.  This object stores
47413** information used by checkpoint.
47414**
47415** nBackfill is the number of frames in the WAL that have been written
47416** back into the database. (We call the act of moving content from WAL to
47417** database "backfilling".)  The nBackfill number is never greater than
47418** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
47419** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
47420** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
47421** mxFrame back to zero when the WAL is reset.
47422**
47423** There is one entry in aReadMark[] for each reader lock.  If a reader
47424** holds read-lock K, then the value in aReadMark[K] is no greater than
47425** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
47426** for any aReadMark[] means that entry is unused.  aReadMark[0] is
47427** a special case; its value is never used and it exists as a place-holder
47428** to avoid having to offset aReadMark[] indexs by one.  Readers holding
47429** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
47430** directly from the database.
47431**
47432** The value of aReadMark[K] may only be changed by a thread that
47433** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
47434** aReadMark[K] cannot changed while there is a reader is using that mark
47435** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
47436**
47437** The checkpointer may only transfer frames from WAL to database where
47438** the frame numbers are less than or equal to every aReadMark[] that is
47439** in use (that is, every aReadMark[j] for which there is a corresponding
47440** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
47441** largest value and will increase an unused aReadMark[] to mxFrame if there
47442** is not already an aReadMark[] equal to mxFrame.  The exception to the
47443** previous sentence is when nBackfill equals mxFrame (meaning that everything
47444** in the WAL has been backfilled into the database) then new readers
47445** will choose aReadMark[0] which has value 0 and hence such reader will
47446** get all their all content directly from the database file and ignore
47447** the WAL.
47448**
47449** Writers normally append new frames to the end of the WAL.  However,
47450** if nBackfill equals mxFrame (meaning that all WAL content has been
47451** written back into the database) and if no readers are using the WAL
47452** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
47453** the writer will first "reset" the WAL back to the beginning and start
47454** writing new content beginning at frame 1.
47455**
47456** We assume that 32-bit loads are atomic and so no locks are needed in
47457** order to read from any aReadMark[] entries.
47458*/
47459struct WalCkptInfo {
47460  u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
47461  u32 aReadMark[WAL_NREADER];     /* Reader marks */
47462};
47463#define READMARK_NOT_USED  0xffffffff
47464
47465
47466/* A block of WALINDEX_LOCK_RESERVED bytes beginning at
47467** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
47468** only support mandatory file-locks, we do not read or write data
47469** from the region of the file on which locks are applied.
47470*/
47471#define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
47472#define WALINDEX_LOCK_RESERVED 16
47473#define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
47474
47475/* Size of header before each frame in wal */
47476#define WAL_FRAME_HDRSIZE 24
47477
47478/* Size of write ahead log header, including checksum. */
47479/* #define WAL_HDRSIZE 24 */
47480#define WAL_HDRSIZE 32
47481
47482/* WAL magic value. Either this value, or the same value with the least
47483** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
47484** big-endian format in the first 4 bytes of a WAL file.
47485**
47486** If the LSB is set, then the checksums for each frame within the WAL
47487** file are calculated by treating all data as an array of 32-bit
47488** big-endian words. Otherwise, they are calculated by interpreting
47489** all data as 32-bit little-endian words.
47490*/
47491#define WAL_MAGIC 0x377f0682
47492
47493/*
47494** Return the offset of frame iFrame in the write-ahead log file,
47495** assuming a database page size of szPage bytes. The offset returned
47496** is to the start of the write-ahead log frame-header.
47497*/
47498#define walFrameOffset(iFrame, szPage) (                               \
47499  WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
47500)
47501
47502/*
47503** An open write-ahead log file is represented by an instance of the
47504** following object.
47505*/
47506struct Wal {
47507  sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
47508  sqlite3_file *pDbFd;       /* File handle for the database file */
47509  sqlite3_file *pWalFd;      /* File handle for WAL file */
47510  u32 iCallback;             /* Value to pass to log callback (or 0) */
47511  i64 mxWalSize;             /* Truncate WAL to this size upon reset */
47512  int nWiData;               /* Size of array apWiData */
47513  int szFirstBlock;          /* Size of first block written to WAL file */
47514  volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
47515  u32 szPage;                /* Database page size */
47516  i16 readLock;              /* Which read lock is being held.  -1 for none */
47517  u8 syncFlags;              /* Flags to use to sync header writes */
47518  u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
47519  u8 writeLock;              /* True if in a write transaction */
47520  u8 ckptLock;               /* True if holding a checkpoint lock */
47521  u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
47522  u8 truncateOnCommit;       /* True to truncate WAL file on commit */
47523  u8 syncHeader;             /* Fsync the WAL header if true */
47524  u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
47525  WalIndexHdr hdr;           /* Wal-index header for current transaction */
47526  const char *zWalName;      /* Name of WAL file */
47527  u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
47528#ifdef SQLITE_DEBUG
47529  u8 lockError;              /* True if a locking error has occurred */
47530#endif
47531};
47532
47533/*
47534** Candidate values for Wal.exclusiveMode.
47535*/
47536#define WAL_NORMAL_MODE     0
47537#define WAL_EXCLUSIVE_MODE  1
47538#define WAL_HEAPMEMORY_MODE 2
47539
47540/*
47541** Possible values for WAL.readOnly
47542*/
47543#define WAL_RDWR        0    /* Normal read/write connection */
47544#define WAL_RDONLY      1    /* The WAL file is readonly */
47545#define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
47546
47547/*
47548** Each page of the wal-index mapping contains a hash-table made up of
47549** an array of HASHTABLE_NSLOT elements of the following type.
47550*/
47551typedef u16 ht_slot;
47552
47553/*
47554** This structure is used to implement an iterator that loops through
47555** all frames in the WAL in database page order. Where two or more frames
47556** correspond to the same database page, the iterator visits only the
47557** frame most recently written to the WAL (in other words, the frame with
47558** the largest index).
47559**
47560** The internals of this structure are only accessed by:
47561**
47562**   walIteratorInit() - Create a new iterator,
47563**   walIteratorNext() - Step an iterator,
47564**   walIteratorFree() - Free an iterator.
47565**
47566** This functionality is used by the checkpoint code (see walCheckpoint()).
47567*/
47568struct WalIterator {
47569  int iPrior;                     /* Last result returned from the iterator */
47570  int nSegment;                   /* Number of entries in aSegment[] */
47571  struct WalSegment {
47572    int iNext;                    /* Next slot in aIndex[] not yet returned */
47573    ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
47574    u32 *aPgno;                   /* Array of page numbers. */
47575    int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
47576    int iZero;                    /* Frame number associated with aPgno[0] */
47577  } aSegment[1];                  /* One for every 32KB page in the wal-index */
47578};
47579
47580/*
47581** Define the parameters of the hash tables in the wal-index file. There
47582** is a hash-table following every HASHTABLE_NPAGE page numbers in the
47583** wal-index.
47584**
47585** Changing any of these constants will alter the wal-index format and
47586** create incompatibilities.
47587*/
47588#define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
47589#define HASHTABLE_HASH_1     383                  /* Should be prime */
47590#define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
47591
47592/*
47593** The block of page numbers associated with the first hash-table in a
47594** wal-index is smaller than usual. This is so that there is a complete
47595** hash-table on each aligned 32KB page of the wal-index.
47596*/
47597#define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
47598
47599/* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
47600#define WALINDEX_PGSZ   (                                         \
47601    sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
47602)
47603
47604/*
47605** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
47606** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
47607** numbered from zero.
47608**
47609** If this call is successful, *ppPage is set to point to the wal-index
47610** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
47611** then an SQLite error code is returned and *ppPage is set to 0.
47612*/
47613static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
47614  int rc = SQLITE_OK;
47615
47616  /* Enlarge the pWal->apWiData[] array if required */
47617  if( pWal->nWiData<=iPage ){
47618    int nByte = sizeof(u32*)*(iPage+1);
47619    volatile u32 **apNew;
47620    apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
47621    if( !apNew ){
47622      *ppPage = 0;
47623      return SQLITE_NOMEM;
47624    }
47625    memset((void*)&apNew[pWal->nWiData], 0,
47626           sizeof(u32*)*(iPage+1-pWal->nWiData));
47627    pWal->apWiData = apNew;
47628    pWal->nWiData = iPage+1;
47629  }
47630
47631  /* Request a pointer to the required page from the VFS */
47632  if( pWal->apWiData[iPage]==0 ){
47633    if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
47634      pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
47635      if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
47636    }else{
47637      rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
47638          pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
47639      );
47640      if( rc==SQLITE_READONLY ){
47641        pWal->readOnly |= WAL_SHM_RDONLY;
47642        rc = SQLITE_OK;
47643      }
47644    }
47645  }
47646
47647  *ppPage = pWal->apWiData[iPage];
47648  assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
47649  return rc;
47650}
47651
47652/*
47653** Return a pointer to the WalCkptInfo structure in the wal-index.
47654*/
47655static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
47656  assert( pWal->nWiData>0 && pWal->apWiData[0] );
47657  return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
47658}
47659
47660/*
47661** Return a pointer to the WalIndexHdr structure in the wal-index.
47662*/
47663static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
47664  assert( pWal->nWiData>0 && pWal->apWiData[0] );
47665  return (volatile WalIndexHdr*)pWal->apWiData[0];
47666}
47667
47668/*
47669** The argument to this macro must be of type u32. On a little-endian
47670** architecture, it returns the u32 value that results from interpreting
47671** the 4 bytes as a big-endian value. On a big-endian architecture, it
47672** returns the value that would be produced by intepreting the 4 bytes
47673** of the input value as a little-endian integer.
47674*/
47675#define BYTESWAP32(x) ( \
47676    (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
47677  + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
47678)
47679
47680/*
47681** Generate or extend an 8 byte checksum based on the data in
47682** array aByte[] and the initial values of aIn[0] and aIn[1] (or
47683** initial values of 0 and 0 if aIn==NULL).
47684**
47685** The checksum is written back into aOut[] before returning.
47686**
47687** nByte must be a positive multiple of 8.
47688*/
47689static void walChecksumBytes(
47690  int nativeCksum, /* True for native byte-order, false for non-native */
47691  u8 *a,           /* Content to be checksummed */
47692  int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
47693  const u32 *aIn,  /* Initial checksum value input */
47694  u32 *aOut        /* OUT: Final checksum value output */
47695){
47696  u32 s1, s2;
47697  u32 *aData = (u32 *)a;
47698  u32 *aEnd = (u32 *)&a[nByte];
47699
47700  if( aIn ){
47701    s1 = aIn[0];
47702    s2 = aIn[1];
47703  }else{
47704    s1 = s2 = 0;
47705  }
47706
47707  assert( nByte>=8 );
47708  assert( (nByte&0x00000007)==0 );
47709
47710  if( nativeCksum ){
47711    do {
47712      s1 += *aData++ + s2;
47713      s2 += *aData++ + s1;
47714    }while( aData<aEnd );
47715  }else{
47716    do {
47717      s1 += BYTESWAP32(aData[0]) + s2;
47718      s2 += BYTESWAP32(aData[1]) + s1;
47719      aData += 2;
47720    }while( aData<aEnd );
47721  }
47722
47723  aOut[0] = s1;
47724  aOut[1] = s2;
47725}
47726
47727static void walShmBarrier(Wal *pWal){
47728  if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
47729    sqlite3OsShmBarrier(pWal->pDbFd);
47730  }
47731}
47732
47733/*
47734** Write the header information in pWal->hdr into the wal-index.
47735**
47736** The checksum on pWal->hdr is updated before it is written.
47737*/
47738static void walIndexWriteHdr(Wal *pWal){
47739  volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
47740  const int nCksum = offsetof(WalIndexHdr, aCksum);
47741
47742  assert( pWal->writeLock );
47743  pWal->hdr.isInit = 1;
47744  pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
47745  walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
47746  memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
47747  walShmBarrier(pWal);
47748  memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
47749}
47750
47751/*
47752** This function encodes a single frame header and writes it to a buffer
47753** supplied by the caller. A frame-header is made up of a series of
47754** 4-byte big-endian integers, as follows:
47755**
47756**     0: Page number.
47757**     4: For commit records, the size of the database image in pages
47758**        after the commit. For all other records, zero.
47759**     8: Salt-1 (copied from the wal-header)
47760**    12: Salt-2 (copied from the wal-header)
47761**    16: Checksum-1.
47762**    20: Checksum-2.
47763*/
47764static void walEncodeFrame(
47765  Wal *pWal,                      /* The write-ahead log */
47766  u32 iPage,                      /* Database page number for frame */
47767  u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
47768  u8 *aData,                      /* Pointer to page data */
47769  u8 *aFrame                      /* OUT: Write encoded frame here */
47770){
47771  int nativeCksum;                /* True for native byte-order checksums */
47772  u32 *aCksum = pWal->hdr.aFrameCksum;
47773  assert( WAL_FRAME_HDRSIZE==24 );
47774  sqlite3Put4byte(&aFrame[0], iPage);
47775  sqlite3Put4byte(&aFrame[4], nTruncate);
47776  memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
47777
47778  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
47779  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
47780  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
47781
47782  sqlite3Put4byte(&aFrame[16], aCksum[0]);
47783  sqlite3Put4byte(&aFrame[20], aCksum[1]);
47784}
47785
47786/*
47787** Check to see if the frame with header in aFrame[] and content
47788** in aData[] is valid.  If it is a valid frame, fill *piPage and
47789** *pnTruncate and return true.  Return if the frame is not valid.
47790*/
47791static int walDecodeFrame(
47792  Wal *pWal,                      /* The write-ahead log */
47793  u32 *piPage,                    /* OUT: Database page number for frame */
47794  u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
47795  u8 *aData,                      /* Pointer to page data (for checksum) */
47796  u8 *aFrame                      /* Frame data */
47797){
47798  int nativeCksum;                /* True for native byte-order checksums */
47799  u32 *aCksum = pWal->hdr.aFrameCksum;
47800  u32 pgno;                       /* Page number of the frame */
47801  assert( WAL_FRAME_HDRSIZE==24 );
47802
47803  /* A frame is only valid if the salt values in the frame-header
47804  ** match the salt values in the wal-header.
47805  */
47806  if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
47807    return 0;
47808  }
47809
47810  /* A frame is only valid if the page number is creater than zero.
47811  */
47812  pgno = sqlite3Get4byte(&aFrame[0]);
47813  if( pgno==0 ){
47814    return 0;
47815  }
47816
47817  /* A frame is only valid if a checksum of the WAL header,
47818  ** all prior frams, the first 16 bytes of this frame-header,
47819  ** and the frame-data matches the checksum in the last 8
47820  ** bytes of this frame-header.
47821  */
47822  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
47823  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
47824  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
47825  if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
47826   || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
47827  ){
47828    /* Checksum failed. */
47829    return 0;
47830  }
47831
47832  /* If we reach this point, the frame is valid.  Return the page number
47833  ** and the new database size.
47834  */
47835  *piPage = pgno;
47836  *pnTruncate = sqlite3Get4byte(&aFrame[4]);
47837  return 1;
47838}
47839
47840
47841#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
47842/*
47843** Names of locks.  This routine is used to provide debugging output and is not
47844** a part of an ordinary build.
47845*/
47846static const char *walLockName(int lockIdx){
47847  if( lockIdx==WAL_WRITE_LOCK ){
47848    return "WRITE-LOCK";
47849  }else if( lockIdx==WAL_CKPT_LOCK ){
47850    return "CKPT-LOCK";
47851  }else if( lockIdx==WAL_RECOVER_LOCK ){
47852    return "RECOVER-LOCK";
47853  }else{
47854    static char zName[15];
47855    sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
47856                     lockIdx-WAL_READ_LOCK(0));
47857    return zName;
47858  }
47859}
47860#endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
47861
47862
47863/*
47864** Set or release locks on the WAL.  Locks are either shared or exclusive.
47865** A lock cannot be moved directly between shared and exclusive - it must go
47866** through the unlocked state first.
47867**
47868** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
47869*/
47870static int walLockShared(Wal *pWal, int lockIdx){
47871  int rc;
47872  if( pWal->exclusiveMode ) return SQLITE_OK;
47873  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
47874                        SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
47875  WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
47876            walLockName(lockIdx), rc ? "failed" : "ok"));
47877  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
47878  return rc;
47879}
47880static void walUnlockShared(Wal *pWal, int lockIdx){
47881  if( pWal->exclusiveMode ) return;
47882  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
47883                         SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
47884  WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
47885}
47886static int walLockExclusive(Wal *pWal, int lockIdx, int n){
47887  int rc;
47888  if( pWal->exclusiveMode ) return SQLITE_OK;
47889  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
47890                        SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
47891  WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
47892            walLockName(lockIdx), n, rc ? "failed" : "ok"));
47893  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
47894  return rc;
47895}
47896static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
47897  if( pWal->exclusiveMode ) return;
47898  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
47899                         SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
47900  WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
47901             walLockName(lockIdx), n));
47902}
47903
47904/*
47905** Compute a hash on a page number.  The resulting hash value must land
47906** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
47907** the hash to the next value in the event of a collision.
47908*/
47909static int walHash(u32 iPage){
47910  assert( iPage>0 );
47911  assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
47912  return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
47913}
47914static int walNextHash(int iPriorHash){
47915  return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
47916}
47917
47918/*
47919** Return pointers to the hash table and page number array stored on
47920** page iHash of the wal-index. The wal-index is broken into 32KB pages
47921** numbered starting from 0.
47922**
47923** Set output variable *paHash to point to the start of the hash table
47924** in the wal-index file. Set *piZero to one less than the frame
47925** number of the first frame indexed by this hash table. If a
47926** slot in the hash table is set to N, it refers to frame number
47927** (*piZero+N) in the log.
47928**
47929** Finally, set *paPgno so that *paPgno[1] is the page number of the
47930** first frame indexed by the hash table, frame (*piZero+1).
47931*/
47932static int walHashGet(
47933  Wal *pWal,                      /* WAL handle */
47934  int iHash,                      /* Find the iHash'th table */
47935  volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
47936  volatile u32 **paPgno,          /* OUT: Pointer to page number array */
47937  u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
47938){
47939  int rc;                         /* Return code */
47940  volatile u32 *aPgno;
47941
47942  rc = walIndexPage(pWal, iHash, &aPgno);
47943  assert( rc==SQLITE_OK || iHash>0 );
47944
47945  if( rc==SQLITE_OK ){
47946    u32 iZero;
47947    volatile ht_slot *aHash;
47948
47949    aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
47950    if( iHash==0 ){
47951      aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
47952      iZero = 0;
47953    }else{
47954      iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
47955    }
47956
47957    *paPgno = &aPgno[-1];
47958    *paHash = aHash;
47959    *piZero = iZero;
47960  }
47961  return rc;
47962}
47963
47964/*
47965** Return the number of the wal-index page that contains the hash-table
47966** and page-number array that contain entries corresponding to WAL frame
47967** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
47968** are numbered starting from 0.
47969*/
47970static int walFramePage(u32 iFrame){
47971  int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
47972  assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
47973       && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
47974       && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
47975       && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
47976       && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
47977  );
47978  return iHash;
47979}
47980
47981/*
47982** Return the page number associated with frame iFrame in this WAL.
47983*/
47984static u32 walFramePgno(Wal *pWal, u32 iFrame){
47985  int iHash = walFramePage(iFrame);
47986  if( iHash==0 ){
47987    return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
47988  }
47989  return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
47990}
47991
47992/*
47993** Remove entries from the hash table that point to WAL slots greater
47994** than pWal->hdr.mxFrame.
47995**
47996** This function is called whenever pWal->hdr.mxFrame is decreased due
47997** to a rollback or savepoint.
47998**
47999** At most only the hash table containing pWal->hdr.mxFrame needs to be
48000** updated.  Any later hash tables will be automatically cleared when
48001** pWal->hdr.mxFrame advances to the point where those hash tables are
48002** actually needed.
48003*/
48004static void walCleanupHash(Wal *pWal){
48005  volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
48006  volatile u32 *aPgno = 0;        /* Page number array for hash table */
48007  u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
48008  int iLimit = 0;                 /* Zero values greater than this */
48009  int nByte;                      /* Number of bytes to zero in aPgno[] */
48010  int i;                          /* Used to iterate through aHash[] */
48011
48012  assert( pWal->writeLock );
48013  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
48014  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
48015  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
48016
48017  if( pWal->hdr.mxFrame==0 ) return;
48018
48019  /* Obtain pointers to the hash-table and page-number array containing
48020  ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
48021  ** that the page said hash-table and array reside on is already mapped.
48022  */
48023  assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
48024  assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
48025  walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
48026
48027  /* Zero all hash-table entries that correspond to frame numbers greater
48028  ** than pWal->hdr.mxFrame.
48029  */
48030  iLimit = pWal->hdr.mxFrame - iZero;
48031  assert( iLimit>0 );
48032  for(i=0; i<HASHTABLE_NSLOT; i++){
48033    if( aHash[i]>iLimit ){
48034      aHash[i] = 0;
48035    }
48036  }
48037
48038  /* Zero the entries in the aPgno array that correspond to frames with
48039  ** frame numbers greater than pWal->hdr.mxFrame.
48040  */
48041  nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
48042  memset((void *)&aPgno[iLimit+1], 0, nByte);
48043
48044#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
48045  /* Verify that the every entry in the mapping region is still reachable
48046  ** via the hash table even after the cleanup.
48047  */
48048  if( iLimit ){
48049    int i;           /* Loop counter */
48050    int iKey;        /* Hash key */
48051    for(i=1; i<=iLimit; i++){
48052      for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
48053        if( aHash[iKey]==i ) break;
48054      }
48055      assert( aHash[iKey]==i );
48056    }
48057  }
48058#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
48059}
48060
48061
48062/*
48063** Set an entry in the wal-index that will map database page number
48064** pPage into WAL frame iFrame.
48065*/
48066static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
48067  int rc;                         /* Return code */
48068  u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
48069  volatile u32 *aPgno = 0;        /* Page number array */
48070  volatile ht_slot *aHash = 0;    /* Hash table */
48071
48072  rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
48073
48074  /* Assuming the wal-index file was successfully mapped, populate the
48075  ** page number array and hash table entry.
48076  */
48077  if( rc==SQLITE_OK ){
48078    int iKey;                     /* Hash table key */
48079    int idx;                      /* Value to write to hash-table slot */
48080    int nCollide;                 /* Number of hash collisions */
48081
48082    idx = iFrame - iZero;
48083    assert( idx <= HASHTABLE_NSLOT/2 + 1 );
48084
48085    /* If this is the first entry to be added to this hash-table, zero the
48086    ** entire hash table and aPgno[] array before proceding.
48087    */
48088    if( idx==1 ){
48089      int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
48090      memset((void*)&aPgno[1], 0, nByte);
48091    }
48092
48093    /* If the entry in aPgno[] is already set, then the previous writer
48094    ** must have exited unexpectedly in the middle of a transaction (after
48095    ** writing one or more dirty pages to the WAL to free up memory).
48096    ** Remove the remnants of that writers uncommitted transaction from
48097    ** the hash-table before writing any new entries.
48098    */
48099    if( aPgno[idx] ){
48100      walCleanupHash(pWal);
48101      assert( !aPgno[idx] );
48102    }
48103
48104    /* Write the aPgno[] array entry and the hash-table slot. */
48105    nCollide = idx;
48106    for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
48107      if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
48108    }
48109    aPgno[idx] = iPage;
48110    aHash[iKey] = (ht_slot)idx;
48111
48112#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
48113    /* Verify that the number of entries in the hash table exactly equals
48114    ** the number of entries in the mapping region.
48115    */
48116    {
48117      int i;           /* Loop counter */
48118      int nEntry = 0;  /* Number of entries in the hash table */
48119      for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
48120      assert( nEntry==idx );
48121    }
48122
48123    /* Verify that the every entry in the mapping region is reachable
48124    ** via the hash table.  This turns out to be a really, really expensive
48125    ** thing to check, so only do this occasionally - not on every
48126    ** iteration.
48127    */
48128    if( (idx&0x3ff)==0 ){
48129      int i;           /* Loop counter */
48130      for(i=1; i<=idx; i++){
48131        for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
48132          if( aHash[iKey]==i ) break;
48133        }
48134        assert( aHash[iKey]==i );
48135      }
48136    }
48137#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
48138  }
48139
48140
48141  return rc;
48142}
48143
48144
48145/*
48146** Recover the wal-index by reading the write-ahead log file.
48147**
48148** This routine first tries to establish an exclusive lock on the
48149** wal-index to prevent other threads/processes from doing anything
48150** with the WAL or wal-index while recovery is running.  The
48151** WAL_RECOVER_LOCK is also held so that other threads will know
48152** that this thread is running recovery.  If unable to establish
48153** the necessary locks, this routine returns SQLITE_BUSY.
48154*/
48155static int walIndexRecover(Wal *pWal){
48156  int rc;                         /* Return Code */
48157  i64 nSize;                      /* Size of log file */
48158  u32 aFrameCksum[2] = {0, 0};
48159  int iLock;                      /* Lock offset to lock for checkpoint */
48160  int nLock;                      /* Number of locks to hold */
48161
48162  /* Obtain an exclusive lock on all byte in the locking range not already
48163  ** locked by the caller. The caller is guaranteed to have locked the
48164  ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
48165  ** If successful, the same bytes that are locked here are unlocked before
48166  ** this function returns.
48167  */
48168  assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
48169  assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
48170  assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
48171  assert( pWal->writeLock );
48172  iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
48173  nLock = SQLITE_SHM_NLOCK - iLock;
48174  rc = walLockExclusive(pWal, iLock, nLock);
48175  if( rc ){
48176    return rc;
48177  }
48178  WALTRACE(("WAL%p: recovery begin...\n", pWal));
48179
48180  memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
48181
48182  rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
48183  if( rc!=SQLITE_OK ){
48184    goto recovery_error;
48185  }
48186
48187  if( nSize>WAL_HDRSIZE ){
48188    u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
48189    u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
48190    int szFrame;                  /* Number of bytes in buffer aFrame[] */
48191    u8 *aData;                    /* Pointer to data part of aFrame buffer */
48192    int iFrame;                   /* Index of last frame read */
48193    i64 iOffset;                  /* Next offset to read from log file */
48194    int szPage;                   /* Page size according to the log */
48195    u32 magic;                    /* Magic value read from WAL header */
48196    u32 version;                  /* Magic value read from WAL header */
48197    int isValid;                  /* True if this frame is valid */
48198
48199    /* Read in the WAL header. */
48200    rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
48201    if( rc!=SQLITE_OK ){
48202      goto recovery_error;
48203    }
48204
48205    /* If the database page size is not a power of two, or is greater than
48206    ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
48207    ** data. Similarly, if the 'magic' value is invalid, ignore the whole
48208    ** WAL file.
48209    */
48210    magic = sqlite3Get4byte(&aBuf[0]);
48211    szPage = sqlite3Get4byte(&aBuf[8]);
48212    if( (magic&0xFFFFFFFE)!=WAL_MAGIC
48213     || szPage&(szPage-1)
48214     || szPage>SQLITE_MAX_PAGE_SIZE
48215     || szPage<512
48216    ){
48217      goto finished;
48218    }
48219    pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
48220    pWal->szPage = szPage;
48221    pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
48222    memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
48223
48224    /* Verify that the WAL header checksum is correct */
48225    walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
48226        aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
48227    );
48228    if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
48229     || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
48230    ){
48231      goto finished;
48232    }
48233
48234    /* Verify that the version number on the WAL format is one that
48235    ** are able to understand */
48236    version = sqlite3Get4byte(&aBuf[4]);
48237    if( version!=WAL_MAX_VERSION ){
48238      rc = SQLITE_CANTOPEN_BKPT;
48239      goto finished;
48240    }
48241
48242    /* Malloc a buffer to read frames into. */
48243    szFrame = szPage + WAL_FRAME_HDRSIZE;
48244    aFrame = (u8 *)sqlite3_malloc(szFrame);
48245    if( !aFrame ){
48246      rc = SQLITE_NOMEM;
48247      goto recovery_error;
48248    }
48249    aData = &aFrame[WAL_FRAME_HDRSIZE];
48250
48251    /* Read all frames from the log file. */
48252    iFrame = 0;
48253    for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
48254      u32 pgno;                   /* Database page number for frame */
48255      u32 nTruncate;              /* dbsize field from frame header */
48256
48257      /* Read and decode the next log frame. */
48258      iFrame++;
48259      rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
48260      if( rc!=SQLITE_OK ) break;
48261      isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
48262      if( !isValid ) break;
48263      rc = walIndexAppend(pWal, iFrame, pgno);
48264      if( rc!=SQLITE_OK ) break;
48265
48266      /* If nTruncate is non-zero, this is a commit record. */
48267      if( nTruncate ){
48268        pWal->hdr.mxFrame = iFrame;
48269        pWal->hdr.nPage = nTruncate;
48270        pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
48271        testcase( szPage<=32768 );
48272        testcase( szPage>=65536 );
48273        aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
48274        aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
48275      }
48276    }
48277
48278    sqlite3_free(aFrame);
48279  }
48280
48281finished:
48282  if( rc==SQLITE_OK ){
48283    volatile WalCkptInfo *pInfo;
48284    int i;
48285    pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
48286    pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
48287    walIndexWriteHdr(pWal);
48288
48289    /* Reset the checkpoint-header. This is safe because this thread is
48290    ** currently holding locks that exclude all other readers, writers and
48291    ** checkpointers.
48292    */
48293    pInfo = walCkptInfo(pWal);
48294    pInfo->nBackfill = 0;
48295    pInfo->aReadMark[0] = 0;
48296    for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
48297    if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
48298
48299    /* If more than one frame was recovered from the log file, report an
48300    ** event via sqlite3_log(). This is to help with identifying performance
48301    ** problems caused by applications routinely shutting down without
48302    ** checkpointing the log file.
48303    */
48304    if( pWal->hdr.nPage ){
48305      sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
48306          "recovered %d frames from WAL file %s",
48307          pWal->hdr.mxFrame, pWal->zWalName
48308      );
48309    }
48310  }
48311
48312recovery_error:
48313  WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
48314  walUnlockExclusive(pWal, iLock, nLock);
48315  return rc;
48316}
48317
48318/*
48319** Close an open wal-index.
48320*/
48321static void walIndexClose(Wal *pWal, int isDelete){
48322  if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
48323    int i;
48324    for(i=0; i<pWal->nWiData; i++){
48325      sqlite3_free((void *)pWal->apWiData[i]);
48326      pWal->apWiData[i] = 0;
48327    }
48328  }else{
48329    sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
48330  }
48331}
48332
48333/*
48334** Open a connection to the WAL file zWalName. The database file must
48335** already be opened on connection pDbFd. The buffer that zWalName points
48336** to must remain valid for the lifetime of the returned Wal* handle.
48337**
48338** A SHARED lock should be held on the database file when this function
48339** is called. The purpose of this SHARED lock is to prevent any other
48340** client from unlinking the WAL or wal-index file. If another process
48341** were to do this just after this client opened one of these files, the
48342** system would be badly broken.
48343**
48344** If the log file is successfully opened, SQLITE_OK is returned and
48345** *ppWal is set to point to a new WAL handle. If an error occurs,
48346** an SQLite error code is returned and *ppWal is left unmodified.
48347*/
48348SQLITE_PRIVATE int sqlite3WalOpen(
48349  sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
48350  sqlite3_file *pDbFd,            /* The open database file */
48351  const char *zWalName,           /* Name of the WAL file */
48352  int bNoShm,                     /* True to run in heap-memory mode */
48353  i64 mxWalSize,                  /* Truncate WAL to this size on reset */
48354  Wal **ppWal                     /* OUT: Allocated Wal handle */
48355){
48356  int rc;                         /* Return Code */
48357  Wal *pRet;                      /* Object to allocate and return */
48358  int flags;                      /* Flags passed to OsOpen() */
48359
48360  assert( zWalName && zWalName[0] );
48361  assert( pDbFd );
48362
48363  /* In the amalgamation, the os_unix.c and os_win.c source files come before
48364  ** this source file.  Verify that the #defines of the locking byte offsets
48365  ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
48366  */
48367#ifdef WIN_SHM_BASE
48368  assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
48369#endif
48370#ifdef UNIX_SHM_BASE
48371  assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
48372#endif
48373
48374
48375  /* Allocate an instance of struct Wal to return. */
48376  *ppWal = 0;
48377  pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
48378  if( !pRet ){
48379    return SQLITE_NOMEM;
48380  }
48381
48382  pRet->pVfs = pVfs;
48383  pRet->pWalFd = (sqlite3_file *)&pRet[1];
48384  pRet->pDbFd = pDbFd;
48385  pRet->readLock = -1;
48386  pRet->mxWalSize = mxWalSize;
48387  pRet->zWalName = zWalName;
48388  pRet->syncHeader = 1;
48389  pRet->padToSectorBoundary = 1;
48390  pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
48391
48392  /* Open file handle on the write-ahead log file. */
48393  flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
48394  rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
48395  if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
48396    pRet->readOnly = WAL_RDONLY;
48397  }
48398
48399  if( rc!=SQLITE_OK ){
48400    walIndexClose(pRet, 0);
48401    sqlite3OsClose(pRet->pWalFd);
48402    sqlite3_free(pRet);
48403  }else{
48404    int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
48405    if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
48406    if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
48407      pRet->padToSectorBoundary = 0;
48408    }
48409    *ppWal = pRet;
48410    WALTRACE(("WAL%d: opened\n", pRet));
48411  }
48412  return rc;
48413}
48414
48415/*
48416** Change the size to which the WAL file is trucated on each reset.
48417*/
48418SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
48419  if( pWal ) pWal->mxWalSize = iLimit;
48420}
48421
48422/*
48423** Find the smallest page number out of all pages held in the WAL that
48424** has not been returned by any prior invocation of this method on the
48425** same WalIterator object.   Write into *piFrame the frame index where
48426** that page was last written into the WAL.  Write into *piPage the page
48427** number.
48428**
48429** Return 0 on success.  If there are no pages in the WAL with a page
48430** number larger than *piPage, then return 1.
48431*/
48432static int walIteratorNext(
48433  WalIterator *p,               /* Iterator */
48434  u32 *piPage,                  /* OUT: The page number of the next page */
48435  u32 *piFrame                  /* OUT: Wal frame index of next page */
48436){
48437  u32 iMin;                     /* Result pgno must be greater than iMin */
48438  u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
48439  int i;                        /* For looping through segments */
48440
48441  iMin = p->iPrior;
48442  assert( iMin<0xffffffff );
48443  for(i=p->nSegment-1; i>=0; i--){
48444    struct WalSegment *pSegment = &p->aSegment[i];
48445    while( pSegment->iNext<pSegment->nEntry ){
48446      u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
48447      if( iPg>iMin ){
48448        if( iPg<iRet ){
48449          iRet = iPg;
48450          *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
48451        }
48452        break;
48453      }
48454      pSegment->iNext++;
48455    }
48456  }
48457
48458  *piPage = p->iPrior = iRet;
48459  return (iRet==0xFFFFFFFF);
48460}
48461
48462/*
48463** This function merges two sorted lists into a single sorted list.
48464**
48465** aLeft[] and aRight[] are arrays of indices.  The sort key is
48466** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
48467** is guaranteed for all J<K:
48468**
48469**        aContent[aLeft[J]] < aContent[aLeft[K]]
48470**        aContent[aRight[J]] < aContent[aRight[K]]
48471**
48472** This routine overwrites aRight[] with a new (probably longer) sequence
48473** of indices such that the aRight[] contains every index that appears in
48474** either aLeft[] or the old aRight[] and such that the second condition
48475** above is still met.
48476**
48477** The aContent[aLeft[X]] values will be unique for all X.  And the
48478** aContent[aRight[X]] values will be unique too.  But there might be
48479** one or more combinations of X and Y such that
48480**
48481**      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
48482**
48483** When that happens, omit the aLeft[X] and use the aRight[Y] index.
48484*/
48485static void walMerge(
48486  const u32 *aContent,            /* Pages in wal - keys for the sort */
48487  ht_slot *aLeft,                 /* IN: Left hand input list */
48488  int nLeft,                      /* IN: Elements in array *paLeft */
48489  ht_slot **paRight,              /* IN/OUT: Right hand input list */
48490  int *pnRight,                   /* IN/OUT: Elements in *paRight */
48491  ht_slot *aTmp                   /* Temporary buffer */
48492){
48493  int iLeft = 0;                  /* Current index in aLeft */
48494  int iRight = 0;                 /* Current index in aRight */
48495  int iOut = 0;                   /* Current index in output buffer */
48496  int nRight = *pnRight;
48497  ht_slot *aRight = *paRight;
48498
48499  assert( nLeft>0 && nRight>0 );
48500  while( iRight<nRight || iLeft<nLeft ){
48501    ht_slot logpage;
48502    Pgno dbpage;
48503
48504    if( (iLeft<nLeft)
48505     && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
48506    ){
48507      logpage = aLeft[iLeft++];
48508    }else{
48509      logpage = aRight[iRight++];
48510    }
48511    dbpage = aContent[logpage];
48512
48513    aTmp[iOut++] = logpage;
48514    if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
48515
48516    assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
48517    assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
48518  }
48519
48520  *paRight = aLeft;
48521  *pnRight = iOut;
48522  memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
48523}
48524
48525/*
48526** Sort the elements in list aList using aContent[] as the sort key.
48527** Remove elements with duplicate keys, preferring to keep the
48528** larger aList[] values.
48529**
48530** The aList[] entries are indices into aContent[].  The values in
48531** aList[] are to be sorted so that for all J<K:
48532**
48533**      aContent[aList[J]] < aContent[aList[K]]
48534**
48535** For any X and Y such that
48536**
48537**      aContent[aList[X]] == aContent[aList[Y]]
48538**
48539** Keep the larger of the two values aList[X] and aList[Y] and discard
48540** the smaller.
48541*/
48542static void walMergesort(
48543  const u32 *aContent,            /* Pages in wal */
48544  ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
48545  ht_slot *aList,                 /* IN/OUT: List to sort */
48546  int *pnList                     /* IN/OUT: Number of elements in aList[] */
48547){
48548  struct Sublist {
48549    int nList;                    /* Number of elements in aList */
48550    ht_slot *aList;               /* Pointer to sub-list content */
48551  };
48552
48553  const int nList = *pnList;      /* Size of input list */
48554  int nMerge = 0;                 /* Number of elements in list aMerge */
48555  ht_slot *aMerge = 0;            /* List to be merged */
48556  int iList;                      /* Index into input list */
48557  int iSub = 0;                   /* Index into aSub array */
48558  struct Sublist aSub[13];        /* Array of sub-lists */
48559
48560  memset(aSub, 0, sizeof(aSub));
48561  assert( nList<=HASHTABLE_NPAGE && nList>0 );
48562  assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
48563
48564  for(iList=0; iList<nList; iList++){
48565    nMerge = 1;
48566    aMerge = &aList[iList];
48567    for(iSub=0; iList & (1<<iSub); iSub++){
48568      struct Sublist *p = &aSub[iSub];
48569      assert( p->aList && p->nList<=(1<<iSub) );
48570      assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
48571      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
48572    }
48573    aSub[iSub].aList = aMerge;
48574    aSub[iSub].nList = nMerge;
48575  }
48576
48577  for(iSub++; iSub<ArraySize(aSub); iSub++){
48578    if( nList & (1<<iSub) ){
48579      struct Sublist *p = &aSub[iSub];
48580      assert( p->nList<=(1<<iSub) );
48581      assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
48582      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
48583    }
48584  }
48585  assert( aMerge==aList );
48586  *pnList = nMerge;
48587
48588#ifdef SQLITE_DEBUG
48589  {
48590    int i;
48591    for(i=1; i<*pnList; i++){
48592      assert( aContent[aList[i]] > aContent[aList[i-1]] );
48593    }
48594  }
48595#endif
48596}
48597
48598/*
48599** Free an iterator allocated by walIteratorInit().
48600*/
48601static void walIteratorFree(WalIterator *p){
48602  sqlite3ScratchFree(p);
48603}
48604
48605/*
48606** Construct a WalInterator object that can be used to loop over all
48607** pages in the WAL in ascending order. The caller must hold the checkpoint
48608** lock.
48609**
48610** On success, make *pp point to the newly allocated WalInterator object
48611** return SQLITE_OK. Otherwise, return an error code. If this routine
48612** returns an error, the value of *pp is undefined.
48613**
48614** The calling routine should invoke walIteratorFree() to destroy the
48615** WalIterator object when it has finished with it.
48616*/
48617static int walIteratorInit(Wal *pWal, WalIterator **pp){
48618  WalIterator *p;                 /* Return value */
48619  int nSegment;                   /* Number of segments to merge */
48620  u32 iLast;                      /* Last frame in log */
48621  int nByte;                      /* Number of bytes to allocate */
48622  int i;                          /* Iterator variable */
48623  ht_slot *aTmp;                  /* Temp space used by merge-sort */
48624  int rc = SQLITE_OK;             /* Return Code */
48625
48626  /* This routine only runs while holding the checkpoint lock. And
48627  ** it only runs if there is actually content in the log (mxFrame>0).
48628  */
48629  assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
48630  iLast = pWal->hdr.mxFrame;
48631
48632  /* Allocate space for the WalIterator object. */
48633  nSegment = walFramePage(iLast) + 1;
48634  nByte = sizeof(WalIterator)
48635        + (nSegment-1)*sizeof(struct WalSegment)
48636        + iLast*sizeof(ht_slot);
48637  p = (WalIterator *)sqlite3ScratchMalloc(nByte);
48638  if( !p ){
48639    return SQLITE_NOMEM;
48640  }
48641  memset(p, 0, nByte);
48642  p->nSegment = nSegment;
48643
48644  /* Allocate temporary space used by the merge-sort routine. This block
48645  ** of memory will be freed before this function returns.
48646  */
48647  aTmp = (ht_slot *)sqlite3ScratchMalloc(
48648      sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
48649  );
48650  if( !aTmp ){
48651    rc = SQLITE_NOMEM;
48652  }
48653
48654  for(i=0; rc==SQLITE_OK && i<nSegment; i++){
48655    volatile ht_slot *aHash;
48656    u32 iZero;
48657    volatile u32 *aPgno;
48658
48659    rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
48660    if( rc==SQLITE_OK ){
48661      int j;                      /* Counter variable */
48662      int nEntry;                 /* Number of entries in this segment */
48663      ht_slot *aIndex;            /* Sorted index for this segment */
48664
48665      aPgno++;
48666      if( (i+1)==nSegment ){
48667        nEntry = (int)(iLast - iZero);
48668      }else{
48669        nEntry = (int)((u32*)aHash - (u32*)aPgno);
48670      }
48671      aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
48672      iZero++;
48673
48674      for(j=0; j<nEntry; j++){
48675        aIndex[j] = (ht_slot)j;
48676      }
48677      walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
48678      p->aSegment[i].iZero = iZero;
48679      p->aSegment[i].nEntry = nEntry;
48680      p->aSegment[i].aIndex = aIndex;
48681      p->aSegment[i].aPgno = (u32 *)aPgno;
48682    }
48683  }
48684  sqlite3ScratchFree(aTmp);
48685
48686  if( rc!=SQLITE_OK ){
48687    walIteratorFree(p);
48688  }
48689  *pp = p;
48690  return rc;
48691}
48692
48693/*
48694** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
48695** n. If the attempt fails and parameter xBusy is not NULL, then it is a
48696** busy-handler function. Invoke it and retry the lock until either the
48697** lock is successfully obtained or the busy-handler returns 0.
48698*/
48699static int walBusyLock(
48700  Wal *pWal,                      /* WAL connection */
48701  int (*xBusy)(void*),            /* Function to call when busy */
48702  void *pBusyArg,                 /* Context argument for xBusyHandler */
48703  int lockIdx,                    /* Offset of first byte to lock */
48704  int n                           /* Number of bytes to lock */
48705){
48706  int rc;
48707  do {
48708    rc = walLockExclusive(pWal, lockIdx, n);
48709  }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
48710  return rc;
48711}
48712
48713/*
48714** The cache of the wal-index header must be valid to call this function.
48715** Return the page-size in bytes used by the database.
48716*/
48717static int walPagesize(Wal *pWal){
48718  return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
48719}
48720
48721/*
48722** Copy as much content as we can from the WAL back into the database file
48723** in response to an sqlite3_wal_checkpoint() request or the equivalent.
48724**
48725** The amount of information copies from WAL to database might be limited
48726** by active readers.  This routine will never overwrite a database page
48727** that a concurrent reader might be using.
48728**
48729** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
48730** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if
48731** checkpoints are always run by a background thread or background
48732** process, foreground threads will never block on a lengthy fsync call.
48733**
48734** Fsync is called on the WAL before writing content out of the WAL and
48735** into the database.  This ensures that if the new content is persistent
48736** in the WAL and can be recovered following a power-loss or hard reset.
48737**
48738** Fsync is also called on the database file if (and only if) the entire
48739** WAL content is copied into the database file.  This second fsync makes
48740** it safe to delete the WAL since the new content will persist in the
48741** database file.
48742**
48743** This routine uses and updates the nBackfill field of the wal-index header.
48744** This is the only routine tha will increase the value of nBackfill.
48745** (A WAL reset or recovery will revert nBackfill to zero, but not increase
48746** its value.)
48747**
48748** The caller must be holding sufficient locks to ensure that no other
48749** checkpoint is running (in any other thread or process) at the same
48750** time.
48751*/
48752static int walCheckpoint(
48753  Wal *pWal,                      /* Wal connection */
48754  int eMode,                      /* One of PASSIVE, FULL or RESTART */
48755  int (*xBusyCall)(void*),        /* Function to call when busy */
48756  void *pBusyArg,                 /* Context argument for xBusyHandler */
48757  int sync_flags,                 /* Flags for OsSync() (or 0) */
48758  u8 *zBuf                        /* Temporary buffer to use */
48759){
48760  int rc;                         /* Return code */
48761  int szPage;                     /* Database page-size */
48762  WalIterator *pIter = 0;         /* Wal iterator context */
48763  u32 iDbpage = 0;                /* Next database page to write */
48764  u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
48765  u32 mxSafeFrame;                /* Max frame that can be backfilled */
48766  u32 mxPage;                     /* Max database page to write */
48767  int i;                          /* Loop counter */
48768  volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
48769  int (*xBusy)(void*) = 0;        /* Function to call when waiting for locks */
48770
48771  szPage = walPagesize(pWal);
48772  testcase( szPage<=32768 );
48773  testcase( szPage>=65536 );
48774  pInfo = walCkptInfo(pWal);
48775  if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
48776
48777  /* Allocate the iterator */
48778  rc = walIteratorInit(pWal, &pIter);
48779  if( rc!=SQLITE_OK ){
48780    return rc;
48781  }
48782  assert( pIter );
48783
48784  if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
48785
48786  /* Compute in mxSafeFrame the index of the last frame of the WAL that is
48787  ** safe to write into the database.  Frames beyond mxSafeFrame might
48788  ** overwrite database pages that are in use by active readers and thus
48789  ** cannot be backfilled from the WAL.
48790  */
48791  mxSafeFrame = pWal->hdr.mxFrame;
48792  mxPage = pWal->hdr.nPage;
48793  for(i=1; i<WAL_NREADER; i++){
48794    u32 y = pInfo->aReadMark[i];
48795    if( mxSafeFrame>y ){
48796      assert( y<=pWal->hdr.mxFrame );
48797      rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
48798      if( rc==SQLITE_OK ){
48799        pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
48800        walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
48801      }else if( rc==SQLITE_BUSY ){
48802        mxSafeFrame = y;
48803        xBusy = 0;
48804      }else{
48805        goto walcheckpoint_out;
48806      }
48807    }
48808  }
48809
48810  if( pInfo->nBackfill<mxSafeFrame
48811   && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
48812  ){
48813    i64 nSize;                    /* Current size of database file */
48814    u32 nBackfill = pInfo->nBackfill;
48815
48816    /* Sync the WAL to disk */
48817    if( sync_flags ){
48818      rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
48819    }
48820
48821    /* If the database may grow as a result of this checkpoint, hint
48822    ** about the eventual size of the db file to the VFS layer.
48823    */
48824    if( rc==SQLITE_OK ){
48825      i64 nReq = ((i64)mxPage * szPage);
48826      rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
48827      if( rc==SQLITE_OK && nSize<nReq ){
48828        sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
48829      }
48830    }
48831
48832
48833    /* Iterate through the contents of the WAL, copying data to the db file. */
48834    while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
48835      i64 iOffset;
48836      assert( walFramePgno(pWal, iFrame)==iDbpage );
48837      if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
48838      iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
48839      /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
48840      rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
48841      if( rc!=SQLITE_OK ) break;
48842      iOffset = (iDbpage-1)*(i64)szPage;
48843      testcase( IS_BIG_INT(iOffset) );
48844      rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
48845      if( rc!=SQLITE_OK ) break;
48846    }
48847
48848    /* If work was actually accomplished... */
48849    if( rc==SQLITE_OK ){
48850      if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
48851        i64 szDb = pWal->hdr.nPage*(i64)szPage;
48852        testcase( IS_BIG_INT(szDb) );
48853        rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
48854        if( rc==SQLITE_OK && sync_flags ){
48855          rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
48856        }
48857      }
48858      if( rc==SQLITE_OK ){
48859        pInfo->nBackfill = mxSafeFrame;
48860      }
48861    }
48862
48863    /* Release the reader lock held while backfilling */
48864    walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
48865  }
48866
48867  if( rc==SQLITE_BUSY ){
48868    /* Reset the return code so as not to report a checkpoint failure
48869    ** just because there are active readers.  */
48870    rc = SQLITE_OK;
48871  }
48872
48873  /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
48874  ** file has been copied into the database file, then block until all
48875  ** readers have finished using the wal file. This ensures that the next
48876  ** process to write to the database restarts the wal file.
48877  */
48878  if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
48879    assert( pWal->writeLock );
48880    if( pInfo->nBackfill<pWal->hdr.mxFrame ){
48881      rc = SQLITE_BUSY;
48882    }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
48883      assert( mxSafeFrame==pWal->hdr.mxFrame );
48884      rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
48885      if( rc==SQLITE_OK ){
48886        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
48887      }
48888    }
48889  }
48890
48891 walcheckpoint_out:
48892  walIteratorFree(pIter);
48893  return rc;
48894}
48895
48896/*
48897** If the WAL file is currently larger than nMax bytes in size, truncate
48898** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
48899*/
48900static void walLimitSize(Wal *pWal, i64 nMax){
48901  i64 sz;
48902  int rx;
48903  sqlite3BeginBenignMalloc();
48904  rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
48905  if( rx==SQLITE_OK && (sz > nMax ) ){
48906    rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
48907  }
48908  sqlite3EndBenignMalloc();
48909  if( rx ){
48910    sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
48911  }
48912}
48913
48914/*
48915** Close a connection to a log file.
48916*/
48917SQLITE_PRIVATE int sqlite3WalClose(
48918  Wal *pWal,                      /* Wal to close */
48919  int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
48920  int nBuf,
48921  u8 *zBuf                        /* Buffer of at least nBuf bytes */
48922){
48923  int rc = SQLITE_OK;
48924  if( pWal ){
48925    int isDelete = 0;             /* True to unlink wal and wal-index files */
48926
48927    /* If an EXCLUSIVE lock can be obtained on the database file (using the
48928    ** ordinary, rollback-mode locking methods, this guarantees that the
48929    ** connection associated with this log file is the only connection to
48930    ** the database. In this case checkpoint the database and unlink both
48931    ** the wal and wal-index files.
48932    **
48933    ** The EXCLUSIVE lock is not released before returning.
48934    */
48935    rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
48936    if( rc==SQLITE_OK ){
48937      if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
48938        pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
48939      }
48940      rc = sqlite3WalCheckpoint(
48941          pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
48942      );
48943      if( rc==SQLITE_OK ){
48944        int bPersist = -1;
48945        sqlite3OsFileControlHint(
48946            pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
48947        );
48948        if( bPersist!=1 ){
48949          /* Try to delete the WAL file if the checkpoint completed and
48950          ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
48951          ** mode (!bPersist) */
48952          isDelete = 1;
48953        }else if( pWal->mxWalSize>=0 ){
48954          /* Try to truncate the WAL file to zero bytes if the checkpoint
48955          ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
48956          ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
48957          ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
48958          ** to zero bytes as truncating to the journal_size_limit might
48959          ** leave a corrupt WAL file on disk. */
48960          walLimitSize(pWal, 0);
48961        }
48962      }
48963    }
48964
48965    walIndexClose(pWal, isDelete);
48966    sqlite3OsClose(pWal->pWalFd);
48967    if( isDelete ){
48968      sqlite3BeginBenignMalloc();
48969      sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
48970      sqlite3EndBenignMalloc();
48971    }
48972    WALTRACE(("WAL%p: closed\n", pWal));
48973    sqlite3_free((void *)pWal->apWiData);
48974    sqlite3_free(pWal);
48975  }
48976  return rc;
48977}
48978
48979/*
48980** Try to read the wal-index header.  Return 0 on success and 1 if
48981** there is a problem.
48982**
48983** The wal-index is in shared memory.  Another thread or process might
48984** be writing the header at the same time this procedure is trying to
48985** read it, which might result in inconsistency.  A dirty read is detected
48986** by verifying that both copies of the header are the same and also by
48987** a checksum on the header.
48988**
48989** If and only if the read is consistent and the header is different from
48990** pWal->hdr, then pWal->hdr is updated to the content of the new header
48991** and *pChanged is set to 1.
48992**
48993** If the checksum cannot be verified return non-zero. If the header
48994** is read successfully and the checksum verified, return zero.
48995*/
48996static int walIndexTryHdr(Wal *pWal, int *pChanged){
48997  u32 aCksum[2];                  /* Checksum on the header content */
48998  WalIndexHdr h1, h2;             /* Two copies of the header content */
48999  WalIndexHdr volatile *aHdr;     /* Header in shared memory */
49000
49001  /* The first page of the wal-index must be mapped at this point. */
49002  assert( pWal->nWiData>0 && pWal->apWiData[0] );
49003
49004  /* Read the header. This might happen concurrently with a write to the
49005  ** same area of shared memory on a different CPU in a SMP,
49006  ** meaning it is possible that an inconsistent snapshot is read
49007  ** from the file. If this happens, return non-zero.
49008  **
49009  ** There are two copies of the header at the beginning of the wal-index.
49010  ** When reading, read [0] first then [1].  Writes are in the reverse order.
49011  ** Memory barriers are used to prevent the compiler or the hardware from
49012  ** reordering the reads and writes.
49013  */
49014  aHdr = walIndexHdr(pWal);
49015  memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
49016  walShmBarrier(pWal);
49017  memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
49018
49019  if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
49020    return 1;   /* Dirty read */
49021  }
49022  if( h1.isInit==0 ){
49023    return 1;   /* Malformed header - probably all zeros */
49024  }
49025  walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
49026  if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
49027    return 1;   /* Checksum does not match */
49028  }
49029
49030  if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
49031    *pChanged = 1;
49032    memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
49033    pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
49034    testcase( pWal->szPage<=32768 );
49035    testcase( pWal->szPage>=65536 );
49036  }
49037
49038  /* The header was successfully read. Return zero. */
49039  return 0;
49040}
49041
49042/*
49043** Read the wal-index header from the wal-index and into pWal->hdr.
49044** If the wal-header appears to be corrupt, try to reconstruct the
49045** wal-index from the WAL before returning.
49046**
49047** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
49048** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
49049** to 0.
49050**
49051** If the wal-index header is successfully read, return SQLITE_OK.
49052** Otherwise an SQLite error code.
49053*/
49054static int walIndexReadHdr(Wal *pWal, int *pChanged){
49055  int rc;                         /* Return code */
49056  int badHdr;                     /* True if a header read failed */
49057  volatile u32 *page0;            /* Chunk of wal-index containing header */
49058
49059  /* Ensure that page 0 of the wal-index (the page that contains the
49060  ** wal-index header) is mapped. Return early if an error occurs here.
49061  */
49062  assert( pChanged );
49063  rc = walIndexPage(pWal, 0, &page0);
49064  if( rc!=SQLITE_OK ){
49065    return rc;
49066  };
49067  assert( page0 || pWal->writeLock==0 );
49068
49069  /* If the first page of the wal-index has been mapped, try to read the
49070  ** wal-index header immediately, without holding any lock. This usually
49071  ** works, but may fail if the wal-index header is corrupt or currently
49072  ** being modified by another thread or process.
49073  */
49074  badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
49075
49076  /* If the first attempt failed, it might have been due to a race
49077  ** with a writer.  So get a WRITE lock and try again.
49078  */
49079  assert( badHdr==0 || pWal->writeLock==0 );
49080  if( badHdr ){
49081    if( pWal->readOnly & WAL_SHM_RDONLY ){
49082      if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
49083        walUnlockShared(pWal, WAL_WRITE_LOCK);
49084        rc = SQLITE_READONLY_RECOVERY;
49085      }
49086    }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
49087      pWal->writeLock = 1;
49088      if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
49089        badHdr = walIndexTryHdr(pWal, pChanged);
49090        if( badHdr ){
49091          /* If the wal-index header is still malformed even while holding
49092          ** a WRITE lock, it can only mean that the header is corrupted and
49093          ** needs to be reconstructed.  So run recovery to do exactly that.
49094          */
49095          rc = walIndexRecover(pWal);
49096          *pChanged = 1;
49097        }
49098      }
49099      pWal->writeLock = 0;
49100      walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
49101    }
49102  }
49103
49104  /* If the header is read successfully, check the version number to make
49105  ** sure the wal-index was not constructed with some future format that
49106  ** this version of SQLite cannot understand.
49107  */
49108  if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
49109    rc = SQLITE_CANTOPEN_BKPT;
49110  }
49111
49112  return rc;
49113}
49114
49115/*
49116** This is the value that walTryBeginRead returns when it needs to
49117** be retried.
49118*/
49119#define WAL_RETRY  (-1)
49120
49121/*
49122** Attempt to start a read transaction.  This might fail due to a race or
49123** other transient condition.  When that happens, it returns WAL_RETRY to
49124** indicate to the caller that it is safe to retry immediately.
49125**
49126** On success return SQLITE_OK.  On a permanent failure (such an
49127** I/O error or an SQLITE_BUSY because another process is running
49128** recovery) return a positive error code.
49129**
49130** The useWal parameter is true to force the use of the WAL and disable
49131** the case where the WAL is bypassed because it has been completely
49132** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr()
49133** to make a copy of the wal-index header into pWal->hdr.  If the
49134** wal-index header has changed, *pChanged is set to 1 (as an indication
49135** to the caller that the local paget cache is obsolete and needs to be
49136** flushed.)  When useWal==1, the wal-index header is assumed to already
49137** be loaded and the pChanged parameter is unused.
49138**
49139** The caller must set the cnt parameter to the number of prior calls to
49140** this routine during the current read attempt that returned WAL_RETRY.
49141** This routine will start taking more aggressive measures to clear the
49142** race conditions after multiple WAL_RETRY returns, and after an excessive
49143** number of errors will ultimately return SQLITE_PROTOCOL.  The
49144** SQLITE_PROTOCOL return indicates that some other process has gone rogue
49145** and is not honoring the locking protocol.  There is a vanishingly small
49146** chance that SQLITE_PROTOCOL could be returned because of a run of really
49147** bad luck when there is lots of contention for the wal-index, but that
49148** possibility is so small that it can be safely neglected, we believe.
49149**
49150** On success, this routine obtains a read lock on
49151** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
49152** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
49153** that means the Wal does not hold any read lock.  The reader must not
49154** access any database page that is modified by a WAL frame up to and
49155** including frame number aReadMark[pWal->readLock].  The reader will
49156** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
49157** Or if pWal->readLock==0, then the reader will ignore the WAL
49158** completely and get all content directly from the database file.
49159** If the useWal parameter is 1 then the WAL will never be ignored and
49160** this routine will always set pWal->readLock>0 on success.
49161** When the read transaction is completed, the caller must release the
49162** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
49163**
49164** This routine uses the nBackfill and aReadMark[] fields of the header
49165** to select a particular WAL_READ_LOCK() that strives to let the
49166** checkpoint process do as much work as possible.  This routine might
49167** update values of the aReadMark[] array in the header, but if it does
49168** so it takes care to hold an exclusive lock on the corresponding
49169** WAL_READ_LOCK() while changing values.
49170*/
49171static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
49172  volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
49173  u32 mxReadMark;                 /* Largest aReadMark[] value */
49174  int mxI;                        /* Index of largest aReadMark[] value */
49175  int i;                          /* Loop counter */
49176  int rc = SQLITE_OK;             /* Return code  */
49177
49178  assert( pWal->readLock<0 );     /* Not currently locked */
49179
49180  /* Take steps to avoid spinning forever if there is a protocol error.
49181  **
49182  ** Circumstances that cause a RETRY should only last for the briefest
49183  ** instances of time.  No I/O or other system calls are done while the
49184  ** locks are held, so the locks should not be held for very long. But
49185  ** if we are unlucky, another process that is holding a lock might get
49186  ** paged out or take a page-fault that is time-consuming to resolve,
49187  ** during the few nanoseconds that it is holding the lock.  In that case,
49188  ** it might take longer than normal for the lock to free.
49189  **
49190  ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
49191  ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
49192  ** is more of a scheduler yield than an actual delay.  But on the 10th
49193  ** an subsequent retries, the delays start becoming longer and longer,
49194  ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
49195  ** The total delay time before giving up is less than 1 second.
49196  */
49197  if( cnt>5 ){
49198    int nDelay = 1;                      /* Pause time in microseconds */
49199    if( cnt>100 ){
49200      VVA_ONLY( pWal->lockError = 1; )
49201      return SQLITE_PROTOCOL;
49202    }
49203    if( cnt>=10 ) nDelay = (cnt-9)*238;  /* Max delay 21ms. Total delay 996ms */
49204    sqlite3OsSleep(pWal->pVfs, nDelay);
49205  }
49206
49207  if( !useWal ){
49208    rc = walIndexReadHdr(pWal, pChanged);
49209    if( rc==SQLITE_BUSY ){
49210      /* If there is not a recovery running in another thread or process
49211      ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
49212      ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
49213      ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
49214      ** would be technically correct.  But the race is benign since with
49215      ** WAL_RETRY this routine will be called again and will probably be
49216      ** right on the second iteration.
49217      */
49218      if( pWal->apWiData[0]==0 ){
49219        /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
49220        ** We assume this is a transient condition, so return WAL_RETRY. The
49221        ** xShmMap() implementation used by the default unix and win32 VFS
49222        ** modules may return SQLITE_BUSY due to a race condition in the
49223        ** code that determines whether or not the shared-memory region
49224        ** must be zeroed before the requested page is returned.
49225        */
49226        rc = WAL_RETRY;
49227      }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
49228        walUnlockShared(pWal, WAL_RECOVER_LOCK);
49229        rc = WAL_RETRY;
49230      }else if( rc==SQLITE_BUSY ){
49231        rc = SQLITE_BUSY_RECOVERY;
49232      }
49233    }
49234    if( rc!=SQLITE_OK ){
49235      return rc;
49236    }
49237  }
49238
49239  pInfo = walCkptInfo(pWal);
49240  if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
49241    /* The WAL has been completely backfilled (or it is empty).
49242    ** and can be safely ignored.
49243    */
49244    rc = walLockShared(pWal, WAL_READ_LOCK(0));
49245    walShmBarrier(pWal);
49246    if( rc==SQLITE_OK ){
49247      if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
49248        /* It is not safe to allow the reader to continue here if frames
49249        ** may have been appended to the log before READ_LOCK(0) was obtained.
49250        ** When holding READ_LOCK(0), the reader ignores the entire log file,
49251        ** which implies that the database file contains a trustworthy
49252        ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
49253        ** happening, this is usually correct.
49254        **
49255        ** However, if frames have been appended to the log (or if the log
49256        ** is wrapped and written for that matter) before the READ_LOCK(0)
49257        ** is obtained, that is not necessarily true. A checkpointer may
49258        ** have started to backfill the appended frames but crashed before
49259        ** it finished. Leaving a corrupt image in the database file.
49260        */
49261        walUnlockShared(pWal, WAL_READ_LOCK(0));
49262        return WAL_RETRY;
49263      }
49264      pWal->readLock = 0;
49265      return SQLITE_OK;
49266    }else if( rc!=SQLITE_BUSY ){
49267      return rc;
49268    }
49269  }
49270
49271  /* If we get this far, it means that the reader will want to use
49272  ** the WAL to get at content from recent commits.  The job now is
49273  ** to select one of the aReadMark[] entries that is closest to
49274  ** but not exceeding pWal->hdr.mxFrame and lock that entry.
49275  */
49276  mxReadMark = 0;
49277  mxI = 0;
49278  for(i=1; i<WAL_NREADER; i++){
49279    u32 thisMark = pInfo->aReadMark[i];
49280    if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
49281      assert( thisMark!=READMARK_NOT_USED );
49282      mxReadMark = thisMark;
49283      mxI = i;
49284    }
49285  }
49286  /* There was once an "if" here. The extra "{" is to preserve indentation. */
49287  {
49288    if( (pWal->readOnly & WAL_SHM_RDONLY)==0
49289     && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
49290    ){
49291      for(i=1; i<WAL_NREADER; i++){
49292        rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
49293        if( rc==SQLITE_OK ){
49294          mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
49295          mxI = i;
49296          walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
49297          break;
49298        }else if( rc!=SQLITE_BUSY ){
49299          return rc;
49300        }
49301      }
49302    }
49303    if( mxI==0 ){
49304      assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
49305      return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
49306    }
49307
49308    rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
49309    if( rc ){
49310      return rc==SQLITE_BUSY ? WAL_RETRY : rc;
49311    }
49312    /* Now that the read-lock has been obtained, check that neither the
49313    ** value in the aReadMark[] array or the contents of the wal-index
49314    ** header have changed.
49315    **
49316    ** It is necessary to check that the wal-index header did not change
49317    ** between the time it was read and when the shared-lock was obtained
49318    ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
49319    ** that the log file may have been wrapped by a writer, or that frames
49320    ** that occur later in the log than pWal->hdr.mxFrame may have been
49321    ** copied into the database by a checkpointer. If either of these things
49322    ** happened, then reading the database with the current value of
49323    ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
49324    ** instead.
49325    **
49326    ** This does not guarantee that the copy of the wal-index header is up to
49327    ** date before proceeding. That would not be possible without somehow
49328    ** blocking writers. It only guarantees that a dangerous checkpoint or
49329    ** log-wrap (either of which would require an exclusive lock on
49330    ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
49331    */
49332    walShmBarrier(pWal);
49333    if( pInfo->aReadMark[mxI]!=mxReadMark
49334     || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
49335    ){
49336      walUnlockShared(pWal, WAL_READ_LOCK(mxI));
49337      return WAL_RETRY;
49338    }else{
49339      assert( mxReadMark<=pWal->hdr.mxFrame );
49340      pWal->readLock = (i16)mxI;
49341    }
49342  }
49343  return rc;
49344}
49345
49346/*
49347** Begin a read transaction on the database.
49348**
49349** This routine used to be called sqlite3OpenSnapshot() and with good reason:
49350** it takes a snapshot of the state of the WAL and wal-index for the current
49351** instant in time.  The current thread will continue to use this snapshot.
49352** Other threads might append new content to the WAL and wal-index but
49353** that extra content is ignored by the current thread.
49354**
49355** If the database contents have changes since the previous read
49356** transaction, then *pChanged is set to 1 before returning.  The
49357** Pager layer will use this to know that is cache is stale and
49358** needs to be flushed.
49359*/
49360SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
49361  int rc;                         /* Return code */
49362  int cnt = 0;                    /* Number of TryBeginRead attempts */
49363
49364  do{
49365    rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
49366  }while( rc==WAL_RETRY );
49367  testcase( (rc&0xff)==SQLITE_BUSY );
49368  testcase( (rc&0xff)==SQLITE_IOERR );
49369  testcase( rc==SQLITE_PROTOCOL );
49370  testcase( rc==SQLITE_OK );
49371  return rc;
49372}
49373
49374/*
49375** Finish with a read transaction.  All this does is release the
49376** read-lock.
49377*/
49378SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
49379  sqlite3WalEndWriteTransaction(pWal);
49380  if( pWal->readLock>=0 ){
49381    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
49382    pWal->readLock = -1;
49383  }
49384}
49385
49386/*
49387** Search the wal file for page pgno. If found, set *piRead to the frame that
49388** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
49389** to zero.
49390**
49391** Return SQLITE_OK if successful, or an error code if an error occurs. If an
49392** error does occur, the final value of *piRead is undefined.
49393*/
49394SQLITE_PRIVATE int sqlite3WalFindFrame(
49395  Wal *pWal,                      /* WAL handle */
49396  Pgno pgno,                      /* Database page number to read data for */
49397  u32 *piRead                     /* OUT: Frame number (or zero) */
49398){
49399  u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
49400  u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
49401  int iHash;                      /* Used to loop through N hash tables */
49402
49403  /* This routine is only be called from within a read transaction. */
49404  assert( pWal->readLock>=0 || pWal->lockError );
49405
49406  /* If the "last page" field of the wal-index header snapshot is 0, then
49407  ** no data will be read from the wal under any circumstances. Return early
49408  ** in this case as an optimization.  Likewise, if pWal->readLock==0,
49409  ** then the WAL is ignored by the reader so return early, as if the
49410  ** WAL were empty.
49411  */
49412  if( iLast==0 || pWal->readLock==0 ){
49413    *piRead = 0;
49414    return SQLITE_OK;
49415  }
49416
49417  /* Search the hash table or tables for an entry matching page number
49418  ** pgno. Each iteration of the following for() loop searches one
49419  ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
49420  **
49421  ** This code might run concurrently to the code in walIndexAppend()
49422  ** that adds entries to the wal-index (and possibly to this hash
49423  ** table). This means the value just read from the hash
49424  ** slot (aHash[iKey]) may have been added before or after the
49425  ** current read transaction was opened. Values added after the
49426  ** read transaction was opened may have been written incorrectly -
49427  ** i.e. these slots may contain garbage data. However, we assume
49428  ** that any slots written before the current read transaction was
49429  ** opened remain unmodified.
49430  **
49431  ** For the reasons above, the if(...) condition featured in the inner
49432  ** loop of the following block is more stringent that would be required
49433  ** if we had exclusive access to the hash-table:
49434  **
49435  **   (aPgno[iFrame]==pgno):
49436  **     This condition filters out normal hash-table collisions.
49437  **
49438  **   (iFrame<=iLast):
49439  **     This condition filters out entries that were added to the hash
49440  **     table after the current read-transaction had started.
49441  */
49442  for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
49443    volatile ht_slot *aHash;      /* Pointer to hash table */
49444    volatile u32 *aPgno;          /* Pointer to array of page numbers */
49445    u32 iZero;                    /* Frame number corresponding to aPgno[0] */
49446    int iKey;                     /* Hash slot index */
49447    int nCollide;                 /* Number of hash collisions remaining */
49448    int rc;                       /* Error code */
49449
49450    rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
49451    if( rc!=SQLITE_OK ){
49452      return rc;
49453    }
49454    nCollide = HASHTABLE_NSLOT;
49455    for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
49456      u32 iFrame = aHash[iKey] + iZero;
49457      if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
49458        /* assert( iFrame>iRead ); -- not true if there is corruption */
49459        iRead = iFrame;
49460      }
49461      if( (nCollide--)==0 ){
49462        return SQLITE_CORRUPT_BKPT;
49463      }
49464    }
49465  }
49466
49467#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
49468  /* If expensive assert() statements are available, do a linear search
49469  ** of the wal-index file content. Make sure the results agree with the
49470  ** result obtained using the hash indexes above.  */
49471  {
49472    u32 iRead2 = 0;
49473    u32 iTest;
49474    for(iTest=iLast; iTest>0; iTest--){
49475      if( walFramePgno(pWal, iTest)==pgno ){
49476        iRead2 = iTest;
49477        break;
49478      }
49479    }
49480    assert( iRead==iRead2 );
49481  }
49482#endif
49483
49484  *piRead = iRead;
49485  return SQLITE_OK;
49486}
49487
49488/*
49489** Read the contents of frame iRead from the wal file into buffer pOut
49490** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
49491** error code otherwise.
49492*/
49493SQLITE_PRIVATE int sqlite3WalReadFrame(
49494  Wal *pWal,                      /* WAL handle */
49495  u32 iRead,                      /* Frame to read */
49496  int nOut,                       /* Size of buffer pOut in bytes */
49497  u8 *pOut                        /* Buffer to write page data to */
49498){
49499  int sz;
49500  i64 iOffset;
49501  sz = pWal->hdr.szPage;
49502  sz = (sz&0xfe00) + ((sz&0x0001)<<16);
49503  testcase( sz<=32768 );
49504  testcase( sz>=65536 );
49505  iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
49506  /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
49507  return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
49508}
49509
49510/*
49511** Return the size of the database in pages (or zero, if unknown).
49512*/
49513SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
49514  if( pWal && ALWAYS(pWal->readLock>=0) ){
49515    return pWal->hdr.nPage;
49516  }
49517  return 0;
49518}
49519
49520
49521/*
49522** This function starts a write transaction on the WAL.
49523**
49524** A read transaction must have already been started by a prior call
49525** to sqlite3WalBeginReadTransaction().
49526**
49527** If another thread or process has written into the database since
49528** the read transaction was started, then it is not possible for this
49529** thread to write as doing so would cause a fork.  So this routine
49530** returns SQLITE_BUSY in that case and no write transaction is started.
49531**
49532** There can only be a single writer active at a time.
49533*/
49534SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
49535  int rc;
49536
49537  /* Cannot start a write transaction without first holding a read
49538  ** transaction. */
49539  assert( pWal->readLock>=0 );
49540
49541  if( pWal->readOnly ){
49542    return SQLITE_READONLY;
49543  }
49544
49545  /* Only one writer allowed at a time.  Get the write lock.  Return
49546  ** SQLITE_BUSY if unable.
49547  */
49548  rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
49549  if( rc ){
49550    return rc;
49551  }
49552  pWal->writeLock = 1;
49553
49554  /* If another connection has written to the database file since the
49555  ** time the read transaction on this connection was started, then
49556  ** the write is disallowed.
49557  */
49558  if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
49559    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
49560    pWal->writeLock = 0;
49561    rc = SQLITE_BUSY_SNAPSHOT;
49562  }
49563
49564  return rc;
49565}
49566
49567/*
49568** End a write transaction.  The commit has already been done.  This
49569** routine merely releases the lock.
49570*/
49571SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
49572  if( pWal->writeLock ){
49573    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
49574    pWal->writeLock = 0;
49575    pWal->truncateOnCommit = 0;
49576  }
49577  return SQLITE_OK;
49578}
49579
49580/*
49581** If any data has been written (but not committed) to the log file, this
49582** function moves the write-pointer back to the start of the transaction.
49583**
49584** Additionally, the callback function is invoked for each frame written
49585** to the WAL since the start of the transaction. If the callback returns
49586** other than SQLITE_OK, it is not invoked again and the error code is
49587** returned to the caller.
49588**
49589** Otherwise, if the callback function does not return an error, this
49590** function returns SQLITE_OK.
49591*/
49592SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
49593  int rc = SQLITE_OK;
49594  if( ALWAYS(pWal->writeLock) ){
49595    Pgno iMax = pWal->hdr.mxFrame;
49596    Pgno iFrame;
49597
49598    /* Restore the clients cache of the wal-index header to the state it
49599    ** was in before the client began writing to the database.
49600    */
49601    memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
49602
49603    for(iFrame=pWal->hdr.mxFrame+1;
49604        ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
49605        iFrame++
49606    ){
49607      /* This call cannot fail. Unless the page for which the page number
49608      ** is passed as the second argument is (a) in the cache and
49609      ** (b) has an outstanding reference, then xUndo is either a no-op
49610      ** (if (a) is false) or simply expels the page from the cache (if (b)
49611      ** is false).
49612      **
49613      ** If the upper layer is doing a rollback, it is guaranteed that there
49614      ** are no outstanding references to any page other than page 1. And
49615      ** page 1 is never written to the log until the transaction is
49616      ** committed. As a result, the call to xUndo may not fail.
49617      */
49618      assert( walFramePgno(pWal, iFrame)!=1 );
49619      rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
49620    }
49621    if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
49622  }
49623  assert( rc==SQLITE_OK );
49624  return rc;
49625}
49626
49627/*
49628** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
49629** values. This function populates the array with values required to
49630** "rollback" the write position of the WAL handle back to the current
49631** point in the event of a savepoint rollback (via WalSavepointUndo()).
49632*/
49633SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
49634  assert( pWal->writeLock );
49635  aWalData[0] = pWal->hdr.mxFrame;
49636  aWalData[1] = pWal->hdr.aFrameCksum[0];
49637  aWalData[2] = pWal->hdr.aFrameCksum[1];
49638  aWalData[3] = pWal->nCkpt;
49639}
49640
49641/*
49642** Move the write position of the WAL back to the point identified by
49643** the values in the aWalData[] array. aWalData must point to an array
49644** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
49645** by a call to WalSavepoint().
49646*/
49647SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
49648  int rc = SQLITE_OK;
49649
49650  assert( pWal->writeLock );
49651  assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
49652
49653  if( aWalData[3]!=pWal->nCkpt ){
49654    /* This savepoint was opened immediately after the write-transaction
49655    ** was started. Right after that, the writer decided to wrap around
49656    ** to the start of the log. Update the savepoint values to match.
49657    */
49658    aWalData[0] = 0;
49659    aWalData[3] = pWal->nCkpt;
49660  }
49661
49662  if( aWalData[0]<pWal->hdr.mxFrame ){
49663    pWal->hdr.mxFrame = aWalData[0];
49664    pWal->hdr.aFrameCksum[0] = aWalData[1];
49665    pWal->hdr.aFrameCksum[1] = aWalData[2];
49666    walCleanupHash(pWal);
49667  }
49668
49669  return rc;
49670}
49671
49672
49673/*
49674** This function is called just before writing a set of frames to the log
49675** file (see sqlite3WalFrames()). It checks to see if, instead of appending
49676** to the current log file, it is possible to overwrite the start of the
49677** existing log file with the new frames (i.e. "reset" the log). If so,
49678** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
49679** unchanged.
49680**
49681** SQLITE_OK is returned if no error is encountered (regardless of whether
49682** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
49683** if an error occurs.
49684*/
49685static int walRestartLog(Wal *pWal){
49686  int rc = SQLITE_OK;
49687  int cnt;
49688
49689  if( pWal->readLock==0 ){
49690    volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
49691    assert( pInfo->nBackfill==pWal->hdr.mxFrame );
49692    if( pInfo->nBackfill>0 ){
49693      u32 salt1;
49694      sqlite3_randomness(4, &salt1);
49695      rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
49696      if( rc==SQLITE_OK ){
49697        /* If all readers are using WAL_READ_LOCK(0) (in other words if no
49698        ** readers are currently using the WAL), then the transactions
49699        ** frames will overwrite the start of the existing log. Update the
49700        ** wal-index header to reflect this.
49701        **
49702        ** In theory it would be Ok to update the cache of the header only
49703        ** at this point. But updating the actual wal-index header is also
49704        ** safe and means there is no special case for sqlite3WalUndo()
49705        ** to handle if this transaction is rolled back.
49706        */
49707        int i;                    /* Loop counter */
49708        u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
49709
49710        pWal->nCkpt++;
49711        pWal->hdr.mxFrame = 0;
49712        sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
49713        aSalt[1] = salt1;
49714        walIndexWriteHdr(pWal);
49715        pInfo->nBackfill = 0;
49716        pInfo->aReadMark[1] = 0;
49717        for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
49718        assert( pInfo->aReadMark[0]==0 );
49719        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
49720      }else if( rc!=SQLITE_BUSY ){
49721        return rc;
49722      }
49723    }
49724    walUnlockShared(pWal, WAL_READ_LOCK(0));
49725    pWal->readLock = -1;
49726    cnt = 0;
49727    do{
49728      int notUsed;
49729      rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
49730    }while( rc==WAL_RETRY );
49731    assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
49732    testcase( (rc&0xff)==SQLITE_IOERR );
49733    testcase( rc==SQLITE_PROTOCOL );
49734    testcase( rc==SQLITE_OK );
49735  }
49736  return rc;
49737}
49738
49739/*
49740** Information about the current state of the WAL file and where
49741** the next fsync should occur - passed from sqlite3WalFrames() into
49742** walWriteToLog().
49743*/
49744typedef struct WalWriter {
49745  Wal *pWal;                   /* The complete WAL information */
49746  sqlite3_file *pFd;           /* The WAL file to which we write */
49747  sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
49748  int syncFlags;               /* Flags for the fsync */
49749  int szPage;                  /* Size of one page */
49750} WalWriter;
49751
49752/*
49753** Write iAmt bytes of content into the WAL file beginning at iOffset.
49754** Do a sync when crossing the p->iSyncPoint boundary.
49755**
49756** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
49757** first write the part before iSyncPoint, then sync, then write the
49758** rest.
49759*/
49760static int walWriteToLog(
49761  WalWriter *p,              /* WAL to write to */
49762  void *pContent,            /* Content to be written */
49763  int iAmt,                  /* Number of bytes to write */
49764  sqlite3_int64 iOffset      /* Start writing at this offset */
49765){
49766  int rc;
49767  if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
49768    int iFirstAmt = (int)(p->iSyncPoint - iOffset);
49769    rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
49770    if( rc ) return rc;
49771    iOffset += iFirstAmt;
49772    iAmt -= iFirstAmt;
49773    pContent = (void*)(iFirstAmt + (char*)pContent);
49774    assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
49775    rc = sqlite3OsSync(p->pFd, p->syncFlags & SQLITE_SYNC_MASK);
49776    if( iAmt==0 || rc ) return rc;
49777  }
49778  rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
49779  return rc;
49780}
49781
49782/*
49783** Write out a single frame of the WAL
49784*/
49785static int walWriteOneFrame(
49786  WalWriter *p,               /* Where to write the frame */
49787  PgHdr *pPage,               /* The page of the frame to be written */
49788  int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
49789  sqlite3_int64 iOffset       /* Byte offset at which to write */
49790){
49791  int rc;                         /* Result code from subfunctions */
49792  void *pData;                    /* Data actually written */
49793  u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
49794#if defined(SQLITE_HAS_CODEC)
49795  if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
49796#else
49797  pData = pPage->pData;
49798#endif
49799  walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
49800  rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
49801  if( rc ) return rc;
49802  /* Write the page data */
49803  rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
49804  return rc;
49805}
49806
49807/*
49808** Write a set of frames to the log. The caller must hold the write-lock
49809** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
49810*/
49811SQLITE_PRIVATE int sqlite3WalFrames(
49812  Wal *pWal,                      /* Wal handle to write to */
49813  int szPage,                     /* Database page-size in bytes */
49814  PgHdr *pList,                   /* List of dirty pages to write */
49815  Pgno nTruncate,                 /* Database size after this commit */
49816  int isCommit,                   /* True if this is a commit */
49817  int sync_flags                  /* Flags to pass to OsSync() (or 0) */
49818){
49819  int rc;                         /* Used to catch return codes */
49820  u32 iFrame;                     /* Next frame address */
49821  PgHdr *p;                       /* Iterator to run through pList with. */
49822  PgHdr *pLast = 0;               /* Last frame in list */
49823  int nExtra = 0;                 /* Number of extra copies of last page */
49824  int szFrame;                    /* The size of a single frame */
49825  i64 iOffset;                    /* Next byte to write in WAL file */
49826  WalWriter w;                    /* The writer */
49827
49828  assert( pList );
49829  assert( pWal->writeLock );
49830
49831  /* If this frame set completes a transaction, then nTruncate>0.  If
49832  ** nTruncate==0 then this frame set does not complete the transaction. */
49833  assert( (isCommit!=0)==(nTruncate!=0) );
49834
49835#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
49836  { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
49837    WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
49838              pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
49839  }
49840#endif
49841
49842  /* See if it is possible to write these frames into the start of the
49843  ** log file, instead of appending to it at pWal->hdr.mxFrame.
49844  */
49845  if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
49846    return rc;
49847  }
49848
49849  /* If this is the first frame written into the log, write the WAL
49850  ** header to the start of the WAL file. See comments at the top of
49851  ** this source file for a description of the WAL header format.
49852  */
49853  iFrame = pWal->hdr.mxFrame;
49854  if( iFrame==0 ){
49855    u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
49856    u32 aCksum[2];                /* Checksum for wal-header */
49857
49858    sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
49859    sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
49860    sqlite3Put4byte(&aWalHdr[8], szPage);
49861    sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
49862    if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
49863    memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
49864    walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
49865    sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
49866    sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
49867
49868    pWal->szPage = szPage;
49869    pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
49870    pWal->hdr.aFrameCksum[0] = aCksum[0];
49871    pWal->hdr.aFrameCksum[1] = aCksum[1];
49872    pWal->truncateOnCommit = 1;
49873
49874    rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
49875    WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
49876    if( rc!=SQLITE_OK ){
49877      return rc;
49878    }
49879
49880    /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
49881    ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
49882    ** an out-of-order write following a WAL restart could result in
49883    ** database corruption.  See the ticket:
49884    **
49885    **     http://localhost:591/sqlite/info/ff5be73dee
49886    */
49887    if( pWal->syncHeader && sync_flags ){
49888      rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
49889      if( rc ) return rc;
49890    }
49891  }
49892  assert( (int)pWal->szPage==szPage );
49893
49894  /* Setup information needed to write frames into the WAL */
49895  w.pWal = pWal;
49896  w.pFd = pWal->pWalFd;
49897  w.iSyncPoint = 0;
49898  w.syncFlags = sync_flags;
49899  w.szPage = szPage;
49900  iOffset = walFrameOffset(iFrame+1, szPage);
49901  szFrame = szPage + WAL_FRAME_HDRSIZE;
49902
49903  /* Write all frames into the log file exactly once */
49904  for(p=pList; p; p=p->pDirty){
49905    int nDbSize;   /* 0 normally.  Positive == commit flag */
49906    iFrame++;
49907    assert( iOffset==walFrameOffset(iFrame, szPage) );
49908    nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
49909    rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
49910    if( rc ) return rc;
49911    pLast = p;
49912    iOffset += szFrame;
49913  }
49914
49915  /* If this is the end of a transaction, then we might need to pad
49916  ** the transaction and/or sync the WAL file.
49917  **
49918  ** Padding and syncing only occur if this set of frames complete a
49919  ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
49920  ** or synchonous==OFF, then no padding or syncing are needed.
49921  **
49922  ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
49923  ** needed and only the sync is done.  If padding is needed, then the
49924  ** final frame is repeated (with its commit mark) until the next sector
49925  ** boundary is crossed.  Only the part of the WAL prior to the last
49926  ** sector boundary is synced; the part of the last frame that extends
49927  ** past the sector boundary is written after the sync.
49928  */
49929  if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
49930    if( pWal->padToSectorBoundary ){
49931      int sectorSize = sqlite3SectorSize(pWal->pWalFd);
49932      w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
49933      while( iOffset<w.iSyncPoint ){
49934        rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
49935        if( rc ) return rc;
49936        iOffset += szFrame;
49937        nExtra++;
49938      }
49939    }else{
49940      rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
49941    }
49942  }
49943
49944  /* If this frame set completes the first transaction in the WAL and
49945  ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
49946  ** journal size limit, if possible.
49947  */
49948  if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
49949    i64 sz = pWal->mxWalSize;
49950    if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
49951      sz = walFrameOffset(iFrame+nExtra+1, szPage);
49952    }
49953    walLimitSize(pWal, sz);
49954    pWal->truncateOnCommit = 0;
49955  }
49956
49957  /* Append data to the wal-index. It is not necessary to lock the
49958  ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
49959  ** guarantees that there are no other writers, and no data that may
49960  ** be in use by existing readers is being overwritten.
49961  */
49962  iFrame = pWal->hdr.mxFrame;
49963  for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
49964    iFrame++;
49965    rc = walIndexAppend(pWal, iFrame, p->pgno);
49966  }
49967  while( rc==SQLITE_OK && nExtra>0 ){
49968    iFrame++;
49969    nExtra--;
49970    rc = walIndexAppend(pWal, iFrame, pLast->pgno);
49971  }
49972
49973  if( rc==SQLITE_OK ){
49974    /* Update the private copy of the header. */
49975    pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
49976    testcase( szPage<=32768 );
49977    testcase( szPage>=65536 );
49978    pWal->hdr.mxFrame = iFrame;
49979    if( isCommit ){
49980      pWal->hdr.iChange++;
49981      pWal->hdr.nPage = nTruncate;
49982    }
49983    /* If this is a commit, update the wal-index header too. */
49984    if( isCommit ){
49985      walIndexWriteHdr(pWal);
49986      pWal->iCallback = iFrame;
49987    }
49988  }
49989
49990  WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
49991  return rc;
49992}
49993
49994/*
49995** This routine is called to implement sqlite3_wal_checkpoint() and
49996** related interfaces.
49997**
49998** Obtain a CHECKPOINT lock and then backfill as much information as
49999** we can from WAL into the database.
50000**
50001** If parameter xBusy is not NULL, it is a pointer to a busy-handler
50002** callback. In this case this function runs a blocking checkpoint.
50003*/
50004SQLITE_PRIVATE int sqlite3WalCheckpoint(
50005  Wal *pWal,                      /* Wal connection */
50006  int eMode,                      /* PASSIVE, FULL or RESTART */
50007  int (*xBusy)(void*),            /* Function to call when busy */
50008  void *pBusyArg,                 /* Context argument for xBusyHandler */
50009  int sync_flags,                 /* Flags to sync db file with (or 0) */
50010  int nBuf,                       /* Size of temporary buffer */
50011  u8 *zBuf,                       /* Temporary buffer to use */
50012  int *pnLog,                     /* OUT: Number of frames in WAL */
50013  int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
50014){
50015  int rc;                         /* Return code */
50016  int isChanged = 0;              /* True if a new wal-index header is loaded */
50017  int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
50018
50019  assert( pWal->ckptLock==0 );
50020  assert( pWal->writeLock==0 );
50021
50022  if( pWal->readOnly ) return SQLITE_READONLY;
50023  WALTRACE(("WAL%p: checkpoint begins\n", pWal));
50024  rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
50025  if( rc ){
50026    /* Usually this is SQLITE_BUSY meaning that another thread or process
50027    ** is already running a checkpoint, or maybe a recovery.  But it might
50028    ** also be SQLITE_IOERR. */
50029    return rc;
50030  }
50031  pWal->ckptLock = 1;
50032
50033  /* If this is a blocking-checkpoint, then obtain the write-lock as well
50034  ** to prevent any writers from running while the checkpoint is underway.
50035  ** This has to be done before the call to walIndexReadHdr() below.
50036  **
50037  ** If the writer lock cannot be obtained, then a passive checkpoint is
50038  ** run instead. Since the checkpointer is not holding the writer lock,
50039  ** there is no point in blocking waiting for any readers. Assuming no
50040  ** other error occurs, this function will return SQLITE_BUSY to the caller.
50041  */
50042  if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
50043    rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
50044    if( rc==SQLITE_OK ){
50045      pWal->writeLock = 1;
50046    }else if( rc==SQLITE_BUSY ){
50047      eMode2 = SQLITE_CHECKPOINT_PASSIVE;
50048      rc = SQLITE_OK;
50049    }
50050  }
50051
50052  /* Read the wal-index header. */
50053  if( rc==SQLITE_OK ){
50054    rc = walIndexReadHdr(pWal, &isChanged);
50055    if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
50056      sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
50057    }
50058  }
50059
50060  /* Copy data from the log to the database file. */
50061  if( rc==SQLITE_OK ){
50062    if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
50063      rc = SQLITE_CORRUPT_BKPT;
50064    }else{
50065      rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
50066    }
50067
50068    /* If no error occurred, set the output variables. */
50069    if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
50070      if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
50071      if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
50072    }
50073  }
50074
50075  if( isChanged ){
50076    /* If a new wal-index header was loaded before the checkpoint was
50077    ** performed, then the pager-cache associated with pWal is now
50078    ** out of date. So zero the cached wal-index header to ensure that
50079    ** next time the pager opens a snapshot on this database it knows that
50080    ** the cache needs to be reset.
50081    */
50082    memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
50083  }
50084
50085  /* Release the locks. */
50086  sqlite3WalEndWriteTransaction(pWal);
50087  walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
50088  pWal->ckptLock = 0;
50089  WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
50090  return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
50091}
50092
50093/* Return the value to pass to a sqlite3_wal_hook callback, the
50094** number of frames in the WAL at the point of the last commit since
50095** sqlite3WalCallback() was called.  If no commits have occurred since
50096** the last call, then return 0.
50097*/
50098SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
50099  u32 ret = 0;
50100  if( pWal ){
50101    ret = pWal->iCallback;
50102    pWal->iCallback = 0;
50103  }
50104  return (int)ret;
50105}
50106
50107/*
50108** This function is called to change the WAL subsystem into or out
50109** of locking_mode=EXCLUSIVE.
50110**
50111** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
50112** into locking_mode=NORMAL.  This means that we must acquire a lock
50113** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
50114** or if the acquisition of the lock fails, then return 0.  If the
50115** transition out of exclusive-mode is successful, return 1.  This
50116** operation must occur while the pager is still holding the exclusive
50117** lock on the main database file.
50118**
50119** If op is one, then change from locking_mode=NORMAL into
50120** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
50121** be released.  Return 1 if the transition is made and 0 if the
50122** WAL is already in exclusive-locking mode - meaning that this
50123** routine is a no-op.  The pager must already hold the exclusive lock
50124** on the main database file before invoking this operation.
50125**
50126** If op is negative, then do a dry-run of the op==1 case but do
50127** not actually change anything. The pager uses this to see if it
50128** should acquire the database exclusive lock prior to invoking
50129** the op==1 case.
50130*/
50131SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
50132  int rc;
50133  assert( pWal->writeLock==0 );
50134  assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
50135
50136  /* pWal->readLock is usually set, but might be -1 if there was a
50137  ** prior error while attempting to acquire are read-lock. This cannot
50138  ** happen if the connection is actually in exclusive mode (as no xShmLock
50139  ** locks are taken in this case). Nor should the pager attempt to
50140  ** upgrade to exclusive-mode following such an error.
50141  */
50142  assert( pWal->readLock>=0 || pWal->lockError );
50143  assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
50144
50145  if( op==0 ){
50146    if( pWal->exclusiveMode ){
50147      pWal->exclusiveMode = 0;
50148      if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
50149        pWal->exclusiveMode = 1;
50150      }
50151      rc = pWal->exclusiveMode==0;
50152    }else{
50153      /* Already in locking_mode=NORMAL */
50154      rc = 0;
50155    }
50156  }else if( op>0 ){
50157    assert( pWal->exclusiveMode==0 );
50158    assert( pWal->readLock>=0 );
50159    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
50160    pWal->exclusiveMode = 1;
50161    rc = 1;
50162  }else{
50163    rc = pWal->exclusiveMode==0;
50164  }
50165  return rc;
50166}
50167
50168/*
50169** Return true if the argument is non-NULL and the WAL module is using
50170** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
50171** WAL module is using shared-memory, return false.
50172*/
50173SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
50174  return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
50175}
50176
50177#ifdef SQLITE_ENABLE_ZIPVFS
50178/*
50179** If the argument is not NULL, it points to a Wal object that holds a
50180** read-lock. This function returns the database page-size if it is known,
50181** or zero if it is not (or if pWal is NULL).
50182*/
50183SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
50184  assert( pWal==0 || pWal->readLock>=0 );
50185  return (pWal ? pWal->szPage : 0);
50186}
50187#endif
50188
50189#endif /* #ifndef SQLITE_OMIT_WAL */
50190
50191/************** End of wal.c *************************************************/
50192/************** Begin file btmutex.c *****************************************/
50193/*
50194** 2007 August 27
50195**
50196** The author disclaims copyright to this source code.  In place of
50197** a legal notice, here is a blessing:
50198**
50199**    May you do good and not evil.
50200**    May you find forgiveness for yourself and forgive others.
50201**    May you share freely, never taking more than you give.
50202**
50203*************************************************************************
50204**
50205** This file contains code used to implement mutexes on Btree objects.
50206** This code really belongs in btree.c.  But btree.c is getting too
50207** big and we want to break it down some.  This packaged seemed like
50208** a good breakout.
50209*/
50210/************** Include btreeInt.h in the middle of btmutex.c ****************/
50211/************** Begin file btreeInt.h ****************************************/
50212/*
50213** 2004 April 6
50214**
50215** The author disclaims copyright to this source code.  In place of
50216** a legal notice, here is a blessing:
50217**
50218**    May you do good and not evil.
50219**    May you find forgiveness for yourself and forgive others.
50220**    May you share freely, never taking more than you give.
50221**
50222*************************************************************************
50223** This file implements a external (disk-based) database using BTrees.
50224** For a detailed discussion of BTrees, refer to
50225**
50226**     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
50227**     "Sorting And Searching", pages 473-480. Addison-Wesley
50228**     Publishing Company, Reading, Massachusetts.
50229**
50230** The basic idea is that each page of the file contains N database
50231** entries and N+1 pointers to subpages.
50232**
50233**   ----------------------------------------------------------------
50234**   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
50235**   ----------------------------------------------------------------
50236**
50237** All of the keys on the page that Ptr(0) points to have values less
50238** than Key(0).  All of the keys on page Ptr(1) and its subpages have
50239** values greater than Key(0) and less than Key(1).  All of the keys
50240** on Ptr(N) and its subpages have values greater than Key(N-1).  And
50241** so forth.
50242**
50243** Finding a particular key requires reading O(log(M)) pages from the
50244** disk where M is the number of entries in the tree.
50245**
50246** In this implementation, a single file can hold one or more separate
50247** BTrees.  Each BTree is identified by the index of its root page.  The
50248** key and data for any entry are combined to form the "payload".  A
50249** fixed amount of payload can be carried directly on the database
50250** page.  If the payload is larger than the preset amount then surplus
50251** bytes are stored on overflow pages.  The payload for an entry
50252** and the preceding pointer are combined to form a "Cell".  Each
50253** page has a small header which contains the Ptr(N) pointer and other
50254** information such as the size of key and data.
50255**
50256** FORMAT DETAILS
50257**
50258** The file is divided into pages.  The first page is called page 1,
50259** the second is page 2, and so forth.  A page number of zero indicates
50260** "no such page".  The page size can be any power of 2 between 512 and 65536.
50261** Each page can be either a btree page, a freelist page, an overflow
50262** page, or a pointer-map page.
50263**
50264** The first page is always a btree page.  The first 100 bytes of the first
50265** page contain a special header (the "file header") that describes the file.
50266** The format of the file header is as follows:
50267**
50268**   OFFSET   SIZE    DESCRIPTION
50269**      0      16     Header string: "SQLite format 3\000"
50270**     16       2     Page size in bytes.  (1 means 65536)
50271**     18       1     File format write version
50272**     19       1     File format read version
50273**     20       1     Bytes of unused space at the end of each page
50274**     21       1     Max embedded payload fraction (must be 64)
50275**     22       1     Min embedded payload fraction (must be 32)
50276**     23       1     Min leaf payload fraction (must be 32)
50277**     24       4     File change counter
50278**     28       4     Reserved for future use
50279**     32       4     First freelist page
50280**     36       4     Number of freelist pages in the file
50281**     40      60     15 4-byte meta values passed to higher layers
50282**
50283**     40       4     Schema cookie
50284**     44       4     File format of schema layer
50285**     48       4     Size of page cache
50286**     52       4     Largest root-page (auto/incr_vacuum)
50287**     56       4     1=UTF-8 2=UTF16le 3=UTF16be
50288**     60       4     User version
50289**     64       4     Incremental vacuum mode
50290**     68       4     Application-ID
50291**     72      20     unused
50292**     92       4     The version-valid-for number
50293**     96       4     SQLITE_VERSION_NUMBER
50294**
50295** All of the integer values are big-endian (most significant byte first).
50296**
50297** The file change counter is incremented when the database is changed
50298** This counter allows other processes to know when the file has changed
50299** and thus when they need to flush their cache.
50300**
50301** The max embedded payload fraction is the amount of the total usable
50302** space in a page that can be consumed by a single cell for standard
50303** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
50304** is to limit the maximum cell size so that at least 4 cells will fit
50305** on one page.  Thus the default max embedded payload fraction is 64.
50306**
50307** If the payload for a cell is larger than the max payload, then extra
50308** payload is spilled to overflow pages.  Once an overflow page is allocated,
50309** as many bytes as possible are moved into the overflow pages without letting
50310** the cell size drop below the min embedded payload fraction.
50311**
50312** The min leaf payload fraction is like the min embedded payload fraction
50313** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
50314** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
50315** not specified in the header.
50316**
50317** Each btree pages is divided into three sections:  The header, the
50318** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
50319** file header that occurs before the page header.
50320**
50321**      |----------------|
50322**      | file header    |   100 bytes.  Page 1 only.
50323**      |----------------|
50324**      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
50325**      |----------------|
50326**      | cell pointer   |   |  2 bytes per cell.  Sorted order.
50327**      | array          |   |  Grows downward
50328**      |                |   v
50329**      |----------------|
50330**      | unallocated    |
50331**      | space          |
50332**      |----------------|   ^  Grows upwards
50333**      | cell content   |   |  Arbitrary order interspersed with freeblocks.
50334**      | area           |   |  and free space fragments.
50335**      |----------------|
50336**
50337** The page headers looks like this:
50338**
50339**   OFFSET   SIZE     DESCRIPTION
50340**      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
50341**      1       2      byte offset to the first freeblock
50342**      3       2      number of cells on this page
50343**      5       2      first byte of the cell content area
50344**      7       1      number of fragmented free bytes
50345**      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
50346**
50347** The flags define the format of this btree page.  The leaf flag means that
50348** this page has no children.  The zerodata flag means that this page carries
50349** only keys and no data.  The intkey flag means that the key is a integer
50350** which is stored in the key size entry of the cell header rather than in
50351** the payload area.
50352**
50353** The cell pointer array begins on the first byte after the page header.
50354** The cell pointer array contains zero or more 2-byte numbers which are
50355** offsets from the beginning of the page to the cell content in the cell
50356** content area.  The cell pointers occur in sorted order.  The system strives
50357** to keep free space after the last cell pointer so that new cells can
50358** be easily added without having to defragment the page.
50359**
50360** Cell content is stored at the very end of the page and grows toward the
50361** beginning of the page.
50362**
50363** Unused space within the cell content area is collected into a linked list of
50364** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
50365** to the first freeblock is given in the header.  Freeblocks occur in
50366** increasing order.  Because a freeblock must be at least 4 bytes in size,
50367** any group of 3 or fewer unused bytes in the cell content area cannot
50368** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
50369** a fragment.  The total number of bytes in all fragments is recorded.
50370** in the page header at offset 7.
50371**
50372**    SIZE    DESCRIPTION
50373**      2     Byte offset of the next freeblock
50374**      2     Bytes in this freeblock
50375**
50376** Cells are of variable length.  Cells are stored in the cell content area at
50377** the end of the page.  Pointers to the cells are in the cell pointer array
50378** that immediately follows the page header.  Cells is not necessarily
50379** contiguous or in order, but cell pointers are contiguous and in order.
50380**
50381** Cell content makes use of variable length integers.  A variable
50382** length integer is 1 to 9 bytes where the lower 7 bits of each
50383** byte are used.  The integer consists of all bytes that have bit 8 set and
50384** the first byte with bit 8 clear.  The most significant byte of the integer
50385** appears first.  A variable-length integer may not be more than 9 bytes long.
50386** As a special case, all 8 bytes of the 9th byte are used as data.  This
50387** allows a 64-bit integer to be encoded in 9 bytes.
50388**
50389**    0x00                      becomes  0x00000000
50390**    0x7f                      becomes  0x0000007f
50391**    0x81 0x00                 becomes  0x00000080
50392**    0x82 0x00                 becomes  0x00000100
50393**    0x80 0x7f                 becomes  0x0000007f
50394**    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
50395**    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
50396**
50397** Variable length integers are used for rowids and to hold the number of
50398** bytes of key and data in a btree cell.
50399**
50400** The content of a cell looks like this:
50401**
50402**    SIZE    DESCRIPTION
50403**      4     Page number of the left child. Omitted if leaf flag is set.
50404**     var    Number of bytes of data. Omitted if the zerodata flag is set.
50405**     var    Number of bytes of key. Or the key itself if intkey flag is set.
50406**      *     Payload
50407**      4     First page of the overflow chain.  Omitted if no overflow
50408**
50409** Overflow pages form a linked list.  Each page except the last is completely
50410** filled with data (pagesize - 4 bytes).  The last page can have as little
50411** as 1 byte of data.
50412**
50413**    SIZE    DESCRIPTION
50414**      4     Page number of next overflow page
50415**      *     Data
50416**
50417** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
50418** file header points to the first in a linked list of trunk page.  Each trunk
50419** page points to multiple leaf pages.  The content of a leaf page is
50420** unspecified.  A trunk page looks like this:
50421**
50422**    SIZE    DESCRIPTION
50423**      4     Page number of next trunk page
50424**      4     Number of leaf pointers on this page
50425**      *     zero or more pages numbers of leaves
50426*/
50427
50428
50429/* The following value is the maximum cell size assuming a maximum page
50430** size give above.
50431*/
50432#define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
50433
50434/* The maximum number of cells on a single page of the database.  This
50435** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
50436** plus 2 bytes for the index to the cell in the page header).  Such
50437** small cells will be rare, but they are possible.
50438*/
50439#define MX_CELL(pBt) ((pBt->pageSize-8)/6)
50440
50441/* Forward declarations */
50442typedef struct MemPage MemPage;
50443typedef struct BtLock BtLock;
50444
50445/*
50446** This is a magic string that appears at the beginning of every
50447** SQLite database in order to identify the file as a real database.
50448**
50449** You can change this value at compile-time by specifying a
50450** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
50451** header must be exactly 16 bytes including the zero-terminator so
50452** the string itself should be 15 characters long.  If you change
50453** the header, then your custom library will not be able to read
50454** databases generated by the standard tools and the standard tools
50455** will not be able to read databases created by your custom library.
50456*/
50457#ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
50458#  define SQLITE_FILE_HEADER "SQLite format 3"
50459#endif
50460
50461/*
50462** Page type flags.  An ORed combination of these flags appear as the
50463** first byte of on-disk image of every BTree page.
50464*/
50465#define PTF_INTKEY    0x01
50466#define PTF_ZERODATA  0x02
50467#define PTF_LEAFDATA  0x04
50468#define PTF_LEAF      0x08
50469
50470/*
50471** As each page of the file is loaded into memory, an instance of the following
50472** structure is appended and initialized to zero.  This structure stores
50473** information about the page that is decoded from the raw file page.
50474**
50475** The pParent field points back to the parent page.  This allows us to
50476** walk up the BTree from any leaf to the root.  Care must be taken to
50477** unref() the parent page pointer when this page is no longer referenced.
50478** The pageDestructor() routine handles that chore.
50479**
50480** Access to all fields of this structure is controlled by the mutex
50481** stored in MemPage.pBt->mutex.
50482*/
50483struct MemPage {
50484  u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
50485  u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
50486  u8 intKey;           /* True if intkey flag is set */
50487  u8 leaf;             /* True if leaf flag is set */
50488  u8 hasData;          /* True if this page stores data */
50489  u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
50490  u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
50491  u8 max1bytePayload;  /* min(maxLocal,127) */
50492  u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
50493  u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
50494  u16 cellOffset;      /* Index in aData of first cell pointer */
50495  u16 nFree;           /* Number of free bytes on the page */
50496  u16 nCell;           /* Number of cells on this page, local and ovfl */
50497  u16 maskPage;        /* Mask for page offset */
50498  u16 aiOvfl[5];       /* Insert the i-th overflow cell before the aiOvfl-th
50499                       ** non-overflow cell */
50500  u8 *apOvfl[5];       /* Pointers to the body of overflow cells */
50501  BtShared *pBt;       /* Pointer to BtShared that this page is part of */
50502  u8 *aData;           /* Pointer to disk image of the page data */
50503  u8 *aDataEnd;        /* One byte past the end of usable data */
50504  u8 *aCellIdx;        /* The cell index area */
50505  DbPage *pDbPage;     /* Pager page handle */
50506  Pgno pgno;           /* Page number for this page */
50507};
50508
50509/*
50510** The in-memory image of a disk page has the auxiliary information appended
50511** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
50512** that extra information.
50513*/
50514#define EXTRA_SIZE sizeof(MemPage)
50515
50516/*
50517** A linked list of the following structures is stored at BtShared.pLock.
50518** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
50519** is opened on the table with root page BtShared.iTable. Locks are removed
50520** from this list when a transaction is committed or rolled back, or when
50521** a btree handle is closed.
50522*/
50523struct BtLock {
50524  Btree *pBtree;        /* Btree handle holding this lock */
50525  Pgno iTable;          /* Root page of table */
50526  u8 eLock;             /* READ_LOCK or WRITE_LOCK */
50527  BtLock *pNext;        /* Next in BtShared.pLock list */
50528};
50529
50530/* Candidate values for BtLock.eLock */
50531#define READ_LOCK     1
50532#define WRITE_LOCK    2
50533
50534/* A Btree handle
50535**
50536** A database connection contains a pointer to an instance of
50537** this object for every database file that it has open.  This structure
50538** is opaque to the database connection.  The database connection cannot
50539** see the internals of this structure and only deals with pointers to
50540** this structure.
50541**
50542** For some database files, the same underlying database cache might be
50543** shared between multiple connections.  In that case, each connection
50544** has it own instance of this object.  But each instance of this object
50545** points to the same BtShared object.  The database cache and the
50546** schema associated with the database file are all contained within
50547** the BtShared object.
50548**
50549** All fields in this structure are accessed under sqlite3.mutex.
50550** The pBt pointer itself may not be changed while there exists cursors
50551** in the referenced BtShared that point back to this Btree since those
50552** cursors have to go through this Btree to find their BtShared and
50553** they often do so without holding sqlite3.mutex.
50554*/
50555struct Btree {
50556  sqlite3 *db;       /* The database connection holding this btree */
50557  BtShared *pBt;     /* Sharable content of this btree */
50558  u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
50559  u8 sharable;       /* True if we can share pBt with another db */
50560  u8 locked;         /* True if db currently has pBt locked */
50561  int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
50562  int nBackup;       /* Number of backup operations reading this btree */
50563  Btree *pNext;      /* List of other sharable Btrees from the same db */
50564  Btree *pPrev;      /* Back pointer of the same list */
50565#ifndef SQLITE_OMIT_SHARED_CACHE
50566  BtLock lock;       /* Object used to lock page 1 */
50567#endif
50568};
50569
50570/*
50571** Btree.inTrans may take one of the following values.
50572**
50573** If the shared-data extension is enabled, there may be multiple users
50574** of the Btree structure. At most one of these may open a write transaction,
50575** but any number may have active read transactions.
50576*/
50577#define TRANS_NONE  0
50578#define TRANS_READ  1
50579#define TRANS_WRITE 2
50580
50581/*
50582** An instance of this object represents a single database file.
50583**
50584** A single database file can be in use at the same time by two
50585** or more database connections.  When two or more connections are
50586** sharing the same database file, each connection has it own
50587** private Btree object for the file and each of those Btrees points
50588** to this one BtShared object.  BtShared.nRef is the number of
50589** connections currently sharing this database file.
50590**
50591** Fields in this structure are accessed under the BtShared.mutex
50592** mutex, except for nRef and pNext which are accessed under the
50593** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
50594** may not be modified once it is initially set as long as nRef>0.
50595** The pSchema field may be set once under BtShared.mutex and
50596** thereafter is unchanged as long as nRef>0.
50597**
50598** isPending:
50599**
50600**   If a BtShared client fails to obtain a write-lock on a database
50601**   table (because there exists one or more read-locks on the table),
50602**   the shared-cache enters 'pending-lock' state and isPending is
50603**   set to true.
50604**
50605**   The shared-cache leaves the 'pending lock' state when either of
50606**   the following occur:
50607**
50608**     1) The current writer (BtShared.pWriter) concludes its transaction, OR
50609**     2) The number of locks held by other connections drops to zero.
50610**
50611**   while in the 'pending-lock' state, no connection may start a new
50612**   transaction.
50613**
50614**   This feature is included to help prevent writer-starvation.
50615*/
50616struct BtShared {
50617  Pager *pPager;        /* The page cache */
50618  sqlite3 *db;          /* Database connection currently using this Btree */
50619  BtCursor *pCursor;    /* A list of all open cursors */
50620  MemPage *pPage1;      /* First page of the database */
50621  u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
50622#ifndef SQLITE_OMIT_AUTOVACUUM
50623  u8 autoVacuum;        /* True if auto-vacuum is enabled */
50624  u8 incrVacuum;        /* True if incr-vacuum is enabled */
50625  u8 bDoTruncate;       /* True to truncate db on commit */
50626#endif
50627  u8 inTransaction;     /* Transaction state */
50628  u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */
50629  u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */
50630  u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
50631  u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
50632  u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
50633  u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
50634  u32 pageSize;         /* Total number of bytes on a page */
50635  u32 usableSize;       /* Number of usable bytes on each page */
50636  int nTransaction;     /* Number of open transactions (read + write) */
50637  u32 nPage;            /* Number of pages in the database */
50638  void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
50639  void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
50640  sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
50641  Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
50642#ifndef SQLITE_OMIT_SHARED_CACHE
50643  int nRef;             /* Number of references to this structure */
50644  BtShared *pNext;      /* Next on a list of sharable BtShared structs */
50645  BtLock *pLock;        /* List of locks held on this shared-btree struct */
50646  Btree *pWriter;       /* Btree with currently open write transaction */
50647#endif
50648  u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
50649};
50650
50651/*
50652** Allowed values for BtShared.btsFlags
50653*/
50654#define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */
50655#define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */
50656#define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */
50657#define BTS_INITIALLY_EMPTY  0x0008   /* Database was empty at trans start */
50658#define BTS_NO_WAL           0x0010   /* Do not open write-ahead-log files */
50659#define BTS_EXCLUSIVE        0x0020   /* pWriter has an exclusive lock */
50660#define BTS_PENDING          0x0040   /* Waiting for read-locks to clear */
50661
50662/*
50663** An instance of the following structure is used to hold information
50664** about a cell.  The parseCellPtr() function fills in this structure
50665** based on information extract from the raw disk page.
50666*/
50667typedef struct CellInfo CellInfo;
50668struct CellInfo {
50669  i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
50670  u8 *pCell;     /* Pointer to the start of cell content */
50671  u32 nData;     /* Number of bytes of data */
50672  u32 nPayload;  /* Total amount of payload */
50673  u16 nHeader;   /* Size of the cell content header in bytes */
50674  u16 nLocal;    /* Amount of payload held locally */
50675  u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
50676  u16 nSize;     /* Size of the cell content on the main b-tree page */
50677};
50678
50679/*
50680** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
50681** this will be declared corrupt. This value is calculated based on a
50682** maximum database size of 2^31 pages a minimum fanout of 2 for a
50683** root-node and 3 for all other internal nodes.
50684**
50685** If a tree that appears to be taller than this is encountered, it is
50686** assumed that the database is corrupt.
50687*/
50688#define BTCURSOR_MAX_DEPTH 20
50689
50690/*
50691** A cursor is a pointer to a particular entry within a particular
50692** b-tree within a database file.
50693**
50694** The entry is identified by its MemPage and the index in
50695** MemPage.aCell[] of the entry.
50696**
50697** A single database file can be shared by two more database connections,
50698** but cursors cannot be shared.  Each cursor is associated with a
50699** particular database connection identified BtCursor.pBtree.db.
50700**
50701** Fields in this structure are accessed under the BtShared.mutex
50702** found at self->pBt->mutex.
50703*/
50704struct BtCursor {
50705  Btree *pBtree;            /* The Btree to which this cursor belongs */
50706  BtShared *pBt;            /* The BtShared this cursor points to */
50707  BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
50708  struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
50709  Pgno *aOverflow;          /* Cache of overflow page locations */
50710  CellInfo info;            /* A parse of the cell we are pointing at */
50711  i64 nKey;                 /* Size of pKey, or last integer key */
50712  void *pKey;               /* Saved key that was cursor last known position */
50713  Pgno pgnoRoot;            /* The root page of this tree */
50714  int nOvflAlloc;           /* Allocated size of aOverflow[] array */
50715  int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
50716  u8 curFlags;              /* zero or more BTCF_* flags defined below */
50717  u8 eState;                /* One of the CURSOR_XXX constants (see below) */
50718  u8 hints;                             /* As configured by CursorSetHints() */
50719  i16 iPage;                            /* Index of current page in apPage */
50720  u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
50721  MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
50722};
50723
50724/*
50725** Legal values for BtCursor.curFlags
50726*/
50727#define BTCF_WriteFlag    0x01   /* True if a write cursor */
50728#define BTCF_ValidNKey    0x02   /* True if info.nKey is valid */
50729#define BTCF_ValidOvfl    0x04   /* True if aOverflow is valid */
50730#define BTCF_AtLast       0x08   /* Cursor is pointing ot the last entry */
50731#define BTCF_Incrblob     0x10   /* True if an incremental I/O handle */
50732
50733/*
50734** Potential values for BtCursor.eState.
50735**
50736** CURSOR_INVALID:
50737**   Cursor does not point to a valid entry. This can happen (for example)
50738**   because the table is empty or because BtreeCursorFirst() has not been
50739**   called.
50740**
50741** CURSOR_VALID:
50742**   Cursor points to a valid entry. getPayload() etc. may be called.
50743**
50744** CURSOR_SKIPNEXT:
50745**   Cursor is valid except that the Cursor.skipNext field is non-zero
50746**   indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
50747**   operation should be a no-op.
50748**
50749** CURSOR_REQUIRESEEK:
50750**   The table that this cursor was opened on still exists, but has been
50751**   modified since the cursor was last used. The cursor position is saved
50752**   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
50753**   this state, restoreCursorPosition() can be called to attempt to
50754**   seek the cursor to the saved position.
50755**
50756** CURSOR_FAULT:
50757**   A unrecoverable error (an I/O error or a malloc failure) has occurred
50758**   on a different connection that shares the BtShared cache with this
50759**   cursor.  The error has left the cache in an inconsistent state.
50760**   Do nothing else with this cursor.  Any attempt to use the cursor
50761**   should return the error code stored in BtCursor.skip
50762*/
50763#define CURSOR_INVALID           0
50764#define CURSOR_VALID             1
50765#define CURSOR_SKIPNEXT          2
50766#define CURSOR_REQUIRESEEK       3
50767#define CURSOR_FAULT             4
50768
50769/*
50770** The database page the PENDING_BYTE occupies. This page is never used.
50771*/
50772# define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
50773
50774/*
50775** These macros define the location of the pointer-map entry for a
50776** database page. The first argument to each is the number of usable
50777** bytes on each page of the database (often 1024). The second is the
50778** page number to look up in the pointer map.
50779**
50780** PTRMAP_PAGENO returns the database page number of the pointer-map
50781** page that stores the required pointer. PTRMAP_PTROFFSET returns
50782** the offset of the requested map entry.
50783**
50784** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
50785** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
50786** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
50787** this test.
50788*/
50789#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
50790#define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
50791#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
50792
50793/*
50794** The pointer map is a lookup table that identifies the parent page for
50795** each child page in the database file.  The parent page is the page that
50796** contains a pointer to the child.  Every page in the database contains
50797** 0 or 1 parent pages.  (In this context 'database page' refers
50798** to any page that is not part of the pointer map itself.)  Each pointer map
50799** entry consists of a single byte 'type' and a 4 byte parent page number.
50800** The PTRMAP_XXX identifiers below are the valid types.
50801**
50802** The purpose of the pointer map is to facility moving pages from one
50803** position in the file to another as part of autovacuum.  When a page
50804** is moved, the pointer in its parent must be updated to point to the
50805** new location.  The pointer map is used to locate the parent page quickly.
50806**
50807** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
50808**                  used in this case.
50809**
50810** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
50811**                  is not used in this case.
50812**
50813** PTRMAP_OVERFLOW1: The database page is the first page in a list of
50814**                   overflow pages. The page number identifies the page that
50815**                   contains the cell with a pointer to this overflow page.
50816**
50817** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
50818**                   overflow pages. The page-number identifies the previous
50819**                   page in the overflow page list.
50820**
50821** PTRMAP_BTREE: The database page is a non-root btree page. The page number
50822**               identifies the parent page in the btree.
50823*/
50824#define PTRMAP_ROOTPAGE 1
50825#define PTRMAP_FREEPAGE 2
50826#define PTRMAP_OVERFLOW1 3
50827#define PTRMAP_OVERFLOW2 4
50828#define PTRMAP_BTREE 5
50829
50830/* A bunch of assert() statements to check the transaction state variables
50831** of handle p (type Btree*) are internally consistent.
50832*/
50833#define btreeIntegrity(p) \
50834  assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
50835  assert( p->pBt->inTransaction>=p->inTrans );
50836
50837
50838/*
50839** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
50840** if the database supports auto-vacuum or not. Because it is used
50841** within an expression that is an argument to another macro
50842** (sqliteMallocRaw), it is not possible to use conditional compilation.
50843** So, this macro is defined instead.
50844*/
50845#ifndef SQLITE_OMIT_AUTOVACUUM
50846#define ISAUTOVACUUM (pBt->autoVacuum)
50847#else
50848#define ISAUTOVACUUM 0
50849#endif
50850
50851
50852/*
50853** This structure is passed around through all the sanity checking routines
50854** in order to keep track of some global state information.
50855**
50856** The aRef[] array is allocated so that there is 1 bit for each page in
50857** the database. As the integrity-check proceeds, for each page used in
50858** the database the corresponding bit is set. This allows integrity-check to
50859** detect pages that are used twice and orphaned pages (both of which
50860** indicate corruption).
50861*/
50862typedef struct IntegrityCk IntegrityCk;
50863struct IntegrityCk {
50864  BtShared *pBt;    /* The tree being checked out */
50865  Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
50866  u8 *aPgRef;       /* 1 bit per page in the db (see above) */
50867  Pgno nPage;       /* Number of pages in the database */
50868  int mxErr;        /* Stop accumulating errors when this reaches zero */
50869  int nErr;         /* Number of messages written to zErrMsg so far */
50870  int mallocFailed; /* A memory allocation error has occurred */
50871  StrAccum errMsg;  /* Accumulate the error message text here */
50872};
50873
50874/*
50875** Routines to read or write a two- and four-byte big-endian integer values.
50876*/
50877#define get2byte(x)   ((x)[0]<<8 | (x)[1])
50878#define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
50879#define get4byte sqlite3Get4byte
50880#define put4byte sqlite3Put4byte
50881
50882/************** End of btreeInt.h ********************************************/
50883/************** Continuing where we left off in btmutex.c ********************/
50884#ifndef SQLITE_OMIT_SHARED_CACHE
50885#if SQLITE_THREADSAFE
50886
50887/*
50888** Obtain the BtShared mutex associated with B-Tree handle p. Also,
50889** set BtShared.db to the database handle associated with p and the
50890** p->locked boolean to true.
50891*/
50892static void lockBtreeMutex(Btree *p){
50893  assert( p->locked==0 );
50894  assert( sqlite3_mutex_notheld(p->pBt->mutex) );
50895  assert( sqlite3_mutex_held(p->db->mutex) );
50896
50897  sqlite3_mutex_enter(p->pBt->mutex);
50898  p->pBt->db = p->db;
50899  p->locked = 1;
50900}
50901
50902/*
50903** Release the BtShared mutex associated with B-Tree handle p and
50904** clear the p->locked boolean.
50905*/
50906static void unlockBtreeMutex(Btree *p){
50907  BtShared *pBt = p->pBt;
50908  assert( p->locked==1 );
50909  assert( sqlite3_mutex_held(pBt->mutex) );
50910  assert( sqlite3_mutex_held(p->db->mutex) );
50911  assert( p->db==pBt->db );
50912
50913  sqlite3_mutex_leave(pBt->mutex);
50914  p->locked = 0;
50915}
50916
50917/*
50918** Enter a mutex on the given BTree object.
50919**
50920** If the object is not sharable, then no mutex is ever required
50921** and this routine is a no-op.  The underlying mutex is non-recursive.
50922** But we keep a reference count in Btree.wantToLock so the behavior
50923** of this interface is recursive.
50924**
50925** To avoid deadlocks, multiple Btrees are locked in the same order
50926** by all database connections.  The p->pNext is a list of other
50927** Btrees belonging to the same database connection as the p Btree
50928** which need to be locked after p.  If we cannot get a lock on
50929** p, then first unlock all of the others on p->pNext, then wait
50930** for the lock to become available on p, then relock all of the
50931** subsequent Btrees that desire a lock.
50932*/
50933SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
50934  Btree *pLater;
50935
50936  /* Some basic sanity checking on the Btree.  The list of Btrees
50937  ** connected by pNext and pPrev should be in sorted order by
50938  ** Btree.pBt value. All elements of the list should belong to
50939  ** the same connection. Only shared Btrees are on the list. */
50940  assert( p->pNext==0 || p->pNext->pBt>p->pBt );
50941  assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
50942  assert( p->pNext==0 || p->pNext->db==p->db );
50943  assert( p->pPrev==0 || p->pPrev->db==p->db );
50944  assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
50945
50946  /* Check for locking consistency */
50947  assert( !p->locked || p->wantToLock>0 );
50948  assert( p->sharable || p->wantToLock==0 );
50949
50950  /* We should already hold a lock on the database connection */
50951  assert( sqlite3_mutex_held(p->db->mutex) );
50952
50953  /* Unless the database is sharable and unlocked, then BtShared.db
50954  ** should already be set correctly. */
50955  assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
50956
50957  if( !p->sharable ) return;
50958  p->wantToLock++;
50959  if( p->locked ) return;
50960
50961  /* In most cases, we should be able to acquire the lock we
50962  ** want without having to go throught the ascending lock
50963  ** procedure that follows.  Just be sure not to block.
50964  */
50965  if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
50966    p->pBt->db = p->db;
50967    p->locked = 1;
50968    return;
50969  }
50970
50971  /* To avoid deadlock, first release all locks with a larger
50972  ** BtShared address.  Then acquire our lock.  Then reacquire
50973  ** the other BtShared locks that we used to hold in ascending
50974  ** order.
50975  */
50976  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
50977    assert( pLater->sharable );
50978    assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
50979    assert( !pLater->locked || pLater->wantToLock>0 );
50980    if( pLater->locked ){
50981      unlockBtreeMutex(pLater);
50982    }
50983  }
50984  lockBtreeMutex(p);
50985  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
50986    if( pLater->wantToLock ){
50987      lockBtreeMutex(pLater);
50988    }
50989  }
50990}
50991
50992/*
50993** Exit the recursive mutex on a Btree.
50994*/
50995SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
50996  if( p->sharable ){
50997    assert( p->wantToLock>0 );
50998    p->wantToLock--;
50999    if( p->wantToLock==0 ){
51000      unlockBtreeMutex(p);
51001    }
51002  }
51003}
51004
51005#ifndef NDEBUG
51006/*
51007** Return true if the BtShared mutex is held on the btree, or if the
51008** B-Tree is not marked as sharable.
51009**
51010** This routine is used only from within assert() statements.
51011*/
51012SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
51013  assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
51014  assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
51015  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
51016  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
51017
51018  return (p->sharable==0 || p->locked);
51019}
51020#endif
51021
51022
51023#ifndef SQLITE_OMIT_INCRBLOB
51024/*
51025** Enter and leave a mutex on a Btree given a cursor owned by that
51026** Btree.  These entry points are used by incremental I/O and can be
51027** omitted if that module is not used.
51028*/
51029SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
51030  sqlite3BtreeEnter(pCur->pBtree);
51031}
51032SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
51033  sqlite3BtreeLeave(pCur->pBtree);
51034}
51035#endif /* SQLITE_OMIT_INCRBLOB */
51036
51037
51038/*
51039** Enter the mutex on every Btree associated with a database
51040** connection.  This is needed (for example) prior to parsing
51041** a statement since we will be comparing table and column names
51042** against all schemas and we do not want those schemas being
51043** reset out from under us.
51044**
51045** There is a corresponding leave-all procedures.
51046**
51047** Enter the mutexes in accending order by BtShared pointer address
51048** to avoid the possibility of deadlock when two threads with
51049** two or more btrees in common both try to lock all their btrees
51050** at the same instant.
51051*/
51052SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
51053  int i;
51054  Btree *p;
51055  assert( sqlite3_mutex_held(db->mutex) );
51056  for(i=0; i<db->nDb; i++){
51057    p = db->aDb[i].pBt;
51058    if( p ) sqlite3BtreeEnter(p);
51059  }
51060}
51061SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
51062  int i;
51063  Btree *p;
51064  assert( sqlite3_mutex_held(db->mutex) );
51065  for(i=0; i<db->nDb; i++){
51066    p = db->aDb[i].pBt;
51067    if( p ) sqlite3BtreeLeave(p);
51068  }
51069}
51070
51071/*
51072** Return true if a particular Btree requires a lock.  Return FALSE if
51073** no lock is ever required since it is not sharable.
51074*/
51075SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
51076  return p->sharable;
51077}
51078
51079#ifndef NDEBUG
51080/*
51081** Return true if the current thread holds the database connection
51082** mutex and all required BtShared mutexes.
51083**
51084** This routine is used inside assert() statements only.
51085*/
51086SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
51087  int i;
51088  if( !sqlite3_mutex_held(db->mutex) ){
51089    return 0;
51090  }
51091  for(i=0; i<db->nDb; i++){
51092    Btree *p;
51093    p = db->aDb[i].pBt;
51094    if( p && p->sharable &&
51095         (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
51096      return 0;
51097    }
51098  }
51099  return 1;
51100}
51101#endif /* NDEBUG */
51102
51103#ifndef NDEBUG
51104/*
51105** Return true if the correct mutexes are held for accessing the
51106** db->aDb[iDb].pSchema structure.  The mutexes required for schema
51107** access are:
51108**
51109**   (1) The mutex on db
51110**   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
51111**
51112** If pSchema is not NULL, then iDb is computed from pSchema and
51113** db using sqlite3SchemaToIndex().
51114*/
51115SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
51116  Btree *p;
51117  assert( db!=0 );
51118  if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
51119  assert( iDb>=0 && iDb<db->nDb );
51120  if( !sqlite3_mutex_held(db->mutex) ) return 0;
51121  if( iDb==1 ) return 1;
51122  p = db->aDb[iDb].pBt;
51123  assert( p!=0 );
51124  return p->sharable==0 || p->locked==1;
51125}
51126#endif /* NDEBUG */
51127
51128#else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
51129/*
51130** The following are special cases for mutex enter routines for use
51131** in single threaded applications that use shared cache.  Except for
51132** these two routines, all mutex operations are no-ops in that case and
51133** are null #defines in btree.h.
51134**
51135** If shared cache is disabled, then all btree mutex routines, including
51136** the ones below, are no-ops and are null #defines in btree.h.
51137*/
51138
51139SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
51140  p->pBt->db = p->db;
51141}
51142SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
51143  int i;
51144  for(i=0; i<db->nDb; i++){
51145    Btree *p = db->aDb[i].pBt;
51146    if( p ){
51147      p->pBt->db = p->db;
51148    }
51149  }
51150}
51151#endif /* if SQLITE_THREADSAFE */
51152#endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
51153
51154/************** End of btmutex.c *********************************************/
51155/************** Begin file btree.c *******************************************/
51156/*
51157** 2004 April 6
51158**
51159** The author disclaims copyright to this source code.  In place of
51160** a legal notice, here is a blessing:
51161**
51162**    May you do good and not evil.
51163**    May you find forgiveness for yourself and forgive others.
51164**    May you share freely, never taking more than you give.
51165**
51166*************************************************************************
51167** This file implements a external (disk-based) database using BTrees.
51168** See the header comment on "btreeInt.h" for additional information.
51169** Including a description of file format and an overview of operation.
51170*/
51171
51172/*
51173** The header string that appears at the beginning of every
51174** SQLite database.
51175*/
51176static const char zMagicHeader[] = SQLITE_FILE_HEADER;
51177
51178/*
51179** Set this global variable to 1 to enable tracing using the TRACE
51180** macro.
51181*/
51182#if 0
51183int sqlite3BtreeTrace=1;  /* True to enable tracing */
51184# define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
51185#else
51186# define TRACE(X)
51187#endif
51188
51189/*
51190** Extract a 2-byte big-endian integer from an array of unsigned bytes.
51191** But if the value is zero, make it 65536.
51192**
51193** This routine is used to extract the "offset to cell content area" value
51194** from the header of a btree page.  If the page size is 65536 and the page
51195** is empty, the offset should be 65536, but the 2-byte value stores zero.
51196** This routine makes the necessary adjustment to 65536.
51197*/
51198#define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
51199
51200/*
51201** Values passed as the 5th argument to allocateBtreePage()
51202*/
51203#define BTALLOC_ANY   0           /* Allocate any page */
51204#define BTALLOC_EXACT 1           /* Allocate exact page if possible */
51205#define BTALLOC_LE    2           /* Allocate any page <= the parameter */
51206
51207/*
51208** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
51209** defined, or 0 if it is. For example:
51210**
51211**   bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
51212*/
51213#ifndef SQLITE_OMIT_AUTOVACUUM
51214#define IfNotOmitAV(expr) (expr)
51215#else
51216#define IfNotOmitAV(expr) 0
51217#endif
51218
51219#ifndef SQLITE_OMIT_SHARED_CACHE
51220/*
51221** A list of BtShared objects that are eligible for participation
51222** in shared cache.  This variable has file scope during normal builds,
51223** but the test harness needs to access it so we make it global for
51224** test builds.
51225**
51226** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
51227*/
51228#ifdef SQLITE_TEST
51229SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
51230#else
51231static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
51232#endif
51233#endif /* SQLITE_OMIT_SHARED_CACHE */
51234
51235#ifndef SQLITE_OMIT_SHARED_CACHE
51236/*
51237** Enable or disable the shared pager and schema features.
51238**
51239** This routine has no effect on existing database connections.
51240** The shared cache setting effects only future calls to
51241** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
51242*/
51243SQLITE_API int sqlite3_enable_shared_cache(int enable){
51244  sqlite3GlobalConfig.sharedCacheEnabled = enable;
51245  return SQLITE_OK;
51246}
51247#endif
51248
51249
51250
51251#ifdef SQLITE_OMIT_SHARED_CACHE
51252  /*
51253  ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
51254  ** and clearAllSharedCacheTableLocks()
51255  ** manipulate entries in the BtShared.pLock linked list used to store
51256  ** shared-cache table level locks. If the library is compiled with the
51257  ** shared-cache feature disabled, then there is only ever one user
51258  ** of each BtShared structure and so this locking is not necessary.
51259  ** So define the lock related functions as no-ops.
51260  */
51261  #define querySharedCacheTableLock(a,b,c) SQLITE_OK
51262  #define setSharedCacheTableLock(a,b,c) SQLITE_OK
51263  #define clearAllSharedCacheTableLocks(a)
51264  #define downgradeAllSharedCacheTableLocks(a)
51265  #define hasSharedCacheTableLock(a,b,c,d) 1
51266  #define hasReadConflicts(a, b) 0
51267#endif
51268
51269#ifndef SQLITE_OMIT_SHARED_CACHE
51270
51271#ifdef SQLITE_DEBUG
51272/*
51273**** This function is only used as part of an assert() statement. ***
51274**
51275** Check to see if pBtree holds the required locks to read or write to the
51276** table with root page iRoot.   Return 1 if it does and 0 if not.
51277**
51278** For example, when writing to a table with root-page iRoot via
51279** Btree connection pBtree:
51280**
51281**    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
51282**
51283** When writing to an index that resides in a sharable database, the
51284** caller should have first obtained a lock specifying the root page of
51285** the corresponding table. This makes things a bit more complicated,
51286** as this module treats each table as a separate structure. To determine
51287** the table corresponding to the index being written, this
51288** function has to search through the database schema.
51289**
51290** Instead of a lock on the table/index rooted at page iRoot, the caller may
51291** hold a write-lock on the schema table (root page 1). This is also
51292** acceptable.
51293*/
51294static int hasSharedCacheTableLock(
51295  Btree *pBtree,         /* Handle that must hold lock */
51296  Pgno iRoot,            /* Root page of b-tree */
51297  int isIndex,           /* True if iRoot is the root of an index b-tree */
51298  int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
51299){
51300  Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
51301  Pgno iTab = 0;
51302  BtLock *pLock;
51303
51304  /* If this database is not shareable, or if the client is reading
51305  ** and has the read-uncommitted flag set, then no lock is required.
51306  ** Return true immediately.
51307  */
51308  if( (pBtree->sharable==0)
51309   || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
51310  ){
51311    return 1;
51312  }
51313
51314  /* If the client is reading  or writing an index and the schema is
51315  ** not loaded, then it is too difficult to actually check to see if
51316  ** the correct locks are held.  So do not bother - just return true.
51317  ** This case does not come up very often anyhow.
51318  */
51319  if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
51320    return 1;
51321  }
51322
51323  /* Figure out the root-page that the lock should be held on. For table
51324  ** b-trees, this is just the root page of the b-tree being read or
51325  ** written. For index b-trees, it is the root page of the associated
51326  ** table.  */
51327  if( isIndex ){
51328    HashElem *p;
51329    for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
51330      Index *pIdx = (Index *)sqliteHashData(p);
51331      if( pIdx->tnum==(int)iRoot ){
51332        iTab = pIdx->pTable->tnum;
51333      }
51334    }
51335  }else{
51336    iTab = iRoot;
51337  }
51338
51339  /* Search for the required lock. Either a write-lock on root-page iTab, a
51340  ** write-lock on the schema table, or (if the client is reading) a
51341  ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
51342  for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
51343    if( pLock->pBtree==pBtree
51344     && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
51345     && pLock->eLock>=eLockType
51346    ){
51347      return 1;
51348    }
51349  }
51350
51351  /* Failed to find the required lock. */
51352  return 0;
51353}
51354#endif /* SQLITE_DEBUG */
51355
51356#ifdef SQLITE_DEBUG
51357/*
51358**** This function may be used as part of assert() statements only. ****
51359**
51360** Return true if it would be illegal for pBtree to write into the
51361** table or index rooted at iRoot because other shared connections are
51362** simultaneously reading that same table or index.
51363**
51364** It is illegal for pBtree to write if some other Btree object that
51365** shares the same BtShared object is currently reading or writing
51366** the iRoot table.  Except, if the other Btree object has the
51367** read-uncommitted flag set, then it is OK for the other object to
51368** have a read cursor.
51369**
51370** For example, before writing to any part of the table or index
51371** rooted at page iRoot, one should call:
51372**
51373**    assert( !hasReadConflicts(pBtree, iRoot) );
51374*/
51375static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
51376  BtCursor *p;
51377  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
51378    if( p->pgnoRoot==iRoot
51379     && p->pBtree!=pBtree
51380     && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
51381    ){
51382      return 1;
51383    }
51384  }
51385  return 0;
51386}
51387#endif    /* #ifdef SQLITE_DEBUG */
51388
51389/*
51390** Query to see if Btree handle p may obtain a lock of type eLock
51391** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
51392** SQLITE_OK if the lock may be obtained (by calling
51393** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
51394*/
51395static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
51396  BtShared *pBt = p->pBt;
51397  BtLock *pIter;
51398
51399  assert( sqlite3BtreeHoldsMutex(p) );
51400  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
51401  assert( p->db!=0 );
51402  assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
51403
51404  /* If requesting a write-lock, then the Btree must have an open write
51405  ** transaction on this file. And, obviously, for this to be so there
51406  ** must be an open write transaction on the file itself.
51407  */
51408  assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
51409  assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
51410
51411  /* This routine is a no-op if the shared-cache is not enabled */
51412  if( !p->sharable ){
51413    return SQLITE_OK;
51414  }
51415
51416  /* If some other connection is holding an exclusive lock, the
51417  ** requested lock may not be obtained.
51418  */
51419  if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
51420    sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
51421    return SQLITE_LOCKED_SHAREDCACHE;
51422  }
51423
51424  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
51425    /* The condition (pIter->eLock!=eLock) in the following if(...)
51426    ** statement is a simplification of:
51427    **
51428    **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
51429    **
51430    ** since we know that if eLock==WRITE_LOCK, then no other connection
51431    ** may hold a WRITE_LOCK on any table in this file (since there can
51432    ** only be a single writer).
51433    */
51434    assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
51435    assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
51436    if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
51437      sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
51438      if( eLock==WRITE_LOCK ){
51439        assert( p==pBt->pWriter );
51440        pBt->btsFlags |= BTS_PENDING;
51441      }
51442      return SQLITE_LOCKED_SHAREDCACHE;
51443    }
51444  }
51445  return SQLITE_OK;
51446}
51447#endif /* !SQLITE_OMIT_SHARED_CACHE */
51448
51449#ifndef SQLITE_OMIT_SHARED_CACHE
51450/*
51451** Add a lock on the table with root-page iTable to the shared-btree used
51452** by Btree handle p. Parameter eLock must be either READ_LOCK or
51453** WRITE_LOCK.
51454**
51455** This function assumes the following:
51456**
51457**   (a) The specified Btree object p is connected to a sharable
51458**       database (one with the BtShared.sharable flag set), and
51459**
51460**   (b) No other Btree objects hold a lock that conflicts
51461**       with the requested lock (i.e. querySharedCacheTableLock() has
51462**       already been called and returned SQLITE_OK).
51463**
51464** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
51465** is returned if a malloc attempt fails.
51466*/
51467static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
51468  BtShared *pBt = p->pBt;
51469  BtLock *pLock = 0;
51470  BtLock *pIter;
51471
51472  assert( sqlite3BtreeHoldsMutex(p) );
51473  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
51474  assert( p->db!=0 );
51475
51476  /* A connection with the read-uncommitted flag set will never try to
51477  ** obtain a read-lock using this function. The only read-lock obtained
51478  ** by a connection in read-uncommitted mode is on the sqlite_master
51479  ** table, and that lock is obtained in BtreeBeginTrans().  */
51480  assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
51481
51482  /* This function should only be called on a sharable b-tree after it
51483  ** has been determined that no other b-tree holds a conflicting lock.  */
51484  assert( p->sharable );
51485  assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
51486
51487  /* First search the list for an existing lock on this table. */
51488  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
51489    if( pIter->iTable==iTable && pIter->pBtree==p ){
51490      pLock = pIter;
51491      break;
51492    }
51493  }
51494
51495  /* If the above search did not find a BtLock struct associating Btree p
51496  ** with table iTable, allocate one and link it into the list.
51497  */
51498  if( !pLock ){
51499    pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
51500    if( !pLock ){
51501      return SQLITE_NOMEM;
51502    }
51503    pLock->iTable = iTable;
51504    pLock->pBtree = p;
51505    pLock->pNext = pBt->pLock;
51506    pBt->pLock = pLock;
51507  }
51508
51509  /* Set the BtLock.eLock variable to the maximum of the current lock
51510  ** and the requested lock. This means if a write-lock was already held
51511  ** and a read-lock requested, we don't incorrectly downgrade the lock.
51512  */
51513  assert( WRITE_LOCK>READ_LOCK );
51514  if( eLock>pLock->eLock ){
51515    pLock->eLock = eLock;
51516  }
51517
51518  return SQLITE_OK;
51519}
51520#endif /* !SQLITE_OMIT_SHARED_CACHE */
51521
51522#ifndef SQLITE_OMIT_SHARED_CACHE
51523/*
51524** Release all the table locks (locks obtained via calls to
51525** the setSharedCacheTableLock() procedure) held by Btree object p.
51526**
51527** This function assumes that Btree p has an open read or write
51528** transaction. If it does not, then the BTS_PENDING flag
51529** may be incorrectly cleared.
51530*/
51531static void clearAllSharedCacheTableLocks(Btree *p){
51532  BtShared *pBt = p->pBt;
51533  BtLock **ppIter = &pBt->pLock;
51534
51535  assert( sqlite3BtreeHoldsMutex(p) );
51536  assert( p->sharable || 0==*ppIter );
51537  assert( p->inTrans>0 );
51538
51539  while( *ppIter ){
51540    BtLock *pLock = *ppIter;
51541    assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
51542    assert( pLock->pBtree->inTrans>=pLock->eLock );
51543    if( pLock->pBtree==p ){
51544      *ppIter = pLock->pNext;
51545      assert( pLock->iTable!=1 || pLock==&p->lock );
51546      if( pLock->iTable!=1 ){
51547        sqlite3_free(pLock);
51548      }
51549    }else{
51550      ppIter = &pLock->pNext;
51551    }
51552  }
51553
51554  assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
51555  if( pBt->pWriter==p ){
51556    pBt->pWriter = 0;
51557    pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
51558  }else if( pBt->nTransaction==2 ){
51559    /* This function is called when Btree p is concluding its
51560    ** transaction. If there currently exists a writer, and p is not
51561    ** that writer, then the number of locks held by connections other
51562    ** than the writer must be about to drop to zero. In this case
51563    ** set the BTS_PENDING flag to 0.
51564    **
51565    ** If there is not currently a writer, then BTS_PENDING must
51566    ** be zero already. So this next line is harmless in that case.
51567    */
51568    pBt->btsFlags &= ~BTS_PENDING;
51569  }
51570}
51571
51572/*
51573** This function changes all write-locks held by Btree p into read-locks.
51574*/
51575static void downgradeAllSharedCacheTableLocks(Btree *p){
51576  BtShared *pBt = p->pBt;
51577  if( pBt->pWriter==p ){
51578    BtLock *pLock;
51579    pBt->pWriter = 0;
51580    pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
51581    for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
51582      assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
51583      pLock->eLock = READ_LOCK;
51584    }
51585  }
51586}
51587
51588#endif /* SQLITE_OMIT_SHARED_CACHE */
51589
51590static void releasePage(MemPage *pPage);  /* Forward reference */
51591
51592/*
51593***** This routine is used inside of assert() only ****
51594**
51595** Verify that the cursor holds the mutex on its BtShared
51596*/
51597#ifdef SQLITE_DEBUG
51598static int cursorHoldsMutex(BtCursor *p){
51599  return sqlite3_mutex_held(p->pBt->mutex);
51600}
51601#endif
51602
51603/*
51604** Invalidate the overflow cache of the cursor passed as the first argument.
51605** on the shared btree structure pBt.
51606*/
51607#define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
51608
51609/*
51610** Invalidate the overflow page-list cache for all cursors opened
51611** on the shared btree structure pBt.
51612*/
51613static void invalidateAllOverflowCache(BtShared *pBt){
51614  BtCursor *p;
51615  assert( sqlite3_mutex_held(pBt->mutex) );
51616  for(p=pBt->pCursor; p; p=p->pNext){
51617    invalidateOverflowCache(p);
51618  }
51619}
51620
51621#ifndef SQLITE_OMIT_INCRBLOB
51622/*
51623** This function is called before modifying the contents of a table
51624** to invalidate any incrblob cursors that are open on the
51625** row or one of the rows being modified.
51626**
51627** If argument isClearTable is true, then the entire contents of the
51628** table is about to be deleted. In this case invalidate all incrblob
51629** cursors open on any row within the table with root-page pgnoRoot.
51630**
51631** Otherwise, if argument isClearTable is false, then the row with
51632** rowid iRow is being replaced or deleted. In this case invalidate
51633** only those incrblob cursors open on that specific row.
51634*/
51635static void invalidateIncrblobCursors(
51636  Btree *pBtree,          /* The database file to check */
51637  i64 iRow,               /* The rowid that might be changing */
51638  int isClearTable        /* True if all rows are being deleted */
51639){
51640  BtCursor *p;
51641  BtShared *pBt = pBtree->pBt;
51642  assert( sqlite3BtreeHoldsMutex(pBtree) );
51643  for(p=pBt->pCursor; p; p=p->pNext){
51644    if( (p->curFlags & BTCF_Incrblob)!=0 && (isClearTable || p->info.nKey==iRow) ){
51645      p->eState = CURSOR_INVALID;
51646    }
51647  }
51648}
51649
51650#else
51651  /* Stub function when INCRBLOB is omitted */
51652  #define invalidateIncrblobCursors(x,y,z)
51653#endif /* SQLITE_OMIT_INCRBLOB */
51654
51655/*
51656** Set bit pgno of the BtShared.pHasContent bitvec. This is called
51657** when a page that previously contained data becomes a free-list leaf
51658** page.
51659**
51660** The BtShared.pHasContent bitvec exists to work around an obscure
51661** bug caused by the interaction of two useful IO optimizations surrounding
51662** free-list leaf pages:
51663**
51664**   1) When all data is deleted from a page and the page becomes
51665**      a free-list leaf page, the page is not written to the database
51666**      (as free-list leaf pages contain no meaningful data). Sometimes
51667**      such a page is not even journalled (as it will not be modified,
51668**      why bother journalling it?).
51669**
51670**   2) When a free-list leaf page is reused, its content is not read
51671**      from the database or written to the journal file (why should it
51672**      be, if it is not at all meaningful?).
51673**
51674** By themselves, these optimizations work fine and provide a handy
51675** performance boost to bulk delete or insert operations. However, if
51676** a page is moved to the free-list and then reused within the same
51677** transaction, a problem comes up. If the page is not journalled when
51678** it is moved to the free-list and it is also not journalled when it
51679** is extracted from the free-list and reused, then the original data
51680** may be lost. In the event of a rollback, it may not be possible
51681** to restore the database to its original configuration.
51682**
51683** The solution is the BtShared.pHasContent bitvec. Whenever a page is
51684** moved to become a free-list leaf page, the corresponding bit is
51685** set in the bitvec. Whenever a leaf page is extracted from the free-list,
51686** optimization 2 above is omitted if the corresponding bit is already
51687** set in BtShared.pHasContent. The contents of the bitvec are cleared
51688** at the end of every transaction.
51689*/
51690static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
51691  int rc = SQLITE_OK;
51692  if( !pBt->pHasContent ){
51693    assert( pgno<=pBt->nPage );
51694    pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
51695    if( !pBt->pHasContent ){
51696      rc = SQLITE_NOMEM;
51697    }
51698  }
51699  if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
51700    rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
51701  }
51702  return rc;
51703}
51704
51705/*
51706** Query the BtShared.pHasContent vector.
51707**
51708** This function is called when a free-list leaf page is removed from the
51709** free-list for reuse. It returns false if it is safe to retrieve the
51710** page from the pager layer with the 'no-content' flag set. True otherwise.
51711*/
51712static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
51713  Bitvec *p = pBt->pHasContent;
51714  return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
51715}
51716
51717/*
51718** Clear (destroy) the BtShared.pHasContent bitvec. This should be
51719** invoked at the conclusion of each write-transaction.
51720*/
51721static void btreeClearHasContent(BtShared *pBt){
51722  sqlite3BitvecDestroy(pBt->pHasContent);
51723  pBt->pHasContent = 0;
51724}
51725
51726/*
51727** Release all of the apPage[] pages for a cursor.
51728*/
51729static void btreeReleaseAllCursorPages(BtCursor *pCur){
51730  int i;
51731  for(i=0; i<=pCur->iPage; i++){
51732    releasePage(pCur->apPage[i]);
51733    pCur->apPage[i] = 0;
51734  }
51735  pCur->iPage = -1;
51736}
51737
51738
51739/*
51740** Save the current cursor position in the variables BtCursor.nKey
51741** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
51742**
51743** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
51744** prior to calling this routine.
51745*/
51746static int saveCursorPosition(BtCursor *pCur){
51747  int rc;
51748
51749  assert( CURSOR_VALID==pCur->eState );
51750  assert( 0==pCur->pKey );
51751  assert( cursorHoldsMutex(pCur) );
51752
51753  rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
51754  assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
51755
51756  /* If this is an intKey table, then the above call to BtreeKeySize()
51757  ** stores the integer key in pCur->nKey. In this case this value is
51758  ** all that is required. Otherwise, if pCur is not open on an intKey
51759  ** table, then malloc space for and store the pCur->nKey bytes of key
51760  ** data.
51761  */
51762  if( 0==pCur->apPage[0]->intKey ){
51763    void *pKey = sqlite3Malloc( (int)pCur->nKey );
51764    if( pKey ){
51765      rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
51766      if( rc==SQLITE_OK ){
51767        pCur->pKey = pKey;
51768      }else{
51769        sqlite3_free(pKey);
51770      }
51771    }else{
51772      rc = SQLITE_NOMEM;
51773    }
51774  }
51775  assert( !pCur->apPage[0]->intKey || !pCur->pKey );
51776
51777  if( rc==SQLITE_OK ){
51778    btreeReleaseAllCursorPages(pCur);
51779    pCur->eState = CURSOR_REQUIRESEEK;
51780  }
51781
51782  invalidateOverflowCache(pCur);
51783  return rc;
51784}
51785
51786/*
51787** Save the positions of all cursors (except pExcept) that are open on
51788** the table  with root-page iRoot. Usually, this is called just before cursor
51789** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
51790*/
51791static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
51792  BtCursor *p;
51793  assert( sqlite3_mutex_held(pBt->mutex) );
51794  assert( pExcept==0 || pExcept->pBt==pBt );
51795  for(p=pBt->pCursor; p; p=p->pNext){
51796    if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
51797      if( p->eState==CURSOR_VALID ){
51798        int rc = saveCursorPosition(p);
51799        if( SQLITE_OK!=rc ){
51800          return rc;
51801        }
51802      }else{
51803        testcase( p->iPage>0 );
51804        btreeReleaseAllCursorPages(p);
51805      }
51806    }
51807  }
51808  return SQLITE_OK;
51809}
51810
51811/*
51812** Clear the current cursor position.
51813*/
51814SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
51815  assert( cursorHoldsMutex(pCur) );
51816  sqlite3_free(pCur->pKey);
51817  pCur->pKey = 0;
51818  pCur->eState = CURSOR_INVALID;
51819}
51820
51821/*
51822** In this version of BtreeMoveto, pKey is a packed index record
51823** such as is generated by the OP_MakeRecord opcode.  Unpack the
51824** record and then call BtreeMovetoUnpacked() to do the work.
51825*/
51826static int btreeMoveto(
51827  BtCursor *pCur,     /* Cursor open on the btree to be searched */
51828  const void *pKey,   /* Packed key if the btree is an index */
51829  i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
51830  int bias,           /* Bias search to the high end */
51831  int *pRes           /* Write search results here */
51832){
51833  int rc;                    /* Status code */
51834  UnpackedRecord *pIdxKey;   /* Unpacked index key */
51835  char aSpace[200];          /* Temp space for pIdxKey - to avoid a malloc */
51836  char *pFree = 0;
51837
51838  if( pKey ){
51839    assert( nKey==(i64)(int)nKey );
51840    pIdxKey = sqlite3VdbeAllocUnpackedRecord(
51841        pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
51842    );
51843    if( pIdxKey==0 ) return SQLITE_NOMEM;
51844    sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
51845    if( pIdxKey->nField==0 ){
51846      sqlite3DbFree(pCur->pKeyInfo->db, pFree);
51847      return SQLITE_CORRUPT_BKPT;
51848    }
51849  }else{
51850    pIdxKey = 0;
51851  }
51852  rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
51853  if( pFree ){
51854    sqlite3DbFree(pCur->pKeyInfo->db, pFree);
51855  }
51856  return rc;
51857}
51858
51859/*
51860** Restore the cursor to the position it was in (or as close to as possible)
51861** when saveCursorPosition() was called. Note that this call deletes the
51862** saved position info stored by saveCursorPosition(), so there can be
51863** at most one effective restoreCursorPosition() call after each
51864** saveCursorPosition().
51865*/
51866static int btreeRestoreCursorPosition(BtCursor *pCur){
51867  int rc;
51868  assert( cursorHoldsMutex(pCur) );
51869  assert( pCur->eState>=CURSOR_REQUIRESEEK );
51870  if( pCur->eState==CURSOR_FAULT ){
51871    return pCur->skipNext;
51872  }
51873  pCur->eState = CURSOR_INVALID;
51874  rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
51875  if( rc==SQLITE_OK ){
51876    sqlite3_free(pCur->pKey);
51877    pCur->pKey = 0;
51878    assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
51879    if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
51880      pCur->eState = CURSOR_SKIPNEXT;
51881    }
51882  }
51883  return rc;
51884}
51885
51886#define restoreCursorPosition(p) \
51887  (p->eState>=CURSOR_REQUIRESEEK ? \
51888         btreeRestoreCursorPosition(p) : \
51889         SQLITE_OK)
51890
51891/*
51892** Determine whether or not a cursor has moved from the position it
51893** was last placed at.  Cursors can move when the row they are pointing
51894** at is deleted out from under them.
51895**
51896** This routine returns an error code if something goes wrong.  The
51897** integer *pHasMoved is set as follows:
51898**
51899**    0:   The cursor is unchanged
51900**    1:   The cursor is still pointing at the same row, but the pointers
51901**         returned by sqlite3BtreeKeyFetch() or sqlite3BtreeDataFetch()
51902**         might now be invalid because of a balance() or other change to the
51903**         b-tree.
51904**    2:   The cursor is no longer pointing to the row.  The row might have
51905**         been deleted out from under the cursor.
51906*/
51907SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
51908  int rc;
51909
51910  if( pCur->eState==CURSOR_VALID ){
51911    *pHasMoved = 0;
51912    return SQLITE_OK;
51913  }
51914  rc = restoreCursorPosition(pCur);
51915  if( rc ){
51916    *pHasMoved = 2;
51917    return rc;
51918  }
51919  if( pCur->eState!=CURSOR_VALID || NEVER(pCur->skipNext!=0) ){
51920    *pHasMoved = 2;
51921  }else{
51922    *pHasMoved = 1;
51923  }
51924  return SQLITE_OK;
51925}
51926
51927#ifndef SQLITE_OMIT_AUTOVACUUM
51928/*
51929** Given a page number of a regular database page, return the page
51930** number for the pointer-map page that contains the entry for the
51931** input page number.
51932**
51933** Return 0 (not a valid page) for pgno==1 since there is
51934** no pointer map associated with page 1.  The integrity_check logic
51935** requires that ptrmapPageno(*,1)!=1.
51936*/
51937static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
51938  int nPagesPerMapPage;
51939  Pgno iPtrMap, ret;
51940  assert( sqlite3_mutex_held(pBt->mutex) );
51941  if( pgno<2 ) return 0;
51942  nPagesPerMapPage = (pBt->usableSize/5)+1;
51943  iPtrMap = (pgno-2)/nPagesPerMapPage;
51944  ret = (iPtrMap*nPagesPerMapPage) + 2;
51945  if( ret==PENDING_BYTE_PAGE(pBt) ){
51946    ret++;
51947  }
51948  return ret;
51949}
51950
51951/*
51952** Write an entry into the pointer map.
51953**
51954** This routine updates the pointer map entry for page number 'key'
51955** so that it maps to type 'eType' and parent page number 'pgno'.
51956**
51957** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
51958** a no-op.  If an error occurs, the appropriate error code is written
51959** into *pRC.
51960*/
51961static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
51962  DbPage *pDbPage;  /* The pointer map page */
51963  u8 *pPtrmap;      /* The pointer map data */
51964  Pgno iPtrmap;     /* The pointer map page number */
51965  int offset;       /* Offset in pointer map page */
51966  int rc;           /* Return code from subfunctions */
51967
51968  if( *pRC ) return;
51969
51970  assert( sqlite3_mutex_held(pBt->mutex) );
51971  /* The master-journal page number must never be used as a pointer map page */
51972  assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
51973
51974  assert( pBt->autoVacuum );
51975  if( key==0 ){
51976    *pRC = SQLITE_CORRUPT_BKPT;
51977    return;
51978  }
51979  iPtrmap = PTRMAP_PAGENO(pBt, key);
51980  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
51981  if( rc!=SQLITE_OK ){
51982    *pRC = rc;
51983    return;
51984  }
51985  offset = PTRMAP_PTROFFSET(iPtrmap, key);
51986  if( offset<0 ){
51987    *pRC = SQLITE_CORRUPT_BKPT;
51988    goto ptrmap_exit;
51989  }
51990  assert( offset <= (int)pBt->usableSize-5 );
51991  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
51992
51993  if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
51994    TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
51995    *pRC= rc = sqlite3PagerWrite(pDbPage);
51996    if( rc==SQLITE_OK ){
51997      pPtrmap[offset] = eType;
51998      put4byte(&pPtrmap[offset+1], parent);
51999    }
52000  }
52001
52002ptrmap_exit:
52003  sqlite3PagerUnref(pDbPage);
52004}
52005
52006/*
52007** Read an entry from the pointer map.
52008**
52009** This routine retrieves the pointer map entry for page 'key', writing
52010** the type and parent page number to *pEType and *pPgno respectively.
52011** An error code is returned if something goes wrong, otherwise SQLITE_OK.
52012*/
52013static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
52014  DbPage *pDbPage;   /* The pointer map page */
52015  int iPtrmap;       /* Pointer map page index */
52016  u8 *pPtrmap;       /* Pointer map page data */
52017  int offset;        /* Offset of entry in pointer map */
52018  int rc;
52019
52020  assert( sqlite3_mutex_held(pBt->mutex) );
52021
52022  iPtrmap = PTRMAP_PAGENO(pBt, key);
52023  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
52024  if( rc!=0 ){
52025    return rc;
52026  }
52027  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
52028
52029  offset = PTRMAP_PTROFFSET(iPtrmap, key);
52030  if( offset<0 ){
52031    sqlite3PagerUnref(pDbPage);
52032    return SQLITE_CORRUPT_BKPT;
52033  }
52034  assert( offset <= (int)pBt->usableSize-5 );
52035  assert( pEType!=0 );
52036  *pEType = pPtrmap[offset];
52037  if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
52038
52039  sqlite3PagerUnref(pDbPage);
52040  if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
52041  return SQLITE_OK;
52042}
52043
52044#else /* if defined SQLITE_OMIT_AUTOVACUUM */
52045  #define ptrmapPut(w,x,y,z,rc)
52046  #define ptrmapGet(w,x,y,z) SQLITE_OK
52047  #define ptrmapPutOvflPtr(x, y, rc)
52048#endif
52049
52050/*
52051** Given a btree page and a cell index (0 means the first cell on
52052** the page, 1 means the second cell, and so forth) return a pointer
52053** to the cell content.
52054**
52055** This routine works only for pages that do not contain overflow cells.
52056*/
52057#define findCell(P,I) \
52058  ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
52059#define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
52060
52061
52062/*
52063** This a more complex version of findCell() that works for
52064** pages that do contain overflow cells.
52065*/
52066static u8 *findOverflowCell(MemPage *pPage, int iCell){
52067  int i;
52068  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52069  for(i=pPage->nOverflow-1; i>=0; i--){
52070    int k;
52071    k = pPage->aiOvfl[i];
52072    if( k<=iCell ){
52073      if( k==iCell ){
52074        return pPage->apOvfl[i];
52075      }
52076      iCell--;
52077    }
52078  }
52079  return findCell(pPage, iCell);
52080}
52081
52082/*
52083** Parse a cell content block and fill in the CellInfo structure.  There
52084** are two versions of this function.  btreeParseCell() takes a
52085** cell index as the second argument and btreeParseCellPtr()
52086** takes a pointer to the body of the cell as its second argument.
52087**
52088** Within this file, the parseCell() macro can be called instead of
52089** btreeParseCellPtr(). Using some compilers, this will be faster.
52090*/
52091static void btreeParseCellPtr(
52092  MemPage *pPage,         /* Page containing the cell */
52093  u8 *pCell,              /* Pointer to the cell text. */
52094  CellInfo *pInfo         /* Fill in this structure */
52095){
52096  u16 n;                  /* Number bytes in cell content header */
52097  u32 nPayload;           /* Number of bytes of cell payload */
52098
52099  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52100
52101  pInfo->pCell = pCell;
52102  assert( pPage->leaf==0 || pPage->leaf==1 );
52103  n = pPage->childPtrSize;
52104  assert( n==4-4*pPage->leaf );
52105  if( pPage->intKey ){
52106    if( pPage->hasData ){
52107      assert( n==0 );
52108      n = getVarint32(pCell, nPayload);
52109    }else{
52110      nPayload = 0;
52111    }
52112    n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
52113    pInfo->nData = nPayload;
52114  }else{
52115    pInfo->nData = 0;
52116    n += getVarint32(&pCell[n], nPayload);
52117    pInfo->nKey = nPayload;
52118  }
52119  pInfo->nPayload = nPayload;
52120  pInfo->nHeader = n;
52121  testcase( nPayload==pPage->maxLocal );
52122  testcase( nPayload==pPage->maxLocal+1 );
52123  if( likely(nPayload<=pPage->maxLocal) ){
52124    /* This is the (easy) common case where the entire payload fits
52125    ** on the local page.  No overflow is required.
52126    */
52127    if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
52128    pInfo->nLocal = (u16)nPayload;
52129    pInfo->iOverflow = 0;
52130  }else{
52131    /* If the payload will not fit completely on the local page, we have
52132    ** to decide how much to store locally and how much to spill onto
52133    ** overflow pages.  The strategy is to minimize the amount of unused
52134    ** space on overflow pages while keeping the amount of local storage
52135    ** in between minLocal and maxLocal.
52136    **
52137    ** Warning:  changing the way overflow payload is distributed in any
52138    ** way will result in an incompatible file format.
52139    */
52140    int minLocal;  /* Minimum amount of payload held locally */
52141    int maxLocal;  /* Maximum amount of payload held locally */
52142    int surplus;   /* Overflow payload available for local storage */
52143
52144    minLocal = pPage->minLocal;
52145    maxLocal = pPage->maxLocal;
52146    surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
52147    testcase( surplus==maxLocal );
52148    testcase( surplus==maxLocal+1 );
52149    if( surplus <= maxLocal ){
52150      pInfo->nLocal = (u16)surplus;
52151    }else{
52152      pInfo->nLocal = (u16)minLocal;
52153    }
52154    pInfo->iOverflow = (u16)(pInfo->nLocal + n);
52155    pInfo->nSize = pInfo->iOverflow + 4;
52156  }
52157}
52158#define parseCell(pPage, iCell, pInfo) \
52159  btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
52160static void btreeParseCell(
52161  MemPage *pPage,         /* Page containing the cell */
52162  int iCell,              /* The cell index.  First cell is 0 */
52163  CellInfo *pInfo         /* Fill in this structure */
52164){
52165  parseCell(pPage, iCell, pInfo);
52166}
52167
52168/*
52169** Compute the total number of bytes that a Cell needs in the cell
52170** data area of the btree-page.  The return number includes the cell
52171** data header and the local payload, but not any overflow page or
52172** the space used by the cell pointer.
52173*/
52174static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
52175  u8 *pIter = &pCell[pPage->childPtrSize];
52176  u32 nSize;
52177
52178#ifdef SQLITE_DEBUG
52179  /* The value returned by this function should always be the same as
52180  ** the (CellInfo.nSize) value found by doing a full parse of the
52181  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
52182  ** this function verifies that this invariant is not violated. */
52183  CellInfo debuginfo;
52184  btreeParseCellPtr(pPage, pCell, &debuginfo);
52185#endif
52186
52187  if( pPage->intKey ){
52188    u8 *pEnd;
52189    if( pPage->hasData ){
52190      pIter += getVarint32(pIter, nSize);
52191    }else{
52192      nSize = 0;
52193    }
52194
52195    /* pIter now points at the 64-bit integer key value, a variable length
52196    ** integer. The following block moves pIter to point at the first byte
52197    ** past the end of the key value. */
52198    pEnd = &pIter[9];
52199    while( (*pIter++)&0x80 && pIter<pEnd );
52200  }else{
52201    pIter += getVarint32(pIter, nSize);
52202  }
52203
52204  testcase( nSize==pPage->maxLocal );
52205  testcase( nSize==pPage->maxLocal+1 );
52206  if( nSize>pPage->maxLocal ){
52207    int minLocal = pPage->minLocal;
52208    nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
52209    testcase( nSize==pPage->maxLocal );
52210    testcase( nSize==pPage->maxLocal+1 );
52211    if( nSize>pPage->maxLocal ){
52212      nSize = minLocal;
52213    }
52214    nSize += 4;
52215  }
52216  nSize += (u32)(pIter - pCell);
52217
52218  /* The minimum size of any cell is 4 bytes. */
52219  if( nSize<4 ){
52220    nSize = 4;
52221  }
52222
52223  assert( nSize==debuginfo.nSize );
52224  return (u16)nSize;
52225}
52226
52227#ifdef SQLITE_DEBUG
52228/* This variation on cellSizePtr() is used inside of assert() statements
52229** only. */
52230static u16 cellSize(MemPage *pPage, int iCell){
52231  return cellSizePtr(pPage, findCell(pPage, iCell));
52232}
52233#endif
52234
52235#ifndef SQLITE_OMIT_AUTOVACUUM
52236/*
52237** If the cell pCell, part of page pPage contains a pointer
52238** to an overflow page, insert an entry into the pointer-map
52239** for the overflow page.
52240*/
52241static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
52242  CellInfo info;
52243  if( *pRC ) return;
52244  assert( pCell!=0 );
52245  btreeParseCellPtr(pPage, pCell, &info);
52246  assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
52247  if( info.iOverflow ){
52248    Pgno ovfl = get4byte(&pCell[info.iOverflow]);
52249    ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
52250  }
52251}
52252#endif
52253
52254
52255/*
52256** Defragment the page given.  All Cells are moved to the
52257** end of the page and all free space is collected into one
52258** big FreeBlk that occurs in between the header and cell
52259** pointer array and the cell content area.
52260*/
52261static int defragmentPage(MemPage *pPage){
52262  int i;                     /* Loop counter */
52263  int pc;                    /* Address of a i-th cell */
52264  int hdr;                   /* Offset to the page header */
52265  int size;                  /* Size of a cell */
52266  int usableSize;            /* Number of usable bytes on a page */
52267  int cellOffset;            /* Offset to the cell pointer array */
52268  int cbrk;                  /* Offset to the cell content area */
52269  int nCell;                 /* Number of cells on the page */
52270  unsigned char *data;       /* The page data */
52271  unsigned char *temp;       /* Temp area for cell content */
52272  int iCellFirst;            /* First allowable cell index */
52273  int iCellLast;             /* Last possible cell index */
52274
52275
52276  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52277  assert( pPage->pBt!=0 );
52278  assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
52279  assert( pPage->nOverflow==0 );
52280  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52281  temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
52282  data = pPage->aData;
52283  hdr = pPage->hdrOffset;
52284  cellOffset = pPage->cellOffset;
52285  nCell = pPage->nCell;
52286  assert( nCell==get2byte(&data[hdr+3]) );
52287  usableSize = pPage->pBt->usableSize;
52288  cbrk = get2byte(&data[hdr+5]);
52289  memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
52290  cbrk = usableSize;
52291  iCellFirst = cellOffset + 2*nCell;
52292  iCellLast = usableSize - 4;
52293  for(i=0; i<nCell; i++){
52294    u8 *pAddr;     /* The i-th cell pointer */
52295    pAddr = &data[cellOffset + i*2];
52296    pc = get2byte(pAddr);
52297    testcase( pc==iCellFirst );
52298    testcase( pc==iCellLast );
52299#if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
52300    /* These conditions have already been verified in btreeInitPage()
52301    ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
52302    */
52303    if( pc<iCellFirst || pc>iCellLast ){
52304      return SQLITE_CORRUPT_BKPT;
52305    }
52306#endif
52307    assert( pc>=iCellFirst && pc<=iCellLast );
52308    size = cellSizePtr(pPage, &temp[pc]);
52309    cbrk -= size;
52310#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
52311    if( cbrk<iCellFirst ){
52312      return SQLITE_CORRUPT_BKPT;
52313    }
52314#else
52315    if( cbrk<iCellFirst || pc+size>usableSize ){
52316      return SQLITE_CORRUPT_BKPT;
52317    }
52318#endif
52319    assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
52320    testcase( cbrk+size==usableSize );
52321    testcase( pc+size==usableSize );
52322    memcpy(&data[cbrk], &temp[pc], size);
52323    put2byte(pAddr, cbrk);
52324  }
52325  assert( cbrk>=iCellFirst );
52326  put2byte(&data[hdr+5], cbrk);
52327  data[hdr+1] = 0;
52328  data[hdr+2] = 0;
52329  data[hdr+7] = 0;
52330  memset(&data[iCellFirst], 0, cbrk-iCellFirst);
52331  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52332  if( cbrk-iCellFirst!=pPage->nFree ){
52333    return SQLITE_CORRUPT_BKPT;
52334  }
52335  return SQLITE_OK;
52336}
52337
52338/*
52339** Allocate nByte bytes of space from within the B-Tree page passed
52340** as the first argument. Write into *pIdx the index into pPage->aData[]
52341** of the first byte of allocated space. Return either SQLITE_OK or
52342** an error code (usually SQLITE_CORRUPT).
52343**
52344** The caller guarantees that there is sufficient space to make the
52345** allocation.  This routine might need to defragment in order to bring
52346** all the space together, however.  This routine will avoid using
52347** the first two bytes past the cell pointer area since presumably this
52348** allocation is being made in order to insert a new cell, so we will
52349** also end up needing a new cell pointer.
52350*/
52351static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
52352  const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
52353  u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
52354  int nFrag;                           /* Number of fragmented bytes on pPage */
52355  int top;                             /* First byte of cell content area */
52356  int gap;        /* First byte of gap between cell pointers and cell content */
52357  int rc;         /* Integer return code */
52358  int usableSize; /* Usable size of the page */
52359
52360  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52361  assert( pPage->pBt );
52362  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52363  assert( nByte>=0 );  /* Minimum cell size is 4 */
52364  assert( pPage->nFree>=nByte );
52365  assert( pPage->nOverflow==0 );
52366  usableSize = pPage->pBt->usableSize;
52367  assert( nByte < usableSize-8 );
52368
52369  nFrag = data[hdr+7];
52370  assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
52371  gap = pPage->cellOffset + 2*pPage->nCell;
52372  top = get2byteNotZero(&data[hdr+5]);
52373  if( gap>top ) return SQLITE_CORRUPT_BKPT;
52374  testcase( gap+2==top );
52375  testcase( gap+1==top );
52376  testcase( gap==top );
52377
52378  if( nFrag>=60 ){
52379    /* Always defragment highly fragmented pages */
52380    rc = defragmentPage(pPage);
52381    if( rc ) return rc;
52382    top = get2byteNotZero(&data[hdr+5]);
52383  }else if( gap+2<=top ){
52384    /* Search the freelist looking for a free slot big enough to satisfy
52385    ** the request. The allocation is made from the first free slot in
52386    ** the list that is large enough to accommodate it.
52387    */
52388    int pc, addr;
52389    for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
52390      int size;            /* Size of the free slot */
52391      if( pc>usableSize-4 || pc<addr+4 ){
52392        return SQLITE_CORRUPT_BKPT;
52393      }
52394      size = get2byte(&data[pc+2]);
52395      if( size>=nByte ){
52396        int x = size - nByte;
52397        testcase( x==4 );
52398        testcase( x==3 );
52399        if( x<4 ){
52400          /* Remove the slot from the free-list. Update the number of
52401          ** fragmented bytes within the page. */
52402          memcpy(&data[addr], &data[pc], 2);
52403          data[hdr+7] = (u8)(nFrag + x);
52404        }else if( size+pc > usableSize ){
52405          return SQLITE_CORRUPT_BKPT;
52406        }else{
52407          /* The slot remains on the free-list. Reduce its size to account
52408          ** for the portion used by the new allocation. */
52409          put2byte(&data[pc+2], x);
52410        }
52411        *pIdx = pc + x;
52412        return SQLITE_OK;
52413      }
52414    }
52415  }
52416
52417  /* Check to make sure there is enough space in the gap to satisfy
52418  ** the allocation.  If not, defragment.
52419  */
52420  testcase( gap+2+nByte==top );
52421  if( gap+2+nByte>top ){
52422    rc = defragmentPage(pPage);
52423    if( rc ) return rc;
52424    top = get2byteNotZero(&data[hdr+5]);
52425    assert( gap+nByte<=top );
52426  }
52427
52428
52429  /* Allocate memory from the gap in between the cell pointer array
52430  ** and the cell content area.  The btreeInitPage() call has already
52431  ** validated the freelist.  Given that the freelist is valid, there
52432  ** is no way that the allocation can extend off the end of the page.
52433  ** The assert() below verifies the previous sentence.
52434  */
52435  top -= nByte;
52436  put2byte(&data[hdr+5], top);
52437  assert( top+nByte <= (int)pPage->pBt->usableSize );
52438  *pIdx = top;
52439  return SQLITE_OK;
52440}
52441
52442/*
52443** Return a section of the pPage->aData to the freelist.
52444** The first byte of the new free block is pPage->aDisk[start]
52445** and the size of the block is "size" bytes.
52446**
52447** Most of the effort here is involved in coalesing adjacent
52448** free blocks into a single big free block.
52449*/
52450static int freeSpace(MemPage *pPage, int start, int size){
52451  int addr, pbegin, hdr;
52452  int iLast;                        /* Largest possible freeblock offset */
52453  unsigned char *data = pPage->aData;
52454
52455  assert( pPage->pBt!=0 );
52456  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52457  assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
52458  assert( (start + size) <= (int)pPage->pBt->usableSize );
52459  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52460  assert( size>=0 );   /* Minimum cell size is 4 */
52461
52462  if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
52463    /* Overwrite deleted information with zeros when the secure_delete
52464    ** option is enabled */
52465    memset(&data[start], 0, size);
52466  }
52467
52468  /* Add the space back into the linked list of freeblocks.  Note that
52469  ** even though the freeblock list was checked by btreeInitPage(),
52470  ** btreeInitPage() did not detect overlapping cells or
52471  ** freeblocks that overlapped cells.   Nor does it detect when the
52472  ** cell content area exceeds the value in the page header.  If these
52473  ** situations arise, then subsequent insert operations might corrupt
52474  ** the freelist.  So we do need to check for corruption while scanning
52475  ** the freelist.
52476  */
52477  hdr = pPage->hdrOffset;
52478  addr = hdr + 1;
52479  iLast = pPage->pBt->usableSize - 4;
52480  assert( start<=iLast );
52481  while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
52482    if( pbegin<addr+4 ){
52483      return SQLITE_CORRUPT_BKPT;
52484    }
52485    addr = pbegin;
52486  }
52487  if( pbegin>iLast ){
52488    return SQLITE_CORRUPT_BKPT;
52489  }
52490  assert( pbegin>addr || pbegin==0 );
52491  put2byte(&data[addr], start);
52492  put2byte(&data[start], pbegin);
52493  put2byte(&data[start+2], size);
52494  pPage->nFree = pPage->nFree + (u16)size;
52495
52496  /* Coalesce adjacent free blocks */
52497  addr = hdr + 1;
52498  while( (pbegin = get2byte(&data[addr]))>0 ){
52499    int pnext, psize, x;
52500    assert( pbegin>addr );
52501    assert( pbegin <= (int)pPage->pBt->usableSize-4 );
52502    pnext = get2byte(&data[pbegin]);
52503    psize = get2byte(&data[pbegin+2]);
52504    if( pbegin + psize + 3 >= pnext && pnext>0 ){
52505      int frag = pnext - (pbegin+psize);
52506      if( (frag<0) || (frag>(int)data[hdr+7]) ){
52507        return SQLITE_CORRUPT_BKPT;
52508      }
52509      data[hdr+7] -= (u8)frag;
52510      x = get2byte(&data[pnext]);
52511      put2byte(&data[pbegin], x);
52512      x = pnext + get2byte(&data[pnext+2]) - pbegin;
52513      put2byte(&data[pbegin+2], x);
52514    }else{
52515      addr = pbegin;
52516    }
52517  }
52518
52519  /* If the cell content area begins with a freeblock, remove it. */
52520  if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
52521    int top;
52522    pbegin = get2byte(&data[hdr+1]);
52523    memcpy(&data[hdr+1], &data[pbegin], 2);
52524    top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
52525    put2byte(&data[hdr+5], top);
52526  }
52527  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52528  return SQLITE_OK;
52529}
52530
52531/*
52532** Decode the flags byte (the first byte of the header) for a page
52533** and initialize fields of the MemPage structure accordingly.
52534**
52535** Only the following combinations are supported.  Anything different
52536** indicates a corrupt database files:
52537**
52538**         PTF_ZERODATA
52539**         PTF_ZERODATA | PTF_LEAF
52540**         PTF_LEAFDATA | PTF_INTKEY
52541**         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
52542*/
52543static int decodeFlags(MemPage *pPage, int flagByte){
52544  BtShared *pBt;     /* A copy of pPage->pBt */
52545
52546  assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
52547  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52548  pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
52549  flagByte &= ~PTF_LEAF;
52550  pPage->childPtrSize = 4-4*pPage->leaf;
52551  pBt = pPage->pBt;
52552  if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
52553    pPage->intKey = 1;
52554    pPage->hasData = pPage->leaf;
52555    pPage->maxLocal = pBt->maxLeaf;
52556    pPage->minLocal = pBt->minLeaf;
52557  }else if( flagByte==PTF_ZERODATA ){
52558    pPage->intKey = 0;
52559    pPage->hasData = 0;
52560    pPage->maxLocal = pBt->maxLocal;
52561    pPage->minLocal = pBt->minLocal;
52562  }else{
52563    return SQLITE_CORRUPT_BKPT;
52564  }
52565  pPage->max1bytePayload = pBt->max1bytePayload;
52566  return SQLITE_OK;
52567}
52568
52569/*
52570** Initialize the auxiliary information for a disk block.
52571**
52572** Return SQLITE_OK on success.  If we see that the page does
52573** not contain a well-formed database page, then return
52574** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
52575** guarantee that the page is well-formed.  It only shows that
52576** we failed to detect any corruption.
52577*/
52578static int btreeInitPage(MemPage *pPage){
52579
52580  assert( pPage->pBt!=0 );
52581  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52582  assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
52583  assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
52584  assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
52585
52586  if( !pPage->isInit ){
52587    u16 pc;            /* Address of a freeblock within pPage->aData[] */
52588    u8 hdr;            /* Offset to beginning of page header */
52589    u8 *data;          /* Equal to pPage->aData */
52590    BtShared *pBt;        /* The main btree structure */
52591    int usableSize;    /* Amount of usable space on each page */
52592    u16 cellOffset;    /* Offset from start of page to first cell pointer */
52593    int nFree;         /* Number of unused bytes on the page */
52594    int top;           /* First byte of the cell content area */
52595    int iCellFirst;    /* First allowable cell or freeblock offset */
52596    int iCellLast;     /* Last possible cell or freeblock offset */
52597
52598    pBt = pPage->pBt;
52599
52600    hdr = pPage->hdrOffset;
52601    data = pPage->aData;
52602    if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
52603    assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
52604    pPage->maskPage = (u16)(pBt->pageSize - 1);
52605    pPage->nOverflow = 0;
52606    usableSize = pBt->usableSize;
52607    pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
52608    pPage->aDataEnd = &data[usableSize];
52609    pPage->aCellIdx = &data[cellOffset];
52610    top = get2byteNotZero(&data[hdr+5]);
52611    pPage->nCell = get2byte(&data[hdr+3]);
52612    if( pPage->nCell>MX_CELL(pBt) ){
52613      /* To many cells for a single page.  The page must be corrupt */
52614      return SQLITE_CORRUPT_BKPT;
52615    }
52616    testcase( pPage->nCell==MX_CELL(pBt) );
52617
52618    /* A malformed database page might cause us to read past the end
52619    ** of page when parsing a cell.
52620    **
52621    ** The following block of code checks early to see if a cell extends
52622    ** past the end of a page boundary and causes SQLITE_CORRUPT to be
52623    ** returned if it does.
52624    */
52625    iCellFirst = cellOffset + 2*pPage->nCell;
52626    iCellLast = usableSize - 4;
52627#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
52628    {
52629      int i;            /* Index into the cell pointer array */
52630      int sz;           /* Size of a cell */
52631
52632      if( !pPage->leaf ) iCellLast--;
52633      for(i=0; i<pPage->nCell; i++){
52634        pc = get2byte(&data[cellOffset+i*2]);
52635        testcase( pc==iCellFirst );
52636        testcase( pc==iCellLast );
52637        if( pc<iCellFirst || pc>iCellLast ){
52638          return SQLITE_CORRUPT_BKPT;
52639        }
52640        sz = cellSizePtr(pPage, &data[pc]);
52641        testcase( pc+sz==usableSize );
52642        if( pc+sz>usableSize ){
52643          return SQLITE_CORRUPT_BKPT;
52644        }
52645      }
52646      if( !pPage->leaf ) iCellLast++;
52647    }
52648#endif
52649
52650    /* Compute the total free space on the page */
52651    pc = get2byte(&data[hdr+1]);
52652    nFree = data[hdr+7] + top;
52653    while( pc>0 ){
52654      u16 next, size;
52655      if( pc<iCellFirst || pc>iCellLast ){
52656        /* Start of free block is off the page */
52657        return SQLITE_CORRUPT_BKPT;
52658      }
52659      next = get2byte(&data[pc]);
52660      size = get2byte(&data[pc+2]);
52661      if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
52662        /* Free blocks must be in ascending order. And the last byte of
52663        ** the free-block must lie on the database page.  */
52664        return SQLITE_CORRUPT_BKPT;
52665      }
52666      nFree = nFree + size;
52667      pc = next;
52668    }
52669
52670    /* At this point, nFree contains the sum of the offset to the start
52671    ** of the cell-content area plus the number of free bytes within
52672    ** the cell-content area. If this is greater than the usable-size
52673    ** of the page, then the page must be corrupted. This check also
52674    ** serves to verify that the offset to the start of the cell-content
52675    ** area, according to the page header, lies within the page.
52676    */
52677    if( nFree>usableSize ){
52678      return SQLITE_CORRUPT_BKPT;
52679    }
52680    pPage->nFree = (u16)(nFree - iCellFirst);
52681    pPage->isInit = 1;
52682  }
52683  return SQLITE_OK;
52684}
52685
52686/*
52687** Set up a raw page so that it looks like a database page holding
52688** no entries.
52689*/
52690static void zeroPage(MemPage *pPage, int flags){
52691  unsigned char *data = pPage->aData;
52692  BtShared *pBt = pPage->pBt;
52693  u8 hdr = pPage->hdrOffset;
52694  u16 first;
52695
52696  assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
52697  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
52698  assert( sqlite3PagerGetData(pPage->pDbPage) == data );
52699  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52700  assert( sqlite3_mutex_held(pBt->mutex) );
52701  if( pBt->btsFlags & BTS_SECURE_DELETE ){
52702    memset(&data[hdr], 0, pBt->usableSize - hdr);
52703  }
52704  data[hdr] = (char)flags;
52705  first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
52706  memset(&data[hdr+1], 0, 4);
52707  data[hdr+7] = 0;
52708  put2byte(&data[hdr+5], pBt->usableSize);
52709  pPage->nFree = (u16)(pBt->usableSize - first);
52710  decodeFlags(pPage, flags);
52711  pPage->cellOffset = first;
52712  pPage->aDataEnd = &data[pBt->usableSize];
52713  pPage->aCellIdx = &data[first];
52714  pPage->nOverflow = 0;
52715  assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
52716  pPage->maskPage = (u16)(pBt->pageSize - 1);
52717  pPage->nCell = 0;
52718  pPage->isInit = 1;
52719}
52720
52721
52722/*
52723** Convert a DbPage obtained from the pager into a MemPage used by
52724** the btree layer.
52725*/
52726static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
52727  MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
52728  pPage->aData = sqlite3PagerGetData(pDbPage);
52729  pPage->pDbPage = pDbPage;
52730  pPage->pBt = pBt;
52731  pPage->pgno = pgno;
52732  pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
52733  return pPage;
52734}
52735
52736/*
52737** Get a page from the pager.  Initialize the MemPage.pBt and
52738** MemPage.aData elements if needed.
52739**
52740** If the noContent flag is set, it means that we do not care about
52741** the content of the page at this time.  So do not go to the disk
52742** to fetch the content.  Just fill in the content with zeros for now.
52743** If in the future we call sqlite3PagerWrite() on this page, that
52744** means we have started to be concerned about content and the disk
52745** read should occur at that point.
52746*/
52747static int btreeGetPage(
52748  BtShared *pBt,       /* The btree */
52749  Pgno pgno,           /* Number of the page to fetch */
52750  MemPage **ppPage,    /* Return the page in this parameter */
52751  int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
52752){
52753  int rc;
52754  DbPage *pDbPage;
52755
52756  assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
52757  assert( sqlite3_mutex_held(pBt->mutex) );
52758  rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
52759  if( rc ) return rc;
52760  *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
52761  return SQLITE_OK;
52762}
52763
52764/*
52765** Retrieve a page from the pager cache. If the requested page is not
52766** already in the pager cache return NULL. Initialize the MemPage.pBt and
52767** MemPage.aData elements if needed.
52768*/
52769static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
52770  DbPage *pDbPage;
52771  assert( sqlite3_mutex_held(pBt->mutex) );
52772  pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
52773  if( pDbPage ){
52774    return btreePageFromDbPage(pDbPage, pgno, pBt);
52775  }
52776  return 0;
52777}
52778
52779/*
52780** Return the size of the database file in pages. If there is any kind of
52781** error, return ((unsigned int)-1).
52782*/
52783static Pgno btreePagecount(BtShared *pBt){
52784  return pBt->nPage;
52785}
52786SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
52787  assert( sqlite3BtreeHoldsMutex(p) );
52788  assert( ((p->pBt->nPage)&0x8000000)==0 );
52789  return (int)btreePagecount(p->pBt);
52790}
52791
52792/*
52793** Get a page from the pager and initialize it.  This routine is just a
52794** convenience wrapper around separate calls to btreeGetPage() and
52795** btreeInitPage().
52796**
52797** If an error occurs, then the value *ppPage is set to is undefined. It
52798** may remain unchanged, or it may be set to an invalid value.
52799*/
52800static int getAndInitPage(
52801  BtShared *pBt,                  /* The database file */
52802  Pgno pgno,                      /* Number of the page to get */
52803  MemPage **ppPage,               /* Write the page pointer here */
52804  int bReadonly                   /* PAGER_GET_READONLY or 0 */
52805){
52806  int rc;
52807  assert( sqlite3_mutex_held(pBt->mutex) );
52808  assert( bReadonly==PAGER_GET_READONLY || bReadonly==0 );
52809
52810  if( pgno>btreePagecount(pBt) ){
52811    rc = SQLITE_CORRUPT_BKPT;
52812  }else{
52813    rc = btreeGetPage(pBt, pgno, ppPage, bReadonly);
52814    if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
52815      rc = btreeInitPage(*ppPage);
52816      if( rc!=SQLITE_OK ){
52817        releasePage(*ppPage);
52818      }
52819    }
52820  }
52821
52822  testcase( pgno==0 );
52823  assert( pgno!=0 || rc==SQLITE_CORRUPT );
52824  return rc;
52825}
52826
52827/*
52828** Release a MemPage.  This should be called once for each prior
52829** call to btreeGetPage.
52830*/
52831static void releasePage(MemPage *pPage){
52832  if( pPage ){
52833    assert( pPage->aData );
52834    assert( pPage->pBt );
52835    assert( pPage->pDbPage!=0 );
52836    assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
52837    assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
52838    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52839    sqlite3PagerUnrefNotNull(pPage->pDbPage);
52840  }
52841}
52842
52843/*
52844** During a rollback, when the pager reloads information into the cache
52845** so that the cache is restored to its original state at the start of
52846** the transaction, for each page restored this routine is called.
52847**
52848** This routine needs to reset the extra data section at the end of the
52849** page to agree with the restored data.
52850*/
52851static void pageReinit(DbPage *pData){
52852  MemPage *pPage;
52853  pPage = (MemPage *)sqlite3PagerGetExtra(pData);
52854  assert( sqlite3PagerPageRefcount(pData)>0 );
52855  if( pPage->isInit ){
52856    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52857    pPage->isInit = 0;
52858    if( sqlite3PagerPageRefcount(pData)>1 ){
52859      /* pPage might not be a btree page;  it might be an overflow page
52860      ** or ptrmap page or a free page.  In those cases, the following
52861      ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
52862      ** But no harm is done by this.  And it is very important that
52863      ** btreeInitPage() be called on every btree page so we make
52864      ** the call for every page that comes in for re-initing. */
52865      btreeInitPage(pPage);
52866    }
52867  }
52868}
52869
52870/*
52871** Invoke the busy handler for a btree.
52872*/
52873static int btreeInvokeBusyHandler(void *pArg){
52874  BtShared *pBt = (BtShared*)pArg;
52875  assert( pBt->db );
52876  assert( sqlite3_mutex_held(pBt->db->mutex) );
52877  return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
52878}
52879
52880/*
52881** Open a database file.
52882**
52883** zFilename is the name of the database file.  If zFilename is NULL
52884** then an ephemeral database is created.  The ephemeral database might
52885** be exclusively in memory, or it might use a disk-based memory cache.
52886** Either way, the ephemeral database will be automatically deleted
52887** when sqlite3BtreeClose() is called.
52888**
52889** If zFilename is ":memory:" then an in-memory database is created
52890** that is automatically destroyed when it is closed.
52891**
52892** The "flags" parameter is a bitmask that might contain bits like
52893** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
52894**
52895** If the database is already opened in the same database connection
52896** and we are in shared cache mode, then the open will fail with an
52897** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
52898** objects in the same database connection since doing so will lead
52899** to problems with locking.
52900*/
52901SQLITE_PRIVATE int sqlite3BtreeOpen(
52902  sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
52903  const char *zFilename,  /* Name of the file containing the BTree database */
52904  sqlite3 *db,            /* Associated database handle */
52905  Btree **ppBtree,        /* Pointer to new Btree object written here */
52906  int flags,              /* Options */
52907  int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
52908){
52909  BtShared *pBt = 0;             /* Shared part of btree structure */
52910  Btree *p;                      /* Handle to return */
52911  sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
52912  int rc = SQLITE_OK;            /* Result code from this function */
52913  u8 nReserve;                   /* Byte of unused space on each page */
52914  unsigned char zDbHeader[100];  /* Database header content */
52915
52916  /* True if opening an ephemeral, temporary database */
52917  const int isTempDb = zFilename==0 || zFilename[0]==0;
52918
52919  /* Set the variable isMemdb to true for an in-memory database, or
52920  ** false for a file-based database.
52921  */
52922#ifdef SQLITE_OMIT_MEMORYDB
52923  const int isMemdb = 0;
52924#else
52925  const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
52926                       || (isTempDb && sqlite3TempInMemory(db))
52927                       || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
52928#endif
52929
52930  assert( db!=0 );
52931  assert( pVfs!=0 );
52932  assert( sqlite3_mutex_held(db->mutex) );
52933  assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
52934
52935  /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
52936  assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
52937
52938  /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
52939  assert( (flags & BTREE_SINGLE)==0 || isTempDb );
52940
52941  if( isMemdb ){
52942    flags |= BTREE_MEMORY;
52943  }
52944  if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
52945    vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
52946  }
52947  p = sqlite3MallocZero(sizeof(Btree));
52948  if( !p ){
52949    return SQLITE_NOMEM;
52950  }
52951  p->inTrans = TRANS_NONE;
52952  p->db = db;
52953#ifndef SQLITE_OMIT_SHARED_CACHE
52954  p->lock.pBtree = p;
52955  p->lock.iTable = 1;
52956#endif
52957
52958#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
52959  /*
52960  ** If this Btree is a candidate for shared cache, try to find an
52961  ** existing BtShared object that we can share with
52962  */
52963  if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
52964    if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
52965      int nFullPathname = pVfs->mxPathname+1;
52966      char *zFullPathname = sqlite3Malloc(nFullPathname);
52967      MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
52968      p->sharable = 1;
52969      if( !zFullPathname ){
52970        sqlite3_free(p);
52971        return SQLITE_NOMEM;
52972      }
52973      if( isMemdb ){
52974        memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);
52975      }else{
52976        rc = sqlite3OsFullPathname(pVfs, zFilename,
52977                                   nFullPathname, zFullPathname);
52978        if( rc ){
52979          sqlite3_free(zFullPathname);
52980          sqlite3_free(p);
52981          return rc;
52982        }
52983      }
52984#if SQLITE_THREADSAFE
52985      mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
52986      sqlite3_mutex_enter(mutexOpen);
52987      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
52988      sqlite3_mutex_enter(mutexShared);
52989#endif
52990      for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
52991        assert( pBt->nRef>0 );
52992        if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
52993                 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
52994          int iDb;
52995          for(iDb=db->nDb-1; iDb>=0; iDb--){
52996            Btree *pExisting = db->aDb[iDb].pBt;
52997            if( pExisting && pExisting->pBt==pBt ){
52998              sqlite3_mutex_leave(mutexShared);
52999              sqlite3_mutex_leave(mutexOpen);
53000              sqlite3_free(zFullPathname);
53001              sqlite3_free(p);
53002              return SQLITE_CONSTRAINT;
53003            }
53004          }
53005          p->pBt = pBt;
53006          pBt->nRef++;
53007          break;
53008        }
53009      }
53010      sqlite3_mutex_leave(mutexShared);
53011      sqlite3_free(zFullPathname);
53012    }
53013#ifdef SQLITE_DEBUG
53014    else{
53015      /* In debug mode, we mark all persistent databases as sharable
53016      ** even when they are not.  This exercises the locking code and
53017      ** gives more opportunity for asserts(sqlite3_mutex_held())
53018      ** statements to find locking problems.
53019      */
53020      p->sharable = 1;
53021    }
53022#endif
53023  }
53024#endif
53025  if( pBt==0 ){
53026    /*
53027    ** The following asserts make sure that structures used by the btree are
53028    ** the right size.  This is to guard against size changes that result
53029    ** when compiling on a different architecture.
53030    */
53031    assert( sizeof(i64)==8 || sizeof(i64)==4 );
53032    assert( sizeof(u64)==8 || sizeof(u64)==4 );
53033    assert( sizeof(u32)==4 );
53034    assert( sizeof(u16)==2 );
53035    assert( sizeof(Pgno)==4 );
53036
53037    pBt = sqlite3MallocZero( sizeof(*pBt) );
53038    if( pBt==0 ){
53039      rc = SQLITE_NOMEM;
53040      goto btree_open_out;
53041    }
53042    rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
53043                          EXTRA_SIZE, flags, vfsFlags, pageReinit);
53044    if( rc==SQLITE_OK ){
53045      sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
53046      rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
53047    }
53048    if( rc!=SQLITE_OK ){
53049      goto btree_open_out;
53050    }
53051    pBt->openFlags = (u8)flags;
53052    pBt->db = db;
53053    sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
53054    p->pBt = pBt;
53055
53056    pBt->pCursor = 0;
53057    pBt->pPage1 = 0;
53058    if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
53059#ifdef SQLITE_SECURE_DELETE
53060    pBt->btsFlags |= BTS_SECURE_DELETE;
53061#endif
53062    pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
53063    if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
53064         || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
53065      pBt->pageSize = 0;
53066#ifndef SQLITE_OMIT_AUTOVACUUM
53067      /* If the magic name ":memory:" will create an in-memory database, then
53068      ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
53069      ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
53070      ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
53071      ** regular file-name. In this case the auto-vacuum applies as per normal.
53072      */
53073      if( zFilename && !isMemdb ){
53074        pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
53075        pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
53076      }
53077#endif
53078      nReserve = 0;
53079    }else{
53080      nReserve = zDbHeader[20];
53081      pBt->btsFlags |= BTS_PAGESIZE_FIXED;
53082#ifndef SQLITE_OMIT_AUTOVACUUM
53083      pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
53084      pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
53085#endif
53086    }
53087    rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
53088    if( rc ) goto btree_open_out;
53089    pBt->usableSize = pBt->pageSize - nReserve;
53090    assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
53091
53092#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
53093    /* Add the new BtShared object to the linked list sharable BtShareds.
53094    */
53095    if( p->sharable ){
53096      MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
53097      pBt->nRef = 1;
53098      MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
53099      if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
53100        pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
53101        if( pBt->mutex==0 ){
53102          rc = SQLITE_NOMEM;
53103          db->mallocFailed = 0;
53104          goto btree_open_out;
53105        }
53106      }
53107      sqlite3_mutex_enter(mutexShared);
53108      pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
53109      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
53110      sqlite3_mutex_leave(mutexShared);
53111    }
53112#endif
53113  }
53114
53115#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
53116  /* If the new Btree uses a sharable pBtShared, then link the new
53117  ** Btree into the list of all sharable Btrees for the same connection.
53118  ** The list is kept in ascending order by pBt address.
53119  */
53120  if( p->sharable ){
53121    int i;
53122    Btree *pSib;
53123    for(i=0; i<db->nDb; i++){
53124      if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
53125        while( pSib->pPrev ){ pSib = pSib->pPrev; }
53126        if( p->pBt<pSib->pBt ){
53127          p->pNext = pSib;
53128          p->pPrev = 0;
53129          pSib->pPrev = p;
53130        }else{
53131          while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
53132            pSib = pSib->pNext;
53133          }
53134          p->pNext = pSib->pNext;
53135          p->pPrev = pSib;
53136          if( p->pNext ){
53137            p->pNext->pPrev = p;
53138          }
53139          pSib->pNext = p;
53140        }
53141        break;
53142      }
53143    }
53144  }
53145#endif
53146  *ppBtree = p;
53147
53148btree_open_out:
53149  if( rc!=SQLITE_OK ){
53150    if( pBt && pBt->pPager ){
53151      sqlite3PagerClose(pBt->pPager);
53152    }
53153    sqlite3_free(pBt);
53154    sqlite3_free(p);
53155    *ppBtree = 0;
53156  }else{
53157    /* If the B-Tree was successfully opened, set the pager-cache size to the
53158    ** default value. Except, when opening on an existing shared pager-cache,
53159    ** do not change the pager-cache size.
53160    */
53161    if( sqlite3BtreeSchema(p, 0, 0)==0 ){
53162      sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
53163    }
53164  }
53165  if( mutexOpen ){
53166    assert( sqlite3_mutex_held(mutexOpen) );
53167    sqlite3_mutex_leave(mutexOpen);
53168  }
53169  return rc;
53170}
53171
53172/*
53173** Decrement the BtShared.nRef counter.  When it reaches zero,
53174** remove the BtShared structure from the sharing list.  Return
53175** true if the BtShared.nRef counter reaches zero and return
53176** false if it is still positive.
53177*/
53178static int removeFromSharingList(BtShared *pBt){
53179#ifndef SQLITE_OMIT_SHARED_CACHE
53180  MUTEX_LOGIC( sqlite3_mutex *pMaster; )
53181  BtShared *pList;
53182  int removed = 0;
53183
53184  assert( sqlite3_mutex_notheld(pBt->mutex) );
53185  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
53186  sqlite3_mutex_enter(pMaster);
53187  pBt->nRef--;
53188  if( pBt->nRef<=0 ){
53189    if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
53190      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
53191    }else{
53192      pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
53193      while( ALWAYS(pList) && pList->pNext!=pBt ){
53194        pList=pList->pNext;
53195      }
53196      if( ALWAYS(pList) ){
53197        pList->pNext = pBt->pNext;
53198      }
53199    }
53200    if( SQLITE_THREADSAFE ){
53201      sqlite3_mutex_free(pBt->mutex);
53202    }
53203    removed = 1;
53204  }
53205  sqlite3_mutex_leave(pMaster);
53206  return removed;
53207#else
53208  return 1;
53209#endif
53210}
53211
53212/*
53213** Make sure pBt->pTmpSpace points to an allocation of
53214** MX_CELL_SIZE(pBt) bytes.
53215*/
53216static void allocateTempSpace(BtShared *pBt){
53217  if( !pBt->pTmpSpace ){
53218    pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
53219
53220    /* One of the uses of pBt->pTmpSpace is to format cells before
53221    ** inserting them into a leaf page (function fillInCell()). If
53222    ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
53223    ** by the various routines that manipulate binary cells. Which
53224    ** can mean that fillInCell() only initializes the first 2 or 3
53225    ** bytes of pTmpSpace, but that the first 4 bytes are copied from
53226    ** it into a database page. This is not actually a problem, but it
53227    ** does cause a valgrind error when the 1 or 2 bytes of unitialized
53228    ** data is passed to system call write(). So to avoid this error,
53229    ** zero the first 4 bytes of temp space here.  */
53230    if( pBt->pTmpSpace ) memset(pBt->pTmpSpace, 0, 4);
53231  }
53232}
53233
53234/*
53235** Free the pBt->pTmpSpace allocation
53236*/
53237static void freeTempSpace(BtShared *pBt){
53238  sqlite3PageFree( pBt->pTmpSpace);
53239  pBt->pTmpSpace = 0;
53240}
53241
53242/*
53243** Close an open database and invalidate all cursors.
53244*/
53245SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
53246  BtShared *pBt = p->pBt;
53247  BtCursor *pCur;
53248
53249  /* Close all cursors opened via this handle.  */
53250  assert( sqlite3_mutex_held(p->db->mutex) );
53251  sqlite3BtreeEnter(p);
53252  pCur = pBt->pCursor;
53253  while( pCur ){
53254    BtCursor *pTmp = pCur;
53255    pCur = pCur->pNext;
53256    if( pTmp->pBtree==p ){
53257      sqlite3BtreeCloseCursor(pTmp);
53258    }
53259  }
53260
53261  /* Rollback any active transaction and free the handle structure.
53262  ** The call to sqlite3BtreeRollback() drops any table-locks held by
53263  ** this handle.
53264  */
53265  sqlite3BtreeRollback(p, SQLITE_OK);
53266  sqlite3BtreeLeave(p);
53267
53268  /* If there are still other outstanding references to the shared-btree
53269  ** structure, return now. The remainder of this procedure cleans
53270  ** up the shared-btree.
53271  */
53272  assert( p->wantToLock==0 && p->locked==0 );
53273  if( !p->sharable || removeFromSharingList(pBt) ){
53274    /* The pBt is no longer on the sharing list, so we can access
53275    ** it without having to hold the mutex.
53276    **
53277    ** Clean out and delete the BtShared object.
53278    */
53279    assert( !pBt->pCursor );
53280    sqlite3PagerClose(pBt->pPager);
53281    if( pBt->xFreeSchema && pBt->pSchema ){
53282      pBt->xFreeSchema(pBt->pSchema);
53283    }
53284    sqlite3DbFree(0, pBt->pSchema);
53285    freeTempSpace(pBt);
53286    sqlite3_free(pBt);
53287  }
53288
53289#ifndef SQLITE_OMIT_SHARED_CACHE
53290  assert( p->wantToLock==0 );
53291  assert( p->locked==0 );
53292  if( p->pPrev ) p->pPrev->pNext = p->pNext;
53293  if( p->pNext ) p->pNext->pPrev = p->pPrev;
53294#endif
53295
53296  sqlite3_free(p);
53297  return SQLITE_OK;
53298}
53299
53300/*
53301** Change the limit on the number of pages allowed in the cache.
53302**
53303** The maximum number of cache pages is set to the absolute
53304** value of mxPage.  If mxPage is negative, the pager will
53305** operate asynchronously - it will not stop to do fsync()s
53306** to insure data is written to the disk surface before
53307** continuing.  Transactions still work if synchronous is off,
53308** and the database cannot be corrupted if this program
53309** crashes.  But if the operating system crashes or there is
53310** an abrupt power failure when synchronous is off, the database
53311** could be left in an inconsistent and unrecoverable state.
53312** Synchronous is on by default so database corruption is not
53313** normally a worry.
53314*/
53315SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
53316  BtShared *pBt = p->pBt;
53317  assert( sqlite3_mutex_held(p->db->mutex) );
53318  sqlite3BtreeEnter(p);
53319  sqlite3PagerSetCachesize(pBt->pPager, mxPage);
53320  sqlite3BtreeLeave(p);
53321  return SQLITE_OK;
53322}
53323
53324#if SQLITE_MAX_MMAP_SIZE>0
53325/*
53326** Change the limit on the amount of the database file that may be
53327** memory mapped.
53328*/
53329SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
53330  BtShared *pBt = p->pBt;
53331  assert( sqlite3_mutex_held(p->db->mutex) );
53332  sqlite3BtreeEnter(p);
53333  sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
53334  sqlite3BtreeLeave(p);
53335  return SQLITE_OK;
53336}
53337#endif /* SQLITE_MAX_MMAP_SIZE>0 */
53338
53339/*
53340** Change the way data is synced to disk in order to increase or decrease
53341** how well the database resists damage due to OS crashes and power
53342** failures.  Level 1 is the same as asynchronous (no syncs() occur and
53343** there is a high probability of damage)  Level 2 is the default.  There
53344** is a very low but non-zero probability of damage.  Level 3 reduces the
53345** probability of damage to near zero but with a write performance reduction.
53346*/
53347#ifndef SQLITE_OMIT_PAGER_PRAGMAS
53348SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
53349  Btree *p,              /* The btree to set the safety level on */
53350  unsigned pgFlags       /* Various PAGER_* flags */
53351){
53352  BtShared *pBt = p->pBt;
53353  assert( sqlite3_mutex_held(p->db->mutex) );
53354  sqlite3BtreeEnter(p);
53355  sqlite3PagerSetFlags(pBt->pPager, pgFlags);
53356  sqlite3BtreeLeave(p);
53357  return SQLITE_OK;
53358}
53359#endif
53360
53361/*
53362** Return TRUE if the given btree is set to safety level 1.  In other
53363** words, return TRUE if no sync() occurs on the disk files.
53364*/
53365SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
53366  BtShared *pBt = p->pBt;
53367  int rc;
53368  assert( sqlite3_mutex_held(p->db->mutex) );
53369  sqlite3BtreeEnter(p);
53370  assert( pBt && pBt->pPager );
53371  rc = sqlite3PagerNosync(pBt->pPager);
53372  sqlite3BtreeLeave(p);
53373  return rc;
53374}
53375
53376/*
53377** Change the default pages size and the number of reserved bytes per page.
53378** Or, if the page size has already been fixed, return SQLITE_READONLY
53379** without changing anything.
53380**
53381** The page size must be a power of 2 between 512 and 65536.  If the page
53382** size supplied does not meet this constraint then the page size is not
53383** changed.
53384**
53385** Page sizes are constrained to be a power of two so that the region
53386** of the database file used for locking (beginning at PENDING_BYTE,
53387** the first byte past the 1GB boundary, 0x40000000) needs to occur
53388** at the beginning of a page.
53389**
53390** If parameter nReserve is less than zero, then the number of reserved
53391** bytes per page is left unchanged.
53392**
53393** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
53394** and autovacuum mode can no longer be changed.
53395*/
53396SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
53397  int rc = SQLITE_OK;
53398  BtShared *pBt = p->pBt;
53399  assert( nReserve>=-1 && nReserve<=255 );
53400  sqlite3BtreeEnter(p);
53401  if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
53402    sqlite3BtreeLeave(p);
53403    return SQLITE_READONLY;
53404  }
53405  if( nReserve<0 ){
53406    nReserve = pBt->pageSize - pBt->usableSize;
53407  }
53408  assert( nReserve>=0 && nReserve<=255 );
53409  if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
53410        ((pageSize-1)&pageSize)==0 ){
53411    assert( (pageSize & 7)==0 );
53412    assert( !pBt->pPage1 && !pBt->pCursor );
53413    pBt->pageSize = (u32)pageSize;
53414    freeTempSpace(pBt);
53415  }
53416  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
53417  pBt->usableSize = pBt->pageSize - (u16)nReserve;
53418  if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
53419  sqlite3BtreeLeave(p);
53420  return rc;
53421}
53422
53423/*
53424** Return the currently defined page size
53425*/
53426SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
53427  return p->pBt->pageSize;
53428}
53429
53430#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
53431/*
53432** This function is similar to sqlite3BtreeGetReserve(), except that it
53433** may only be called if it is guaranteed that the b-tree mutex is already
53434** held.
53435**
53436** This is useful in one special case in the backup API code where it is
53437** known that the shared b-tree mutex is held, but the mutex on the
53438** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
53439** were to be called, it might collide with some other operation on the
53440** database handle that owns *p, causing undefined behavior.
53441*/
53442SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
53443  assert( sqlite3_mutex_held(p->pBt->mutex) );
53444  return p->pBt->pageSize - p->pBt->usableSize;
53445}
53446#endif /* SQLITE_HAS_CODEC || SQLITE_DEBUG */
53447
53448#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
53449/*
53450** Return the number of bytes of space at the end of every page that
53451** are intentually left unused.  This is the "reserved" space that is
53452** sometimes used by extensions.
53453*/
53454SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
53455  int n;
53456  sqlite3BtreeEnter(p);
53457  n = p->pBt->pageSize - p->pBt->usableSize;
53458  sqlite3BtreeLeave(p);
53459  return n;
53460}
53461
53462/*
53463** Set the maximum page count for a database if mxPage is positive.
53464** No changes are made if mxPage is 0 or negative.
53465** Regardless of the value of mxPage, return the maximum page count.
53466*/
53467SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
53468  int n;
53469  sqlite3BtreeEnter(p);
53470  n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
53471  sqlite3BtreeLeave(p);
53472  return n;
53473}
53474
53475/*
53476** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1.  If newFlag is -1,
53477** then make no changes.  Always return the value of the BTS_SECURE_DELETE
53478** setting after the change.
53479*/
53480SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
53481  int b;
53482  if( p==0 ) return 0;
53483  sqlite3BtreeEnter(p);
53484  if( newFlag>=0 ){
53485    p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
53486    if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
53487  }
53488  b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
53489  sqlite3BtreeLeave(p);
53490  return b;
53491}
53492#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
53493
53494/*
53495** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
53496** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
53497** is disabled. The default value for the auto-vacuum property is
53498** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
53499*/
53500SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
53501#ifdef SQLITE_OMIT_AUTOVACUUM
53502  return SQLITE_READONLY;
53503#else
53504  BtShared *pBt = p->pBt;
53505  int rc = SQLITE_OK;
53506  u8 av = (u8)autoVacuum;
53507
53508  sqlite3BtreeEnter(p);
53509  if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
53510    rc = SQLITE_READONLY;
53511  }else{
53512    pBt->autoVacuum = av ?1:0;
53513    pBt->incrVacuum = av==2 ?1:0;
53514  }
53515  sqlite3BtreeLeave(p);
53516  return rc;
53517#endif
53518}
53519
53520/*
53521** Return the value of the 'auto-vacuum' property. If auto-vacuum is
53522** enabled 1 is returned. Otherwise 0.
53523*/
53524SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
53525#ifdef SQLITE_OMIT_AUTOVACUUM
53526  return BTREE_AUTOVACUUM_NONE;
53527#else
53528  int rc;
53529  sqlite3BtreeEnter(p);
53530  rc = (
53531    (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
53532    (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
53533    BTREE_AUTOVACUUM_INCR
53534  );
53535  sqlite3BtreeLeave(p);
53536  return rc;
53537#endif
53538}
53539
53540
53541/*
53542** Get a reference to pPage1 of the database file.  This will
53543** also acquire a readlock on that file.
53544**
53545** SQLITE_OK is returned on success.  If the file is not a
53546** well-formed database file, then SQLITE_CORRUPT is returned.
53547** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
53548** is returned if we run out of memory.
53549*/
53550static int lockBtree(BtShared *pBt){
53551  int rc;              /* Result code from subfunctions */
53552  MemPage *pPage1;     /* Page 1 of the database file */
53553  int nPage;           /* Number of pages in the database */
53554  int nPageFile = 0;   /* Number of pages in the database file */
53555  int nPageHeader;     /* Number of pages in the database according to hdr */
53556
53557  assert( sqlite3_mutex_held(pBt->mutex) );
53558  assert( pBt->pPage1==0 );
53559  rc = sqlite3PagerSharedLock(pBt->pPager);
53560  if( rc!=SQLITE_OK ) return rc;
53561  rc = btreeGetPage(pBt, 1, &pPage1, 0);
53562  if( rc!=SQLITE_OK ) return rc;
53563
53564  /* Do some checking to help insure the file we opened really is
53565  ** a valid database file.
53566  */
53567  nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
53568  sqlite3PagerPagecount(pBt->pPager, &nPageFile);
53569  if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
53570    nPage = nPageFile;
53571  }
53572  if( nPage>0 ){
53573    u32 pageSize;
53574    u32 usableSize;
53575    u8 *page1 = pPage1->aData;
53576    rc = SQLITE_NOTADB;
53577    if( memcmp(page1, zMagicHeader, 16)!=0 ){
53578      goto page1_init_failed;
53579    }
53580
53581#ifdef SQLITE_OMIT_WAL
53582    if( page1[18]>1 ){
53583      pBt->btsFlags |= BTS_READ_ONLY;
53584    }
53585    if( page1[19]>1 ){
53586      goto page1_init_failed;
53587    }
53588#else
53589    if( page1[18]>2 ){
53590      pBt->btsFlags |= BTS_READ_ONLY;
53591    }
53592    if( page1[19]>2 ){
53593      goto page1_init_failed;
53594    }
53595
53596    /* If the write version is set to 2, this database should be accessed
53597    ** in WAL mode. If the log is not already open, open it now. Then
53598    ** return SQLITE_OK and return without populating BtShared.pPage1.
53599    ** The caller detects this and calls this function again. This is
53600    ** required as the version of page 1 currently in the page1 buffer
53601    ** may not be the latest version - there may be a newer one in the log
53602    ** file.
53603    */
53604    if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
53605      int isOpen = 0;
53606      rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
53607      if( rc!=SQLITE_OK ){
53608        goto page1_init_failed;
53609      }else if( isOpen==0 ){
53610        releasePage(pPage1);
53611        return SQLITE_OK;
53612      }
53613      rc = SQLITE_NOTADB;
53614    }
53615#endif
53616
53617    /* The maximum embedded fraction must be exactly 25%.  And the minimum
53618    ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
53619    ** The original design allowed these amounts to vary, but as of
53620    ** version 3.6.0, we require them to be fixed.
53621    */
53622    if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
53623      goto page1_init_failed;
53624    }
53625    pageSize = (page1[16]<<8) | (page1[17]<<16);
53626    if( ((pageSize-1)&pageSize)!=0
53627     || pageSize>SQLITE_MAX_PAGE_SIZE
53628     || pageSize<=256
53629    ){
53630      goto page1_init_failed;
53631    }
53632    assert( (pageSize & 7)==0 );
53633    usableSize = pageSize - page1[20];
53634    if( (u32)pageSize!=pBt->pageSize ){
53635      /* After reading the first page of the database assuming a page size
53636      ** of BtShared.pageSize, we have discovered that the page-size is
53637      ** actually pageSize. Unlock the database, leave pBt->pPage1 at
53638      ** zero and return SQLITE_OK. The caller will call this function
53639      ** again with the correct page-size.
53640      */
53641      releasePage(pPage1);
53642      pBt->usableSize = usableSize;
53643      pBt->pageSize = pageSize;
53644      freeTempSpace(pBt);
53645      rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
53646                                   pageSize-usableSize);
53647      return rc;
53648    }
53649    if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
53650      rc = SQLITE_CORRUPT_BKPT;
53651      goto page1_init_failed;
53652    }
53653    if( usableSize<480 ){
53654      goto page1_init_failed;
53655    }
53656    pBt->pageSize = pageSize;
53657    pBt->usableSize = usableSize;
53658#ifndef SQLITE_OMIT_AUTOVACUUM
53659    pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
53660    pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
53661#endif
53662  }
53663
53664  /* maxLocal is the maximum amount of payload to store locally for
53665  ** a cell.  Make sure it is small enough so that at least minFanout
53666  ** cells can will fit on one page.  We assume a 10-byte page header.
53667  ** Besides the payload, the cell must store:
53668  **     2-byte pointer to the cell
53669  **     4-byte child pointer
53670  **     9-byte nKey value
53671  **     4-byte nData value
53672  **     4-byte overflow page pointer
53673  ** So a cell consists of a 2-byte pointer, a header which is as much as
53674  ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
53675  ** page pointer.
53676  */
53677  pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
53678  pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
53679  pBt->maxLeaf = (u16)(pBt->usableSize - 35);
53680  pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
53681  if( pBt->maxLocal>127 ){
53682    pBt->max1bytePayload = 127;
53683  }else{
53684    pBt->max1bytePayload = (u8)pBt->maxLocal;
53685  }
53686  assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
53687  pBt->pPage1 = pPage1;
53688  pBt->nPage = nPage;
53689  return SQLITE_OK;
53690
53691page1_init_failed:
53692  releasePage(pPage1);
53693  pBt->pPage1 = 0;
53694  return rc;
53695}
53696
53697#ifndef NDEBUG
53698/*
53699** Return the number of cursors open on pBt. This is for use
53700** in assert() expressions, so it is only compiled if NDEBUG is not
53701** defined.
53702**
53703** Only write cursors are counted if wrOnly is true.  If wrOnly is
53704** false then all cursors are counted.
53705**
53706** For the purposes of this routine, a cursor is any cursor that
53707** is capable of reading or writing to the databse.  Cursors that
53708** have been tripped into the CURSOR_FAULT state are not counted.
53709*/
53710static int countValidCursors(BtShared *pBt, int wrOnly){
53711  BtCursor *pCur;
53712  int r = 0;
53713  for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
53714    if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
53715     && pCur->eState!=CURSOR_FAULT ) r++;
53716  }
53717  return r;
53718}
53719#endif
53720
53721/*
53722** If there are no outstanding cursors and we are not in the middle
53723** of a transaction but there is a read lock on the database, then
53724** this routine unrefs the first page of the database file which
53725** has the effect of releasing the read lock.
53726**
53727** If there is a transaction in progress, this routine is a no-op.
53728*/
53729static void unlockBtreeIfUnused(BtShared *pBt){
53730  assert( sqlite3_mutex_held(pBt->mutex) );
53731  assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
53732  if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
53733    assert( pBt->pPage1->aData );
53734    assert( sqlite3PagerRefcount(pBt->pPager)==1 );
53735    assert( pBt->pPage1->aData );
53736    releasePage(pBt->pPage1);
53737    pBt->pPage1 = 0;
53738  }
53739}
53740
53741/*
53742** If pBt points to an empty file then convert that empty file
53743** into a new empty database by initializing the first page of
53744** the database.
53745*/
53746static int newDatabase(BtShared *pBt){
53747  MemPage *pP1;
53748  unsigned char *data;
53749  int rc;
53750
53751  assert( sqlite3_mutex_held(pBt->mutex) );
53752  if( pBt->nPage>0 ){
53753    return SQLITE_OK;
53754  }
53755  pP1 = pBt->pPage1;
53756  assert( pP1!=0 );
53757  data = pP1->aData;
53758  rc = sqlite3PagerWrite(pP1->pDbPage);
53759  if( rc ) return rc;
53760  memcpy(data, zMagicHeader, sizeof(zMagicHeader));
53761  assert( sizeof(zMagicHeader)==16 );
53762  data[16] = (u8)((pBt->pageSize>>8)&0xff);
53763  data[17] = (u8)((pBt->pageSize>>16)&0xff);
53764  data[18] = 1;
53765  data[19] = 1;
53766  assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
53767  data[20] = (u8)(pBt->pageSize - pBt->usableSize);
53768  data[21] = 64;
53769  data[22] = 32;
53770  data[23] = 32;
53771  memset(&data[24], 0, 100-24);
53772  zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
53773  pBt->btsFlags |= BTS_PAGESIZE_FIXED;
53774#ifndef SQLITE_OMIT_AUTOVACUUM
53775  assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
53776  assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
53777  put4byte(&data[36 + 4*4], pBt->autoVacuum);
53778  put4byte(&data[36 + 7*4], pBt->incrVacuum);
53779#endif
53780  pBt->nPage = 1;
53781  data[31] = 1;
53782  return SQLITE_OK;
53783}
53784
53785/*
53786** Initialize the first page of the database file (creating a database
53787** consisting of a single page and no schema objects). Return SQLITE_OK
53788** if successful, or an SQLite error code otherwise.
53789*/
53790SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
53791  int rc;
53792  sqlite3BtreeEnter(p);
53793  p->pBt->nPage = 0;
53794  rc = newDatabase(p->pBt);
53795  sqlite3BtreeLeave(p);
53796  return rc;
53797}
53798
53799/*
53800** Attempt to start a new transaction. A write-transaction
53801** is started if the second argument is nonzero, otherwise a read-
53802** transaction.  If the second argument is 2 or more and exclusive
53803** transaction is started, meaning that no other process is allowed
53804** to access the database.  A preexisting transaction may not be
53805** upgraded to exclusive by calling this routine a second time - the
53806** exclusivity flag only works for a new transaction.
53807**
53808** A write-transaction must be started before attempting any
53809** changes to the database.  None of the following routines
53810** will work unless a transaction is started first:
53811**
53812**      sqlite3BtreeCreateTable()
53813**      sqlite3BtreeCreateIndex()
53814**      sqlite3BtreeClearTable()
53815**      sqlite3BtreeDropTable()
53816**      sqlite3BtreeInsert()
53817**      sqlite3BtreeDelete()
53818**      sqlite3BtreeUpdateMeta()
53819**
53820** If an initial attempt to acquire the lock fails because of lock contention
53821** and the database was previously unlocked, then invoke the busy handler
53822** if there is one.  But if there was previously a read-lock, do not
53823** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
53824** returned when there is already a read-lock in order to avoid a deadlock.
53825**
53826** Suppose there are two processes A and B.  A has a read lock and B has
53827** a reserved lock.  B tries to promote to exclusive but is blocked because
53828** of A's read lock.  A tries to promote to reserved but is blocked by B.
53829** One or the other of the two processes must give way or there can be
53830** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
53831** when A already has a read lock, we encourage A to give up and let B
53832** proceed.
53833*/
53834SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
53835  sqlite3 *pBlock = 0;
53836  BtShared *pBt = p->pBt;
53837  int rc = SQLITE_OK;
53838
53839  sqlite3BtreeEnter(p);
53840  btreeIntegrity(p);
53841
53842  /* If the btree is already in a write-transaction, or it
53843  ** is already in a read-transaction and a read-transaction
53844  ** is requested, this is a no-op.
53845  */
53846  if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
53847    goto trans_begun;
53848  }
53849  assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
53850
53851  /* Write transactions are not possible on a read-only database */
53852  if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
53853    rc = SQLITE_READONLY;
53854    goto trans_begun;
53855  }
53856
53857#ifndef SQLITE_OMIT_SHARED_CACHE
53858  /* If another database handle has already opened a write transaction
53859  ** on this shared-btree structure and a second write transaction is
53860  ** requested, return SQLITE_LOCKED.
53861  */
53862  if( (wrflag && pBt->inTransaction==TRANS_WRITE)
53863   || (pBt->btsFlags & BTS_PENDING)!=0
53864  ){
53865    pBlock = pBt->pWriter->db;
53866  }else if( wrflag>1 ){
53867    BtLock *pIter;
53868    for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
53869      if( pIter->pBtree!=p ){
53870        pBlock = pIter->pBtree->db;
53871        break;
53872      }
53873    }
53874  }
53875  if( pBlock ){
53876    sqlite3ConnectionBlocked(p->db, pBlock);
53877    rc = SQLITE_LOCKED_SHAREDCACHE;
53878    goto trans_begun;
53879  }
53880#endif
53881
53882  /* Any read-only or read-write transaction implies a read-lock on
53883  ** page 1. So if some other shared-cache client already has a write-lock
53884  ** on page 1, the transaction cannot be opened. */
53885  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
53886  if( SQLITE_OK!=rc ) goto trans_begun;
53887
53888  pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
53889  if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
53890  do {
53891    /* Call lockBtree() until either pBt->pPage1 is populated or
53892    ** lockBtree() returns something other than SQLITE_OK. lockBtree()
53893    ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
53894    ** reading page 1 it discovers that the page-size of the database
53895    ** file is not pBt->pageSize. In this case lockBtree() will update
53896    ** pBt->pageSize to the page-size of the file on disk.
53897    */
53898    while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
53899
53900    if( rc==SQLITE_OK && wrflag ){
53901      if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
53902        rc = SQLITE_READONLY;
53903      }else{
53904        rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
53905        if( rc==SQLITE_OK ){
53906          rc = newDatabase(pBt);
53907        }
53908      }
53909    }
53910
53911    if( rc!=SQLITE_OK ){
53912      unlockBtreeIfUnused(pBt);
53913    }
53914  }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
53915          btreeInvokeBusyHandler(pBt) );
53916
53917  if( rc==SQLITE_OK ){
53918    if( p->inTrans==TRANS_NONE ){
53919      pBt->nTransaction++;
53920#ifndef SQLITE_OMIT_SHARED_CACHE
53921      if( p->sharable ){
53922        assert( p->lock.pBtree==p && p->lock.iTable==1 );
53923        p->lock.eLock = READ_LOCK;
53924        p->lock.pNext = pBt->pLock;
53925        pBt->pLock = &p->lock;
53926      }
53927#endif
53928    }
53929    p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
53930    if( p->inTrans>pBt->inTransaction ){
53931      pBt->inTransaction = p->inTrans;
53932    }
53933    if( wrflag ){
53934      MemPage *pPage1 = pBt->pPage1;
53935#ifndef SQLITE_OMIT_SHARED_CACHE
53936      assert( !pBt->pWriter );
53937      pBt->pWriter = p;
53938      pBt->btsFlags &= ~BTS_EXCLUSIVE;
53939      if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
53940#endif
53941
53942      /* If the db-size header field is incorrect (as it may be if an old
53943      ** client has been writing the database file), update it now. Doing
53944      ** this sooner rather than later means the database size can safely
53945      ** re-read the database size from page 1 if a savepoint or transaction
53946      ** rollback occurs within the transaction.
53947      */
53948      if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
53949        rc = sqlite3PagerWrite(pPage1->pDbPage);
53950        if( rc==SQLITE_OK ){
53951          put4byte(&pPage1->aData[28], pBt->nPage);
53952        }
53953      }
53954    }
53955  }
53956
53957
53958trans_begun:
53959  if( rc==SQLITE_OK && wrflag ){
53960    /* This call makes sure that the pager has the correct number of
53961    ** open savepoints. If the second parameter is greater than 0 and
53962    ** the sub-journal is not already open, then it will be opened here.
53963    */
53964    rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
53965  }
53966
53967  btreeIntegrity(p);
53968  sqlite3BtreeLeave(p);
53969  return rc;
53970}
53971
53972#ifndef SQLITE_OMIT_AUTOVACUUM
53973
53974/*
53975** Set the pointer-map entries for all children of page pPage. Also, if
53976** pPage contains cells that point to overflow pages, set the pointer
53977** map entries for the overflow pages as well.
53978*/
53979static int setChildPtrmaps(MemPage *pPage){
53980  int i;                             /* Counter variable */
53981  int nCell;                         /* Number of cells in page pPage */
53982  int rc;                            /* Return code */
53983  BtShared *pBt = pPage->pBt;
53984  u8 isInitOrig = pPage->isInit;
53985  Pgno pgno = pPage->pgno;
53986
53987  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53988  rc = btreeInitPage(pPage);
53989  if( rc!=SQLITE_OK ){
53990    goto set_child_ptrmaps_out;
53991  }
53992  nCell = pPage->nCell;
53993
53994  for(i=0; i<nCell; i++){
53995    u8 *pCell = findCell(pPage, i);
53996
53997    ptrmapPutOvflPtr(pPage, pCell, &rc);
53998
53999    if( !pPage->leaf ){
54000      Pgno childPgno = get4byte(pCell);
54001      ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
54002    }
54003  }
54004
54005  if( !pPage->leaf ){
54006    Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
54007    ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
54008  }
54009
54010set_child_ptrmaps_out:
54011  pPage->isInit = isInitOrig;
54012  return rc;
54013}
54014
54015/*
54016** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
54017** that it points to iTo. Parameter eType describes the type of pointer to
54018** be modified, as  follows:
54019**
54020** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
54021**                   page of pPage.
54022**
54023** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
54024**                   page pointed to by one of the cells on pPage.
54025**
54026** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
54027**                   overflow page in the list.
54028*/
54029static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
54030  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54031  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
54032  if( eType==PTRMAP_OVERFLOW2 ){
54033    /* The pointer is always the first 4 bytes of the page in this case.  */
54034    if( get4byte(pPage->aData)!=iFrom ){
54035      return SQLITE_CORRUPT_BKPT;
54036    }
54037    put4byte(pPage->aData, iTo);
54038  }else{
54039    u8 isInitOrig = pPage->isInit;
54040    int i;
54041    int nCell;
54042
54043    btreeInitPage(pPage);
54044    nCell = pPage->nCell;
54045
54046    for(i=0; i<nCell; i++){
54047      u8 *pCell = findCell(pPage, i);
54048      if( eType==PTRMAP_OVERFLOW1 ){
54049        CellInfo info;
54050        btreeParseCellPtr(pPage, pCell, &info);
54051        if( info.iOverflow
54052         && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
54053         && iFrom==get4byte(&pCell[info.iOverflow])
54054        ){
54055          put4byte(&pCell[info.iOverflow], iTo);
54056          break;
54057        }
54058      }else{
54059        if( get4byte(pCell)==iFrom ){
54060          put4byte(pCell, iTo);
54061          break;
54062        }
54063      }
54064    }
54065
54066    if( i==nCell ){
54067      if( eType!=PTRMAP_BTREE ||
54068          get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
54069        return SQLITE_CORRUPT_BKPT;
54070      }
54071      put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
54072    }
54073
54074    pPage->isInit = isInitOrig;
54075  }
54076  return SQLITE_OK;
54077}
54078
54079
54080/*
54081** Move the open database page pDbPage to location iFreePage in the
54082** database. The pDbPage reference remains valid.
54083**
54084** The isCommit flag indicates that there is no need to remember that
54085** the journal needs to be sync()ed before database page pDbPage->pgno
54086** can be written to. The caller has already promised not to write to that
54087** page.
54088*/
54089static int relocatePage(
54090  BtShared *pBt,           /* Btree */
54091  MemPage *pDbPage,        /* Open page to move */
54092  u8 eType,                /* Pointer map 'type' entry for pDbPage */
54093  Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
54094  Pgno iFreePage,          /* The location to move pDbPage to */
54095  int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
54096){
54097  MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
54098  Pgno iDbPage = pDbPage->pgno;
54099  Pager *pPager = pBt->pPager;
54100  int rc;
54101
54102  assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
54103      eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
54104  assert( sqlite3_mutex_held(pBt->mutex) );
54105  assert( pDbPage->pBt==pBt );
54106
54107  /* Move page iDbPage from its current location to page number iFreePage */
54108  TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
54109      iDbPage, iFreePage, iPtrPage, eType));
54110  rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
54111  if( rc!=SQLITE_OK ){
54112    return rc;
54113  }
54114  pDbPage->pgno = iFreePage;
54115
54116  /* If pDbPage was a btree-page, then it may have child pages and/or cells
54117  ** that point to overflow pages. The pointer map entries for all these
54118  ** pages need to be changed.
54119  **
54120  ** If pDbPage is an overflow page, then the first 4 bytes may store a
54121  ** pointer to a subsequent overflow page. If this is the case, then
54122  ** the pointer map needs to be updated for the subsequent overflow page.
54123  */
54124  if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
54125    rc = setChildPtrmaps(pDbPage);
54126    if( rc!=SQLITE_OK ){
54127      return rc;
54128    }
54129  }else{
54130    Pgno nextOvfl = get4byte(pDbPage->aData);
54131    if( nextOvfl!=0 ){
54132      ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
54133      if( rc!=SQLITE_OK ){
54134        return rc;
54135      }
54136    }
54137  }
54138
54139  /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
54140  ** that it points at iFreePage. Also fix the pointer map entry for
54141  ** iPtrPage.
54142  */
54143  if( eType!=PTRMAP_ROOTPAGE ){
54144    rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
54145    if( rc!=SQLITE_OK ){
54146      return rc;
54147    }
54148    rc = sqlite3PagerWrite(pPtrPage->pDbPage);
54149    if( rc!=SQLITE_OK ){
54150      releasePage(pPtrPage);
54151      return rc;
54152    }
54153    rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
54154    releasePage(pPtrPage);
54155    if( rc==SQLITE_OK ){
54156      ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
54157    }
54158  }
54159  return rc;
54160}
54161
54162/* Forward declaration required by incrVacuumStep(). */
54163static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
54164
54165/*
54166** Perform a single step of an incremental-vacuum. If successful, return
54167** SQLITE_OK. If there is no work to do (and therefore no point in
54168** calling this function again), return SQLITE_DONE. Or, if an error
54169** occurs, return some other error code.
54170**
54171** More specificly, this function attempts to re-organize the database so
54172** that the last page of the file currently in use is no longer in use.
54173**
54174** Parameter nFin is the number of pages that this database would contain
54175** were this function called until it returns SQLITE_DONE.
54176**
54177** If the bCommit parameter is non-zero, this function assumes that the
54178** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
54179** or an error. bCommit is passed true for an auto-vacuum-on-commmit
54180** operation, or false for an incremental vacuum.
54181*/
54182static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
54183  Pgno nFreeList;           /* Number of pages still on the free-list */
54184  int rc;
54185
54186  assert( sqlite3_mutex_held(pBt->mutex) );
54187  assert( iLastPg>nFin );
54188
54189  if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
54190    u8 eType;
54191    Pgno iPtrPage;
54192
54193    nFreeList = get4byte(&pBt->pPage1->aData[36]);
54194    if( nFreeList==0 ){
54195      return SQLITE_DONE;
54196    }
54197
54198    rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
54199    if( rc!=SQLITE_OK ){
54200      return rc;
54201    }
54202    if( eType==PTRMAP_ROOTPAGE ){
54203      return SQLITE_CORRUPT_BKPT;
54204    }
54205
54206    if( eType==PTRMAP_FREEPAGE ){
54207      if( bCommit==0 ){
54208        /* Remove the page from the files free-list. This is not required
54209        ** if bCommit is non-zero. In that case, the free-list will be
54210        ** truncated to zero after this function returns, so it doesn't
54211        ** matter if it still contains some garbage entries.
54212        */
54213        Pgno iFreePg;
54214        MemPage *pFreePg;
54215        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
54216        if( rc!=SQLITE_OK ){
54217          return rc;
54218        }
54219        assert( iFreePg==iLastPg );
54220        releasePage(pFreePg);
54221      }
54222    } else {
54223      Pgno iFreePg;             /* Index of free page to move pLastPg to */
54224      MemPage *pLastPg;
54225      u8 eMode = BTALLOC_ANY;   /* Mode parameter for allocateBtreePage() */
54226      Pgno iNear = 0;           /* nearby parameter for allocateBtreePage() */
54227
54228      rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
54229      if( rc!=SQLITE_OK ){
54230        return rc;
54231      }
54232
54233      /* If bCommit is zero, this loop runs exactly once and page pLastPg
54234      ** is swapped with the first free page pulled off the free list.
54235      **
54236      ** On the other hand, if bCommit is greater than zero, then keep
54237      ** looping until a free-page located within the first nFin pages
54238      ** of the file is found.
54239      */
54240      if( bCommit==0 ){
54241        eMode = BTALLOC_LE;
54242        iNear = nFin;
54243      }
54244      do {
54245        MemPage *pFreePg;
54246        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
54247        if( rc!=SQLITE_OK ){
54248          releasePage(pLastPg);
54249          return rc;
54250        }
54251        releasePage(pFreePg);
54252      }while( bCommit && iFreePg>nFin );
54253      assert( iFreePg<iLastPg );
54254
54255      rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
54256      releasePage(pLastPg);
54257      if( rc!=SQLITE_OK ){
54258        return rc;
54259      }
54260    }
54261  }
54262
54263  if( bCommit==0 ){
54264    do {
54265      iLastPg--;
54266    }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
54267    pBt->bDoTruncate = 1;
54268    pBt->nPage = iLastPg;
54269  }
54270  return SQLITE_OK;
54271}
54272
54273/*
54274** The database opened by the first argument is an auto-vacuum database
54275** nOrig pages in size containing nFree free pages. Return the expected
54276** size of the database in pages following an auto-vacuum operation.
54277*/
54278static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
54279  int nEntry;                     /* Number of entries on one ptrmap page */
54280  Pgno nPtrmap;                   /* Number of PtrMap pages to be freed */
54281  Pgno nFin;                      /* Return value */
54282
54283  nEntry = pBt->usableSize/5;
54284  nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
54285  nFin = nOrig - nFree - nPtrmap;
54286  if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
54287    nFin--;
54288  }
54289  while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
54290    nFin--;
54291  }
54292
54293  return nFin;
54294}
54295
54296/*
54297** A write-transaction must be opened before calling this function.
54298** It performs a single unit of work towards an incremental vacuum.
54299**
54300** If the incremental vacuum is finished after this function has run,
54301** SQLITE_DONE is returned. If it is not finished, but no error occurred,
54302** SQLITE_OK is returned. Otherwise an SQLite error code.
54303*/
54304SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
54305  int rc;
54306  BtShared *pBt = p->pBt;
54307
54308  sqlite3BtreeEnter(p);
54309  assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
54310  if( !pBt->autoVacuum ){
54311    rc = SQLITE_DONE;
54312  }else{
54313    Pgno nOrig = btreePagecount(pBt);
54314    Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
54315    Pgno nFin = finalDbSize(pBt, nOrig, nFree);
54316
54317    if( nOrig<nFin ){
54318      rc = SQLITE_CORRUPT_BKPT;
54319    }else if( nFree>0 ){
54320      rc = saveAllCursors(pBt, 0, 0);
54321      if( rc==SQLITE_OK ){
54322        invalidateAllOverflowCache(pBt);
54323        rc = incrVacuumStep(pBt, nFin, nOrig, 0);
54324      }
54325      if( rc==SQLITE_OK ){
54326        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
54327        put4byte(&pBt->pPage1->aData[28], pBt->nPage);
54328      }
54329    }else{
54330      rc = SQLITE_DONE;
54331    }
54332  }
54333  sqlite3BtreeLeave(p);
54334  return rc;
54335}
54336
54337/*
54338** This routine is called prior to sqlite3PagerCommit when a transaction
54339** is committed for an auto-vacuum database.
54340**
54341** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
54342** the database file should be truncated to during the commit process.
54343** i.e. the database has been reorganized so that only the first *pnTrunc
54344** pages are in use.
54345*/
54346static int autoVacuumCommit(BtShared *pBt){
54347  int rc = SQLITE_OK;
54348  Pager *pPager = pBt->pPager;
54349  VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
54350
54351  assert( sqlite3_mutex_held(pBt->mutex) );
54352  invalidateAllOverflowCache(pBt);
54353  assert(pBt->autoVacuum);
54354  if( !pBt->incrVacuum ){
54355    Pgno nFin;         /* Number of pages in database after autovacuuming */
54356    Pgno nFree;        /* Number of pages on the freelist initially */
54357    Pgno iFree;        /* The next page to be freed */
54358    Pgno nOrig;        /* Database size before freeing */
54359
54360    nOrig = btreePagecount(pBt);
54361    if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
54362      /* It is not possible to create a database for which the final page
54363      ** is either a pointer-map page or the pending-byte page. If one
54364      ** is encountered, this indicates corruption.
54365      */
54366      return SQLITE_CORRUPT_BKPT;
54367    }
54368
54369    nFree = get4byte(&pBt->pPage1->aData[36]);
54370    nFin = finalDbSize(pBt, nOrig, nFree);
54371    if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
54372    if( nFin<nOrig ){
54373      rc = saveAllCursors(pBt, 0, 0);
54374    }
54375    for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
54376      rc = incrVacuumStep(pBt, nFin, iFree, 1);
54377    }
54378    if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
54379      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
54380      put4byte(&pBt->pPage1->aData[32], 0);
54381      put4byte(&pBt->pPage1->aData[36], 0);
54382      put4byte(&pBt->pPage1->aData[28], nFin);
54383      pBt->bDoTruncate = 1;
54384      pBt->nPage = nFin;
54385    }
54386    if( rc!=SQLITE_OK ){
54387      sqlite3PagerRollback(pPager);
54388    }
54389  }
54390
54391  assert( nRef>=sqlite3PagerRefcount(pPager) );
54392  return rc;
54393}
54394
54395#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
54396# define setChildPtrmaps(x) SQLITE_OK
54397#endif
54398
54399/*
54400** This routine does the first phase of a two-phase commit.  This routine
54401** causes a rollback journal to be created (if it does not already exist)
54402** and populated with enough information so that if a power loss occurs
54403** the database can be restored to its original state by playing back
54404** the journal.  Then the contents of the journal are flushed out to
54405** the disk.  After the journal is safely on oxide, the changes to the
54406** database are written into the database file and flushed to oxide.
54407** At the end of this call, the rollback journal still exists on the
54408** disk and we are still holding all locks, so the transaction has not
54409** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
54410** commit process.
54411**
54412** This call is a no-op if no write-transaction is currently active on pBt.
54413**
54414** Otherwise, sync the database file for the btree pBt. zMaster points to
54415** the name of a master journal file that should be written into the
54416** individual journal file, or is NULL, indicating no master journal file
54417** (single database transaction).
54418**
54419** When this is called, the master journal should already have been
54420** created, populated with this journal pointer and synced to disk.
54421**
54422** Once this is routine has returned, the only thing required to commit
54423** the write-transaction for this database file is to delete the journal.
54424*/
54425SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
54426  int rc = SQLITE_OK;
54427  if( p->inTrans==TRANS_WRITE ){
54428    BtShared *pBt = p->pBt;
54429    sqlite3BtreeEnter(p);
54430#ifndef SQLITE_OMIT_AUTOVACUUM
54431    if( pBt->autoVacuum ){
54432      rc = autoVacuumCommit(pBt);
54433      if( rc!=SQLITE_OK ){
54434        sqlite3BtreeLeave(p);
54435        return rc;
54436      }
54437    }
54438    if( pBt->bDoTruncate ){
54439      sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
54440    }
54441#endif
54442    rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
54443    sqlite3BtreeLeave(p);
54444  }
54445  return rc;
54446}
54447
54448/*
54449** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
54450** at the conclusion of a transaction.
54451*/
54452static void btreeEndTransaction(Btree *p){
54453  BtShared *pBt = p->pBt;
54454  sqlite3 *db = p->db;
54455  assert( sqlite3BtreeHoldsMutex(p) );
54456
54457#ifndef SQLITE_OMIT_AUTOVACUUM
54458  pBt->bDoTruncate = 0;
54459#endif
54460  if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
54461    /* If there are other active statements that belong to this database
54462    ** handle, downgrade to a read-only transaction. The other statements
54463    ** may still be reading from the database.  */
54464    downgradeAllSharedCacheTableLocks(p);
54465    p->inTrans = TRANS_READ;
54466  }else{
54467    /* If the handle had any kind of transaction open, decrement the
54468    ** transaction count of the shared btree. If the transaction count
54469    ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
54470    ** call below will unlock the pager.  */
54471    if( p->inTrans!=TRANS_NONE ){
54472      clearAllSharedCacheTableLocks(p);
54473      pBt->nTransaction--;
54474      if( 0==pBt->nTransaction ){
54475        pBt->inTransaction = TRANS_NONE;
54476      }
54477    }
54478
54479    /* Set the current transaction state to TRANS_NONE and unlock the
54480    ** pager if this call closed the only read or write transaction.  */
54481    p->inTrans = TRANS_NONE;
54482    unlockBtreeIfUnused(pBt);
54483  }
54484
54485  btreeIntegrity(p);
54486}
54487
54488/*
54489** Commit the transaction currently in progress.
54490**
54491** This routine implements the second phase of a 2-phase commit.  The
54492** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
54493** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
54494** routine did all the work of writing information out to disk and flushing the
54495** contents so that they are written onto the disk platter.  All this
54496** routine has to do is delete or truncate or zero the header in the
54497** the rollback journal (which causes the transaction to commit) and
54498** drop locks.
54499**
54500** Normally, if an error occurs while the pager layer is attempting to
54501** finalize the underlying journal file, this function returns an error and
54502** the upper layer will attempt a rollback. However, if the second argument
54503** is non-zero then this b-tree transaction is part of a multi-file
54504** transaction. In this case, the transaction has already been committed
54505** (by deleting a master journal file) and the caller will ignore this
54506** functions return code. So, even if an error occurs in the pager layer,
54507** reset the b-tree objects internal state to indicate that the write
54508** transaction has been closed. This is quite safe, as the pager will have
54509** transitioned to the error state.
54510**
54511** This will release the write lock on the database file.  If there
54512** are no active cursors, it also releases the read lock.
54513*/
54514SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
54515
54516  if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
54517  sqlite3BtreeEnter(p);
54518  btreeIntegrity(p);
54519
54520  /* If the handle has a write-transaction open, commit the shared-btrees
54521  ** transaction and set the shared state to TRANS_READ.
54522  */
54523  if( p->inTrans==TRANS_WRITE ){
54524    int rc;
54525    BtShared *pBt = p->pBt;
54526    assert( pBt->inTransaction==TRANS_WRITE );
54527    assert( pBt->nTransaction>0 );
54528    rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
54529    if( rc!=SQLITE_OK && bCleanup==0 ){
54530      sqlite3BtreeLeave(p);
54531      return rc;
54532    }
54533    pBt->inTransaction = TRANS_READ;
54534    btreeClearHasContent(pBt);
54535  }
54536
54537  btreeEndTransaction(p);
54538  sqlite3BtreeLeave(p);
54539  return SQLITE_OK;
54540}
54541
54542/*
54543** Do both phases of a commit.
54544*/
54545SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
54546  int rc;
54547  sqlite3BtreeEnter(p);
54548  rc = sqlite3BtreeCommitPhaseOne(p, 0);
54549  if( rc==SQLITE_OK ){
54550    rc = sqlite3BtreeCommitPhaseTwo(p, 0);
54551  }
54552  sqlite3BtreeLeave(p);
54553  return rc;
54554}
54555
54556/*
54557** This routine sets the state to CURSOR_FAULT and the error
54558** code to errCode for every cursor on BtShared that pBtree
54559** references.
54560**
54561** Every cursor is tripped, including cursors that belong
54562** to other database connections that happen to be sharing
54563** the cache with pBtree.
54564**
54565** This routine gets called when a rollback occurs.
54566** All cursors using the same cache must be tripped
54567** to prevent them from trying to use the btree after
54568** the rollback.  The rollback may have deleted tables
54569** or moved root pages, so it is not sufficient to
54570** save the state of the cursor.  The cursor must be
54571** invalidated.
54572*/
54573SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
54574  BtCursor *p;
54575  if( pBtree==0 ) return;
54576  sqlite3BtreeEnter(pBtree);
54577  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
54578    int i;
54579    sqlite3BtreeClearCursor(p);
54580    p->eState = CURSOR_FAULT;
54581    p->skipNext = errCode;
54582    for(i=0; i<=p->iPage; i++){
54583      releasePage(p->apPage[i]);
54584      p->apPage[i] = 0;
54585    }
54586  }
54587  sqlite3BtreeLeave(pBtree);
54588}
54589
54590/*
54591** Rollback the transaction in progress.  All cursors will be
54592** invalided by this operation.  Any attempt to use a cursor
54593** that was open at the beginning of this operation will result
54594** in an error.
54595**
54596** This will release the write lock on the database file.  If there
54597** are no active cursors, it also releases the read lock.
54598*/
54599SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode){
54600  int rc;
54601  BtShared *pBt = p->pBt;
54602  MemPage *pPage1;
54603
54604  sqlite3BtreeEnter(p);
54605  if( tripCode==SQLITE_OK ){
54606    rc = tripCode = saveAllCursors(pBt, 0, 0);
54607  }else{
54608    rc = SQLITE_OK;
54609  }
54610  if( tripCode ){
54611    sqlite3BtreeTripAllCursors(p, tripCode);
54612  }
54613  btreeIntegrity(p);
54614
54615  if( p->inTrans==TRANS_WRITE ){
54616    int rc2;
54617
54618    assert( TRANS_WRITE==pBt->inTransaction );
54619    rc2 = sqlite3PagerRollback(pBt->pPager);
54620    if( rc2!=SQLITE_OK ){
54621      rc = rc2;
54622    }
54623
54624    /* The rollback may have destroyed the pPage1->aData value.  So
54625    ** call btreeGetPage() on page 1 again to make
54626    ** sure pPage1->aData is set correctly. */
54627    if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
54628      int nPage = get4byte(28+(u8*)pPage1->aData);
54629      testcase( nPage==0 );
54630      if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
54631      testcase( pBt->nPage!=nPage );
54632      pBt->nPage = nPage;
54633      releasePage(pPage1);
54634    }
54635    assert( countValidCursors(pBt, 1)==0 );
54636    pBt->inTransaction = TRANS_READ;
54637    btreeClearHasContent(pBt);
54638  }
54639
54640  btreeEndTransaction(p);
54641  sqlite3BtreeLeave(p);
54642  return rc;
54643}
54644
54645/*
54646** Start a statement subtransaction. The subtransaction can can be rolled
54647** back independently of the main transaction. You must start a transaction
54648** before starting a subtransaction. The subtransaction is ended automatically
54649** if the main transaction commits or rolls back.
54650**
54651** Statement subtransactions are used around individual SQL statements
54652** that are contained within a BEGIN...COMMIT block.  If a constraint
54653** error occurs within the statement, the effect of that one statement
54654** can be rolled back without having to rollback the entire transaction.
54655**
54656** A statement sub-transaction is implemented as an anonymous savepoint. The
54657** value passed as the second parameter is the total number of savepoints,
54658** including the new anonymous savepoint, open on the B-Tree. i.e. if there
54659** are no active savepoints and no other statement-transactions open,
54660** iStatement is 1. This anonymous savepoint can be released or rolled back
54661** using the sqlite3BtreeSavepoint() function.
54662*/
54663SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
54664  int rc;
54665  BtShared *pBt = p->pBt;
54666  sqlite3BtreeEnter(p);
54667  assert( p->inTrans==TRANS_WRITE );
54668  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
54669  assert( iStatement>0 );
54670  assert( iStatement>p->db->nSavepoint );
54671  assert( pBt->inTransaction==TRANS_WRITE );
54672  /* At the pager level, a statement transaction is a savepoint with
54673  ** an index greater than all savepoints created explicitly using
54674  ** SQL statements. It is illegal to open, release or rollback any
54675  ** such savepoints while the statement transaction savepoint is active.
54676  */
54677  rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
54678  sqlite3BtreeLeave(p);
54679  return rc;
54680}
54681
54682/*
54683** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
54684** or SAVEPOINT_RELEASE. This function either releases or rolls back the
54685** savepoint identified by parameter iSavepoint, depending on the value
54686** of op.
54687**
54688** Normally, iSavepoint is greater than or equal to zero. However, if op is
54689** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
54690** contents of the entire transaction are rolled back. This is different
54691** from a normal transaction rollback, as no locks are released and the
54692** transaction remains open.
54693*/
54694SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
54695  int rc = SQLITE_OK;
54696  if( p && p->inTrans==TRANS_WRITE ){
54697    BtShared *pBt = p->pBt;
54698    assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
54699    assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
54700    sqlite3BtreeEnter(p);
54701    rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
54702    if( rc==SQLITE_OK ){
54703      if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
54704        pBt->nPage = 0;
54705      }
54706      rc = newDatabase(pBt);
54707      pBt->nPage = get4byte(28 + pBt->pPage1->aData);
54708
54709      /* The database size was written into the offset 28 of the header
54710      ** when the transaction started, so we know that the value at offset
54711      ** 28 is nonzero. */
54712      assert( pBt->nPage>0 );
54713    }
54714    sqlite3BtreeLeave(p);
54715  }
54716  return rc;
54717}
54718
54719/*
54720** Create a new cursor for the BTree whose root is on the page
54721** iTable. If a read-only cursor is requested, it is assumed that
54722** the caller already has at least a read-only transaction open
54723** on the database already. If a write-cursor is requested, then
54724** the caller is assumed to have an open write transaction.
54725**
54726** If wrFlag==0, then the cursor can only be used for reading.
54727** If wrFlag==1, then the cursor can be used for reading or for
54728** writing if other conditions for writing are also met.  These
54729** are the conditions that must be met in order for writing to
54730** be allowed:
54731**
54732** 1:  The cursor must have been opened with wrFlag==1
54733**
54734** 2:  Other database connections that share the same pager cache
54735**     but which are not in the READ_UNCOMMITTED state may not have
54736**     cursors open with wrFlag==0 on the same table.  Otherwise
54737**     the changes made by this write cursor would be visible to
54738**     the read cursors in the other database connection.
54739**
54740** 3:  The database must be writable (not on read-only media)
54741**
54742** 4:  There must be an active transaction.
54743**
54744** No checking is done to make sure that page iTable really is the
54745** root page of a b-tree.  If it is not, then the cursor acquired
54746** will not work correctly.
54747**
54748** It is assumed that the sqlite3BtreeCursorZero() has been called
54749** on pCur to initialize the memory space prior to invoking this routine.
54750*/
54751static int btreeCursor(
54752  Btree *p,                              /* The btree */
54753  int iTable,                            /* Root page of table to open */
54754  int wrFlag,                            /* 1 to write. 0 read-only */
54755  struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
54756  BtCursor *pCur                         /* Space for new cursor */
54757){
54758  BtShared *pBt = p->pBt;                /* Shared b-tree handle */
54759
54760  assert( sqlite3BtreeHoldsMutex(p) );
54761  assert( wrFlag==0 || wrFlag==1 );
54762
54763  /* The following assert statements verify that if this is a sharable
54764  ** b-tree database, the connection is holding the required table locks,
54765  ** and that no other connection has any open cursor that conflicts with
54766  ** this lock.  */
54767  assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
54768  assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
54769
54770  /* Assert that the caller has opened the required transaction. */
54771  assert( p->inTrans>TRANS_NONE );
54772  assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
54773  assert( pBt->pPage1 && pBt->pPage1->aData );
54774
54775  if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
54776    return SQLITE_READONLY;
54777  }
54778  if( iTable==1 && btreePagecount(pBt)==0 ){
54779    assert( wrFlag==0 );
54780    iTable = 0;
54781  }
54782
54783  /* Now that no other errors can occur, finish filling in the BtCursor
54784  ** variables and link the cursor into the BtShared list.  */
54785  pCur->pgnoRoot = (Pgno)iTable;
54786  pCur->iPage = -1;
54787  pCur->pKeyInfo = pKeyInfo;
54788  pCur->pBtree = p;
54789  pCur->pBt = pBt;
54790  assert( wrFlag==0 || wrFlag==BTCF_WriteFlag );
54791  pCur->curFlags = wrFlag;
54792  pCur->pNext = pBt->pCursor;
54793  if( pCur->pNext ){
54794    pCur->pNext->pPrev = pCur;
54795  }
54796  pBt->pCursor = pCur;
54797  pCur->eState = CURSOR_INVALID;
54798  return SQLITE_OK;
54799}
54800SQLITE_PRIVATE int sqlite3BtreeCursor(
54801  Btree *p,                                   /* The btree */
54802  int iTable,                                 /* Root page of table to open */
54803  int wrFlag,                                 /* 1 to write. 0 read-only */
54804  struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
54805  BtCursor *pCur                              /* Write new cursor here */
54806){
54807  int rc;
54808  sqlite3BtreeEnter(p);
54809  rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
54810  sqlite3BtreeLeave(p);
54811  return rc;
54812}
54813
54814/*
54815** Return the size of a BtCursor object in bytes.
54816**
54817** This interfaces is needed so that users of cursors can preallocate
54818** sufficient storage to hold a cursor.  The BtCursor object is opaque
54819** to users so they cannot do the sizeof() themselves - they must call
54820** this routine.
54821*/
54822SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
54823  return ROUND8(sizeof(BtCursor));
54824}
54825
54826/*
54827** Initialize memory that will be converted into a BtCursor object.
54828**
54829** The simple approach here would be to memset() the entire object
54830** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
54831** do not need to be zeroed and they are large, so we can save a lot
54832** of run-time by skipping the initialization of those elements.
54833*/
54834SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
54835  memset(p, 0, offsetof(BtCursor, iPage));
54836}
54837
54838/*
54839** Close a cursor.  The read lock on the database file is released
54840** when the last cursor is closed.
54841*/
54842SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
54843  Btree *pBtree = pCur->pBtree;
54844  if( pBtree ){
54845    int i;
54846    BtShared *pBt = pCur->pBt;
54847    sqlite3BtreeEnter(pBtree);
54848    sqlite3BtreeClearCursor(pCur);
54849    if( pCur->pPrev ){
54850      pCur->pPrev->pNext = pCur->pNext;
54851    }else{
54852      pBt->pCursor = pCur->pNext;
54853    }
54854    if( pCur->pNext ){
54855      pCur->pNext->pPrev = pCur->pPrev;
54856    }
54857    for(i=0; i<=pCur->iPage; i++){
54858      releasePage(pCur->apPage[i]);
54859    }
54860    unlockBtreeIfUnused(pBt);
54861    sqlite3DbFree(pBtree->db, pCur->aOverflow);
54862    /* sqlite3_free(pCur); */
54863    sqlite3BtreeLeave(pBtree);
54864  }
54865  return SQLITE_OK;
54866}
54867
54868/*
54869** Make sure the BtCursor* given in the argument has a valid
54870** BtCursor.info structure.  If it is not already valid, call
54871** btreeParseCell() to fill it in.
54872**
54873** BtCursor.info is a cache of the information in the current cell.
54874** Using this cache reduces the number of calls to btreeParseCell().
54875**
54876** 2007-06-25:  There is a bug in some versions of MSVC that cause the
54877** compiler to crash when getCellInfo() is implemented as a macro.
54878** But there is a measureable speed advantage to using the macro on gcc
54879** (when less compiler optimizations like -Os or -O0 are used and the
54880** compiler is not doing agressive inlining.)  So we use a real function
54881** for MSVC and a macro for everything else.  Ticket #2457.
54882*/
54883#ifndef NDEBUG
54884  static void assertCellInfo(BtCursor *pCur){
54885    CellInfo info;
54886    int iPage = pCur->iPage;
54887    memset(&info, 0, sizeof(info));
54888    btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
54889    assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
54890  }
54891#else
54892  #define assertCellInfo(x)
54893#endif
54894#ifdef _MSC_VER
54895  /* Use a real function in MSVC to work around bugs in that compiler. */
54896  static void getCellInfo(BtCursor *pCur){
54897    if( pCur->info.nSize==0 ){
54898      int iPage = pCur->iPage;
54899      btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
54900      pCur->curFlags |= BTCF_ValidNKey;
54901    }else{
54902      assertCellInfo(pCur);
54903    }
54904  }
54905#else /* if not _MSC_VER */
54906  /* Use a macro in all other compilers so that the function is inlined */
54907#define getCellInfo(pCur)                                                      \
54908  if( pCur->info.nSize==0 ){                                                   \
54909    int iPage = pCur->iPage;                                                   \
54910    btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);        \
54911    pCur->curFlags |= BTCF_ValidNKey;                                          \
54912  }else{                                                                       \
54913    assertCellInfo(pCur);                                                      \
54914  }
54915#endif /* _MSC_VER */
54916
54917#ifndef NDEBUG  /* The next routine used only within assert() statements */
54918/*
54919** Return true if the given BtCursor is valid.  A valid cursor is one
54920** that is currently pointing to a row in a (non-empty) table.
54921** This is a verification routine is used only within assert() statements.
54922*/
54923SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
54924  return pCur && pCur->eState==CURSOR_VALID;
54925}
54926#endif /* NDEBUG */
54927
54928/*
54929** Set *pSize to the size of the buffer needed to hold the value of
54930** the key for the current entry.  If the cursor is not pointing
54931** to a valid entry, *pSize is set to 0.
54932**
54933** For a table with the INTKEY flag set, this routine returns the key
54934** itself, not the number of bytes in the key.
54935**
54936** The caller must position the cursor prior to invoking this routine.
54937**
54938** This routine cannot fail.  It always returns SQLITE_OK.
54939*/
54940SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
54941  assert( cursorHoldsMutex(pCur) );
54942  assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
54943  if( pCur->eState!=CURSOR_VALID ){
54944    *pSize = 0;
54945  }else{
54946    getCellInfo(pCur);
54947    *pSize = pCur->info.nKey;
54948  }
54949  return SQLITE_OK;
54950}
54951
54952/*
54953** Set *pSize to the number of bytes of data in the entry the
54954** cursor currently points to.
54955**
54956** The caller must guarantee that the cursor is pointing to a non-NULL
54957** valid entry.  In other words, the calling procedure must guarantee
54958** that the cursor has Cursor.eState==CURSOR_VALID.
54959**
54960** Failure is not possible.  This function always returns SQLITE_OK.
54961** It might just as well be a procedure (returning void) but we continue
54962** to return an integer result code for historical reasons.
54963*/
54964SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
54965  assert( cursorHoldsMutex(pCur) );
54966  assert( pCur->eState==CURSOR_VALID );
54967  getCellInfo(pCur);
54968  *pSize = pCur->info.nData;
54969  return SQLITE_OK;
54970}
54971
54972/*
54973** Given the page number of an overflow page in the database (parameter
54974** ovfl), this function finds the page number of the next page in the
54975** linked list of overflow pages. If possible, it uses the auto-vacuum
54976** pointer-map data instead of reading the content of page ovfl to do so.
54977**
54978** If an error occurs an SQLite error code is returned. Otherwise:
54979**
54980** The page number of the next overflow page in the linked list is
54981** written to *pPgnoNext. If page ovfl is the last page in its linked
54982** list, *pPgnoNext is set to zero.
54983**
54984** If ppPage is not NULL, and a reference to the MemPage object corresponding
54985** to page number pOvfl was obtained, then *ppPage is set to point to that
54986** reference. It is the responsibility of the caller to call releasePage()
54987** on *ppPage to free the reference. In no reference was obtained (because
54988** the pointer-map was used to obtain the value for *pPgnoNext), then
54989** *ppPage is set to zero.
54990*/
54991static int getOverflowPage(
54992  BtShared *pBt,               /* The database file */
54993  Pgno ovfl,                   /* Current overflow page number */
54994  MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
54995  Pgno *pPgnoNext              /* OUT: Next overflow page number */
54996){
54997  Pgno next = 0;
54998  MemPage *pPage = 0;
54999  int rc = SQLITE_OK;
55000
55001  assert( sqlite3_mutex_held(pBt->mutex) );
55002  assert(pPgnoNext);
55003
55004#ifndef SQLITE_OMIT_AUTOVACUUM
55005  /* Try to find the next page in the overflow list using the
55006  ** autovacuum pointer-map pages. Guess that the next page in
55007  ** the overflow list is page number (ovfl+1). If that guess turns
55008  ** out to be wrong, fall back to loading the data of page
55009  ** number ovfl to determine the next page number.
55010  */
55011  if( pBt->autoVacuum ){
55012    Pgno pgno;
55013    Pgno iGuess = ovfl+1;
55014    u8 eType;
55015
55016    while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
55017      iGuess++;
55018    }
55019
55020    if( iGuess<=btreePagecount(pBt) ){
55021      rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
55022      if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
55023        next = iGuess;
55024        rc = SQLITE_DONE;
55025      }
55026    }
55027  }
55028#endif
55029
55030  assert( next==0 || rc==SQLITE_DONE );
55031  if( rc==SQLITE_OK ){
55032    rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
55033    assert( rc==SQLITE_OK || pPage==0 );
55034    if( rc==SQLITE_OK ){
55035      next = get4byte(pPage->aData);
55036    }
55037  }
55038
55039  *pPgnoNext = next;
55040  if( ppPage ){
55041    *ppPage = pPage;
55042  }else{
55043    releasePage(pPage);
55044  }
55045  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
55046}
55047
55048/*
55049** Copy data from a buffer to a page, or from a page to a buffer.
55050**
55051** pPayload is a pointer to data stored on database page pDbPage.
55052** If argument eOp is false, then nByte bytes of data are copied
55053** from pPayload to the buffer pointed at by pBuf. If eOp is true,
55054** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
55055** of data are copied from the buffer pBuf to pPayload.
55056**
55057** SQLITE_OK is returned on success, otherwise an error code.
55058*/
55059static int copyPayload(
55060  void *pPayload,           /* Pointer to page data */
55061  void *pBuf,               /* Pointer to buffer */
55062  int nByte,                /* Number of bytes to copy */
55063  int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
55064  DbPage *pDbPage           /* Page containing pPayload */
55065){
55066  if( eOp ){
55067    /* Copy data from buffer to page (a write operation) */
55068    int rc = sqlite3PagerWrite(pDbPage);
55069    if( rc!=SQLITE_OK ){
55070      return rc;
55071    }
55072    memcpy(pPayload, pBuf, nByte);
55073  }else{
55074    /* Copy data from page to buffer (a read operation) */
55075    memcpy(pBuf, pPayload, nByte);
55076  }
55077  return SQLITE_OK;
55078}
55079
55080/*
55081** This function is used to read or overwrite payload information
55082** for the entry that the pCur cursor is pointing to. The eOp
55083** argument is interpreted as follows:
55084**
55085**   0: The operation is a read. Populate the overflow cache.
55086**   1: The operation is a write. Populate the overflow cache.
55087**   2: The operation is a read. Do not populate the overflow cache.
55088**
55089** A total of "amt" bytes are read or written beginning at "offset".
55090** Data is read to or from the buffer pBuf.
55091**
55092** The content being read or written might appear on the main page
55093** or be scattered out on multiple overflow pages.
55094**
55095** If the current cursor entry uses one or more overflow pages and the
55096** eOp argument is not 2, this function may allocate space for and lazily
55097** popluates the overflow page-list cache array (BtCursor.aOverflow).
55098** Subsequent calls use this cache to make seeking to the supplied offset
55099** more efficient.
55100**
55101** Once an overflow page-list cache has been allocated, it may be
55102** invalidated if some other cursor writes to the same table, or if
55103** the cursor is moved to a different row. Additionally, in auto-vacuum
55104** mode, the following events may invalidate an overflow page-list cache.
55105**
55106**   * An incremental vacuum,
55107**   * A commit in auto_vacuum="full" mode,
55108**   * Creating a table (may require moving an overflow page).
55109*/
55110static int accessPayload(
55111  BtCursor *pCur,      /* Cursor pointing to entry to read from */
55112  u32 offset,          /* Begin reading this far into payload */
55113  u32 amt,             /* Read this many bytes */
55114  unsigned char *pBuf, /* Write the bytes into this buffer */
55115  int eOp              /* zero to read. non-zero to write. */
55116){
55117  unsigned char *aPayload;
55118  int rc = SQLITE_OK;
55119  u32 nKey;
55120  int iIdx = 0;
55121  MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
55122  BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
55123#ifdef SQLITE_DIRECT_OVERFLOW_READ
55124  int bEnd;                                   /* True if reading to end of data */
55125#endif
55126
55127  assert( pPage );
55128  assert( pCur->eState==CURSOR_VALID );
55129  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
55130  assert( cursorHoldsMutex(pCur) );
55131  assert( eOp!=2 || offset==0 );      /* Always start from beginning for eOp==2 */
55132
55133  getCellInfo(pCur);
55134  aPayload = pCur->info.pCell + pCur->info.nHeader;
55135  nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
55136#ifdef SQLITE_DIRECT_OVERFLOW_READ
55137  bEnd = (offset+amt==nKey+pCur->info.nData);
55138#endif
55139
55140  if( NEVER(offset+amt > nKey+pCur->info.nData)
55141   || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
55142  ){
55143    /* Trying to read or write past the end of the data is an error */
55144    return SQLITE_CORRUPT_BKPT;
55145  }
55146
55147  /* Check if data must be read/written to/from the btree page itself. */
55148  if( offset<pCur->info.nLocal ){
55149    int a = amt;
55150    if( a+offset>pCur->info.nLocal ){
55151      a = pCur->info.nLocal - offset;
55152    }
55153    rc = copyPayload(&aPayload[offset], pBuf, a, (eOp & 0x01), pPage->pDbPage);
55154    offset = 0;
55155    pBuf += a;
55156    amt -= a;
55157  }else{
55158    offset -= pCur->info.nLocal;
55159  }
55160
55161  if( rc==SQLITE_OK && amt>0 ){
55162    const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
55163    Pgno nextPage;
55164
55165    nextPage = get4byte(&aPayload[pCur->info.nLocal]);
55166
55167    /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
55168    ** Except, do not allocate aOverflow[] for eOp==2.
55169    **
55170    ** The aOverflow[] array is sized at one entry for each overflow page
55171    ** in the overflow chain. The page number of the first overflow page is
55172    ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
55173    ** means "not yet known" (the cache is lazily populated).
55174    */
55175    if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){
55176      int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
55177      if( nOvfl>pCur->nOvflAlloc ){
55178        Pgno *aNew = (Pgno*)sqlite3DbRealloc(
55179            pCur->pBtree->db, pCur->aOverflow, nOvfl*2*sizeof(Pgno)
55180        );
55181        if( aNew==0 ){
55182          rc = SQLITE_NOMEM;
55183        }else{
55184          pCur->nOvflAlloc = nOvfl*2;
55185          pCur->aOverflow = aNew;
55186        }
55187      }
55188      if( rc==SQLITE_OK ){
55189        memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
55190        pCur->curFlags |= BTCF_ValidOvfl;
55191      }
55192    }
55193
55194    /* If the overflow page-list cache has been allocated and the
55195    ** entry for the first required overflow page is valid, skip
55196    ** directly to it.
55197    */
55198    if( (pCur->curFlags & BTCF_ValidOvfl)!=0 && pCur->aOverflow[offset/ovflSize] ){
55199      iIdx = (offset/ovflSize);
55200      nextPage = pCur->aOverflow[iIdx];
55201      offset = (offset%ovflSize);
55202    }
55203
55204    for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
55205
55206      /* If required, populate the overflow page-list cache. */
55207      if( (pCur->curFlags & BTCF_ValidOvfl)!=0 ){
55208        assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
55209        pCur->aOverflow[iIdx] = nextPage;
55210      }
55211
55212      if( offset>=ovflSize ){
55213        /* The only reason to read this page is to obtain the page
55214        ** number for the next page in the overflow chain. The page
55215        ** data is not required. So first try to lookup the overflow
55216        ** page-list cache, if any, then fall back to the getOverflowPage()
55217        ** function.
55218        **
55219        ** Note that the aOverflow[] array must be allocated because eOp!=2
55220        ** here.  If eOp==2, then offset==0 and this branch is never taken.
55221        */
55222        assert( eOp!=2 );
55223        assert( pCur->curFlags & BTCF_ValidOvfl );
55224        if( pCur->aOverflow[iIdx+1] ){
55225          nextPage = pCur->aOverflow[iIdx+1];
55226        }else{
55227          rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
55228        }
55229        offset -= ovflSize;
55230      }else{
55231        /* Need to read this page properly. It contains some of the
55232        ** range of data that is being read (eOp==0) or written (eOp!=0).
55233        */
55234#ifdef SQLITE_DIRECT_OVERFLOW_READ
55235        sqlite3_file *fd;
55236#endif
55237        int a = amt;
55238        if( a + offset > ovflSize ){
55239          a = ovflSize - offset;
55240        }
55241
55242#ifdef SQLITE_DIRECT_OVERFLOW_READ
55243        /* If all the following are true:
55244        **
55245        **   1) this is a read operation, and
55246        **   2) data is required from the start of this overflow page, and
55247        **   3) the database is file-backed, and
55248        **   4) there is no open write-transaction, and
55249        **   5) the database is not a WAL database,
55250        **   6) all data from the page is being read.
55251        **
55252        ** then data can be read directly from the database file into the
55253        ** output buffer, bypassing the page-cache altogether. This speeds
55254        ** up loading large records that span many overflow pages.
55255        */
55256        if( (eOp&0x01)==0                                      /* (1) */
55257         && offset==0                                          /* (2) */
55258         && (bEnd || a==ovflSize)                              /* (6) */
55259         && pBt->inTransaction==TRANS_READ                     /* (4) */
55260         && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (3) */
55261         && pBt->pPage1->aData[19]==0x01                       /* (5) */
55262        ){
55263          u8 aSave[4];
55264          u8 *aWrite = &pBuf[-4];
55265          memcpy(aSave, aWrite, 4);
55266          rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
55267          nextPage = get4byte(aWrite);
55268          memcpy(aWrite, aSave, 4);
55269        }else
55270#endif
55271
55272        {
55273          DbPage *pDbPage;
55274          rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage,
55275              ((eOp&0x01)==0 ? PAGER_GET_READONLY : 0)
55276          );
55277          if( rc==SQLITE_OK ){
55278            aPayload = sqlite3PagerGetData(pDbPage);
55279            nextPage = get4byte(aPayload);
55280            rc = copyPayload(&aPayload[offset+4], pBuf, a, (eOp&0x01), pDbPage);
55281            sqlite3PagerUnref(pDbPage);
55282            offset = 0;
55283          }
55284        }
55285        amt -= a;
55286        pBuf += a;
55287      }
55288    }
55289  }
55290
55291  if( rc==SQLITE_OK && amt>0 ){
55292    return SQLITE_CORRUPT_BKPT;
55293  }
55294  return rc;
55295}
55296
55297/*
55298** Read part of the key associated with cursor pCur.  Exactly
55299** "amt" bytes will be transfered into pBuf[].  The transfer
55300** begins at "offset".
55301**
55302** The caller must ensure that pCur is pointing to a valid row
55303** in the table.
55304**
55305** Return SQLITE_OK on success or an error code if anything goes
55306** wrong.  An error is returned if "offset+amt" is larger than
55307** the available payload.
55308*/
55309SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
55310  assert( cursorHoldsMutex(pCur) );
55311  assert( pCur->eState==CURSOR_VALID );
55312  assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
55313  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
55314  return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
55315}
55316
55317/*
55318** Read part of the data associated with cursor pCur.  Exactly
55319** "amt" bytes will be transfered into pBuf[].  The transfer
55320** begins at "offset".
55321**
55322** Return SQLITE_OK on success or an error code if anything goes
55323** wrong.  An error is returned if "offset+amt" is larger than
55324** the available payload.
55325*/
55326SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
55327  int rc;
55328
55329#ifndef SQLITE_OMIT_INCRBLOB
55330  if ( pCur->eState==CURSOR_INVALID ){
55331    return SQLITE_ABORT;
55332  }
55333#endif
55334
55335  assert( cursorHoldsMutex(pCur) );
55336  rc = restoreCursorPosition(pCur);
55337  if( rc==SQLITE_OK ){
55338    assert( pCur->eState==CURSOR_VALID );
55339    assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
55340    assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
55341    rc = accessPayload(pCur, offset, amt, pBuf, 0);
55342  }
55343  return rc;
55344}
55345
55346/*
55347** Return a pointer to payload information from the entry that the
55348** pCur cursor is pointing to.  The pointer is to the beginning of
55349** the key if index btrees (pPage->intKey==0) and is the data for
55350** table btrees (pPage->intKey==1). The number of bytes of available
55351** key/data is written into *pAmt.  If *pAmt==0, then the value
55352** returned will not be a valid pointer.
55353**
55354** This routine is an optimization.  It is common for the entire key
55355** and data to fit on the local page and for there to be no overflow
55356** pages.  When that is so, this routine can be used to access the
55357** key and data without making a copy.  If the key and/or data spills
55358** onto overflow pages, then accessPayload() must be used to reassemble
55359** the key/data and copy it into a preallocated buffer.
55360**
55361** The pointer returned by this routine looks directly into the cached
55362** page of the database.  The data might change or move the next time
55363** any btree routine is called.
55364*/
55365static const void *fetchPayload(
55366  BtCursor *pCur,      /* Cursor pointing to entry to read from */
55367  u32 *pAmt            /* Write the number of available bytes here */
55368){
55369  assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
55370  assert( pCur->eState==CURSOR_VALID );
55371  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
55372  assert( cursorHoldsMutex(pCur) );
55373  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
55374  assert( pCur->info.nSize>0 );
55375  *pAmt = pCur->info.nLocal;
55376  return (void*)(pCur->info.pCell + pCur->info.nHeader);
55377}
55378
55379
55380/*
55381** For the entry that cursor pCur is point to, return as
55382** many bytes of the key or data as are available on the local
55383** b-tree page.  Write the number of available bytes into *pAmt.
55384**
55385** The pointer returned is ephemeral.  The key/data may move
55386** or be destroyed on the next call to any Btree routine,
55387** including calls from other threads against the same cache.
55388** Hence, a mutex on the BtShared should be held prior to calling
55389** this routine.
55390**
55391** These routines is used to get quick access to key and data
55392** in the common case where no overflow pages are used.
55393*/
55394SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, u32 *pAmt){
55395  return fetchPayload(pCur, pAmt);
55396}
55397SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, u32 *pAmt){
55398  return fetchPayload(pCur, pAmt);
55399}
55400
55401
55402/*
55403** Move the cursor down to a new child page.  The newPgno argument is the
55404** page number of the child page to move to.
55405**
55406** This function returns SQLITE_CORRUPT if the page-header flags field of
55407** the new child page does not match the flags field of the parent (i.e.
55408** if an intkey page appears to be the parent of a non-intkey page, or
55409** vice-versa).
55410*/
55411static int moveToChild(BtCursor *pCur, u32 newPgno){
55412  int rc;
55413  int i = pCur->iPage;
55414  MemPage *pNewPage;
55415  BtShared *pBt = pCur->pBt;
55416
55417  assert( cursorHoldsMutex(pCur) );
55418  assert( pCur->eState==CURSOR_VALID );
55419  assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
55420  assert( pCur->iPage>=0 );
55421  if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
55422    return SQLITE_CORRUPT_BKPT;
55423  }
55424  rc = getAndInitPage(pBt, newPgno, &pNewPage,
55425               (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0);
55426  if( rc ) return rc;
55427  pCur->apPage[i+1] = pNewPage;
55428  pCur->aiIdx[i+1] = 0;
55429  pCur->iPage++;
55430
55431  pCur->info.nSize = 0;
55432  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
55433  if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
55434    return SQLITE_CORRUPT_BKPT;
55435  }
55436  return SQLITE_OK;
55437}
55438
55439#if 0
55440/*
55441** Page pParent is an internal (non-leaf) tree page. This function
55442** asserts that page number iChild is the left-child if the iIdx'th
55443** cell in page pParent. Or, if iIdx is equal to the total number of
55444** cells in pParent, that page number iChild is the right-child of
55445** the page.
55446*/
55447static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
55448  assert( iIdx<=pParent->nCell );
55449  if( iIdx==pParent->nCell ){
55450    assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
55451  }else{
55452    assert( get4byte(findCell(pParent, iIdx))==iChild );
55453  }
55454}
55455#else
55456#  define assertParentIndex(x,y,z)
55457#endif
55458
55459/*
55460** Move the cursor up to the parent page.
55461**
55462** pCur->idx is set to the cell index that contains the pointer
55463** to the page we are coming from.  If we are coming from the
55464** right-most child page then pCur->idx is set to one more than
55465** the largest cell index.
55466*/
55467static void moveToParent(BtCursor *pCur){
55468  assert( cursorHoldsMutex(pCur) );
55469  assert( pCur->eState==CURSOR_VALID );
55470  assert( pCur->iPage>0 );
55471  assert( pCur->apPage[pCur->iPage] );
55472
55473  /* UPDATE: It is actually possible for the condition tested by the assert
55474  ** below to be untrue if the database file is corrupt. This can occur if
55475  ** one cursor has modified page pParent while a reference to it is held
55476  ** by a second cursor. Which can only happen if a single page is linked
55477  ** into more than one b-tree structure in a corrupt database.  */
55478#if 0
55479  assertParentIndex(
55480    pCur->apPage[pCur->iPage-1],
55481    pCur->aiIdx[pCur->iPage-1],
55482    pCur->apPage[pCur->iPage]->pgno
55483  );
55484#endif
55485  testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
55486
55487  releasePage(pCur->apPage[pCur->iPage]);
55488  pCur->iPage--;
55489  pCur->info.nSize = 0;
55490  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
55491}
55492
55493/*
55494** Move the cursor to point to the root page of its b-tree structure.
55495**
55496** If the table has a virtual root page, then the cursor is moved to point
55497** to the virtual root page instead of the actual root page. A table has a
55498** virtual root page when the actual root page contains no cells and a
55499** single child page. This can only happen with the table rooted at page 1.
55500**
55501** If the b-tree structure is empty, the cursor state is set to
55502** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
55503** cell located on the root (or virtual root) page and the cursor state
55504** is set to CURSOR_VALID.
55505**
55506** If this function returns successfully, it may be assumed that the
55507** page-header flags indicate that the [virtual] root-page is the expected
55508** kind of b-tree page (i.e. if when opening the cursor the caller did not
55509** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
55510** indicating a table b-tree, or if the caller did specify a KeyInfo
55511** structure the flags byte is set to 0x02 or 0x0A, indicating an index
55512** b-tree).
55513*/
55514static int moveToRoot(BtCursor *pCur){
55515  MemPage *pRoot;
55516  int rc = SQLITE_OK;
55517
55518  assert( cursorHoldsMutex(pCur) );
55519  assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
55520  assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
55521  assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
55522  if( pCur->eState>=CURSOR_REQUIRESEEK ){
55523    if( pCur->eState==CURSOR_FAULT ){
55524      assert( pCur->skipNext!=SQLITE_OK );
55525      return pCur->skipNext;
55526    }
55527    sqlite3BtreeClearCursor(pCur);
55528  }
55529
55530  if( pCur->iPage>=0 ){
55531    while( pCur->iPage ) releasePage(pCur->apPage[pCur->iPage--]);
55532  }else if( pCur->pgnoRoot==0 ){
55533    pCur->eState = CURSOR_INVALID;
55534    return SQLITE_OK;
55535  }else{
55536    rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
55537                 (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0);
55538    if( rc!=SQLITE_OK ){
55539      pCur->eState = CURSOR_INVALID;
55540      return rc;
55541    }
55542    pCur->iPage = 0;
55543  }
55544  pRoot = pCur->apPage[0];
55545  assert( pRoot->pgno==pCur->pgnoRoot );
55546
55547  /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
55548  ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
55549  ** NULL, the caller expects a table b-tree. If this is not the case,
55550  ** return an SQLITE_CORRUPT error.
55551  **
55552  ** Earlier versions of SQLite assumed that this test could not fail
55553  ** if the root page was already loaded when this function was called (i.e.
55554  ** if pCur->iPage>=0). But this is not so if the database is corrupted
55555  ** in such a way that page pRoot is linked into a second b-tree table
55556  ** (or the freelist).  */
55557  assert( pRoot->intKey==1 || pRoot->intKey==0 );
55558  if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
55559    return SQLITE_CORRUPT_BKPT;
55560  }
55561
55562  pCur->aiIdx[0] = 0;
55563  pCur->info.nSize = 0;
55564  pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
55565
55566  if( pRoot->nCell>0 ){
55567    pCur->eState = CURSOR_VALID;
55568  }else if( !pRoot->leaf ){
55569    Pgno subpage;
55570    if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
55571    subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
55572    pCur->eState = CURSOR_VALID;
55573    rc = moveToChild(pCur, subpage);
55574  }else{
55575    pCur->eState = CURSOR_INVALID;
55576  }
55577  return rc;
55578}
55579
55580/*
55581** Move the cursor down to the left-most leaf entry beneath the
55582** entry to which it is currently pointing.
55583**
55584** The left-most leaf is the one with the smallest key - the first
55585** in ascending order.
55586*/
55587static int moveToLeftmost(BtCursor *pCur){
55588  Pgno pgno;
55589  int rc = SQLITE_OK;
55590  MemPage *pPage;
55591
55592  assert( cursorHoldsMutex(pCur) );
55593  assert( pCur->eState==CURSOR_VALID );
55594  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
55595    assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
55596    pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
55597    rc = moveToChild(pCur, pgno);
55598  }
55599  return rc;
55600}
55601
55602/*
55603** Move the cursor down to the right-most leaf entry beneath the
55604** page to which it is currently pointing.  Notice the difference
55605** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
55606** finds the left-most entry beneath the *entry* whereas moveToRightmost()
55607** finds the right-most entry beneath the *page*.
55608**
55609** The right-most entry is the one with the largest key - the last
55610** key in ascending order.
55611*/
55612static int moveToRightmost(BtCursor *pCur){
55613  Pgno pgno;
55614  int rc = SQLITE_OK;
55615  MemPage *pPage = 0;
55616
55617  assert( cursorHoldsMutex(pCur) );
55618  assert( pCur->eState==CURSOR_VALID );
55619  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
55620    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
55621    pCur->aiIdx[pCur->iPage] = pPage->nCell;
55622    rc = moveToChild(pCur, pgno);
55623  }
55624  if( rc==SQLITE_OK ){
55625    pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
55626    pCur->info.nSize = 0;
55627    pCur->curFlags &= ~BTCF_ValidNKey;
55628  }
55629  return rc;
55630}
55631
55632/* Move the cursor to the first entry in the table.  Return SQLITE_OK
55633** on success.  Set *pRes to 0 if the cursor actually points to something
55634** or set *pRes to 1 if the table is empty.
55635*/
55636SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
55637  int rc;
55638
55639  assert( cursorHoldsMutex(pCur) );
55640  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
55641  rc = moveToRoot(pCur);
55642  if( rc==SQLITE_OK ){
55643    if( pCur->eState==CURSOR_INVALID ){
55644      assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
55645      *pRes = 1;
55646    }else{
55647      assert( pCur->apPage[pCur->iPage]->nCell>0 );
55648      *pRes = 0;
55649      rc = moveToLeftmost(pCur);
55650    }
55651  }
55652  return rc;
55653}
55654
55655/* Move the cursor to the last entry in the table.  Return SQLITE_OK
55656** on success.  Set *pRes to 0 if the cursor actually points to something
55657** or set *pRes to 1 if the table is empty.
55658*/
55659SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
55660  int rc;
55661
55662  assert( cursorHoldsMutex(pCur) );
55663  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
55664
55665  /* If the cursor already points to the last entry, this is a no-op. */
55666  if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
55667#ifdef SQLITE_DEBUG
55668    /* This block serves to assert() that the cursor really does point
55669    ** to the last entry in the b-tree. */
55670    int ii;
55671    for(ii=0; ii<pCur->iPage; ii++){
55672      assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
55673    }
55674    assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
55675    assert( pCur->apPage[pCur->iPage]->leaf );
55676#endif
55677    return SQLITE_OK;
55678  }
55679
55680  rc = moveToRoot(pCur);
55681  if( rc==SQLITE_OK ){
55682    if( CURSOR_INVALID==pCur->eState ){
55683      assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
55684      *pRes = 1;
55685    }else{
55686      assert( pCur->eState==CURSOR_VALID );
55687      *pRes = 0;
55688      rc = moveToRightmost(pCur);
55689      if( rc==SQLITE_OK ){
55690        pCur->curFlags |= BTCF_AtLast;
55691      }else{
55692        pCur->curFlags &= ~BTCF_AtLast;
55693      }
55694
55695    }
55696  }
55697  return rc;
55698}
55699
55700/* Move the cursor so that it points to an entry near the key
55701** specified by pIdxKey or intKey.   Return a success code.
55702**
55703** For INTKEY tables, the intKey parameter is used.  pIdxKey
55704** must be NULL.  For index tables, pIdxKey is used and intKey
55705** is ignored.
55706**
55707** If an exact match is not found, then the cursor is always
55708** left pointing at a leaf page which would hold the entry if it
55709** were present.  The cursor might point to an entry that comes
55710** before or after the key.
55711**
55712** An integer is written into *pRes which is the result of
55713** comparing the key with the entry to which the cursor is
55714** pointing.  The meaning of the integer written into
55715** *pRes is as follows:
55716**
55717**     *pRes<0      The cursor is left pointing at an entry that
55718**                  is smaller than intKey/pIdxKey or if the table is empty
55719**                  and the cursor is therefore left point to nothing.
55720**
55721**     *pRes==0     The cursor is left pointing at an entry that
55722**                  exactly matches intKey/pIdxKey.
55723**
55724**     *pRes>0      The cursor is left pointing at an entry that
55725**                  is larger than intKey/pIdxKey.
55726**
55727*/
55728SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
55729  BtCursor *pCur,          /* The cursor to be moved */
55730  UnpackedRecord *pIdxKey, /* Unpacked index key */
55731  i64 intKey,              /* The table key */
55732  int biasRight,           /* If true, bias the search to the high end */
55733  int *pRes                /* Write search results here */
55734){
55735  int rc;
55736  RecordCompare xRecordCompare;
55737
55738  assert( cursorHoldsMutex(pCur) );
55739  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
55740  assert( pRes );
55741  assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
55742
55743  /* If the cursor is already positioned at the point we are trying
55744  ** to move to, then just return without doing any work */
55745  if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
55746   && pCur->apPage[0]->intKey
55747  ){
55748    if( pCur->info.nKey==intKey ){
55749      *pRes = 0;
55750      return SQLITE_OK;
55751    }
55752    if( (pCur->curFlags & BTCF_AtLast)!=0 && pCur->info.nKey<intKey ){
55753      *pRes = -1;
55754      return SQLITE_OK;
55755    }
55756  }
55757
55758  if( pIdxKey ){
55759    xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
55760    pIdxKey->isCorrupt = 0;
55761    assert( pIdxKey->default_rc==1
55762         || pIdxKey->default_rc==0
55763         || pIdxKey->default_rc==-1
55764    );
55765  }else{
55766    xRecordCompare = 0; /* All keys are integers */
55767  }
55768
55769  rc = moveToRoot(pCur);
55770  if( rc ){
55771    return rc;
55772  }
55773  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
55774  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
55775  assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
55776  if( pCur->eState==CURSOR_INVALID ){
55777    *pRes = -1;
55778    assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
55779    return SQLITE_OK;
55780  }
55781  assert( pCur->apPage[0]->intKey || pIdxKey );
55782  for(;;){
55783    int lwr, upr, idx, c;
55784    Pgno chldPg;
55785    MemPage *pPage = pCur->apPage[pCur->iPage];
55786    u8 *pCell;                          /* Pointer to current cell in pPage */
55787
55788    /* pPage->nCell must be greater than zero. If this is the root-page
55789    ** the cursor would have been INVALID above and this for(;;) loop
55790    ** not run. If this is not the root-page, then the moveToChild() routine
55791    ** would have already detected db corruption. Similarly, pPage must
55792    ** be the right kind (index or table) of b-tree page. Otherwise
55793    ** a moveToChild() or moveToRoot() call would have detected corruption.  */
55794    assert( pPage->nCell>0 );
55795    assert( pPage->intKey==(pIdxKey==0) );
55796    lwr = 0;
55797    upr = pPage->nCell-1;
55798    assert( biasRight==0 || biasRight==1 );
55799    idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
55800    pCur->aiIdx[pCur->iPage] = (u16)idx;
55801    if( xRecordCompare==0 ){
55802      for(;;){
55803        i64 nCellKey;
55804        pCell = findCell(pPage, idx) + pPage->childPtrSize;
55805        if( pPage->hasData ){
55806          while( 0x80 <= *(pCell++) ){
55807            if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
55808          }
55809        }
55810        getVarint(pCell, (u64*)&nCellKey);
55811        if( nCellKey<intKey ){
55812          lwr = idx+1;
55813          if( lwr>upr ){ c = -1; break; }
55814        }else if( nCellKey>intKey ){
55815          upr = idx-1;
55816          if( lwr>upr ){ c = +1; break; }
55817        }else{
55818          assert( nCellKey==intKey );
55819          pCur->curFlags |= BTCF_ValidNKey;
55820          pCur->info.nKey = nCellKey;
55821          pCur->aiIdx[pCur->iPage] = (u16)idx;
55822          if( !pPage->leaf ){
55823            lwr = idx;
55824            goto moveto_next_layer;
55825          }else{
55826            *pRes = 0;
55827            rc = SQLITE_OK;
55828            goto moveto_finish;
55829          }
55830        }
55831        assert( lwr+upr>=0 );
55832        idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2; */
55833      }
55834    }else{
55835      for(;;){
55836        int nCell;
55837        pCell = findCell(pPage, idx) + pPage->childPtrSize;
55838
55839        /* The maximum supported page-size is 65536 bytes. This means that
55840        ** the maximum number of record bytes stored on an index B-Tree
55841        ** page is less than 16384 bytes and may be stored as a 2-byte
55842        ** varint. This information is used to attempt to avoid parsing
55843        ** the entire cell by checking for the cases where the record is
55844        ** stored entirely within the b-tree page by inspecting the first
55845        ** 2 bytes of the cell.
55846        */
55847        nCell = pCell[0];
55848        if( nCell<=pPage->max1bytePayload ){
55849          /* This branch runs if the record-size field of the cell is a
55850          ** single byte varint and the record fits entirely on the main
55851          ** b-tree page.  */
55852          testcase( pCell+nCell+1==pPage->aDataEnd );
55853          c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey, 0);
55854        }else if( !(pCell[1] & 0x80)
55855          && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
55856        ){
55857          /* The record-size field is a 2 byte varint and the record
55858          ** fits entirely on the main b-tree page.  */
55859          testcase( pCell+nCell+2==pPage->aDataEnd );
55860          c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey, 0);
55861        }else{
55862          /* The record flows over onto one or more overflow pages. In
55863          ** this case the whole cell needs to be parsed, a buffer allocated
55864          ** and accessPayload() used to retrieve the record into the
55865          ** buffer before VdbeRecordCompare() can be called. */
55866          void *pCellKey;
55867          u8 * const pCellBody = pCell - pPage->childPtrSize;
55868          btreeParseCellPtr(pPage, pCellBody, &pCur->info);
55869          nCell = (int)pCur->info.nKey;
55870          pCellKey = sqlite3Malloc( nCell );
55871          if( pCellKey==0 ){
55872            rc = SQLITE_NOMEM;
55873            goto moveto_finish;
55874          }
55875          pCur->aiIdx[pCur->iPage] = (u16)idx;
55876          rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2);
55877          if( rc ){
55878            sqlite3_free(pCellKey);
55879            goto moveto_finish;
55880          }
55881          c = xRecordCompare(nCell, pCellKey, pIdxKey, 0);
55882          sqlite3_free(pCellKey);
55883        }
55884        assert( pIdxKey->isCorrupt==0 || c==0 );
55885        if( c<0 ){
55886          lwr = idx+1;
55887        }else if( c>0 ){
55888          upr = idx-1;
55889        }else{
55890          assert( c==0 );
55891          *pRes = 0;
55892          rc = SQLITE_OK;
55893          pCur->aiIdx[pCur->iPage] = (u16)idx;
55894          if( pIdxKey->isCorrupt ) rc = SQLITE_CORRUPT;
55895          goto moveto_finish;
55896        }
55897        if( lwr>upr ) break;
55898        assert( lwr+upr>=0 );
55899        idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2 */
55900      }
55901    }
55902    assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
55903    assert( pPage->isInit );
55904    if( pPage->leaf ){
55905      assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
55906      pCur->aiIdx[pCur->iPage] = (u16)idx;
55907      *pRes = c;
55908      rc = SQLITE_OK;
55909      goto moveto_finish;
55910    }
55911moveto_next_layer:
55912    if( lwr>=pPage->nCell ){
55913      chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
55914    }else{
55915      chldPg = get4byte(findCell(pPage, lwr));
55916    }
55917    pCur->aiIdx[pCur->iPage] = (u16)lwr;
55918    rc = moveToChild(pCur, chldPg);
55919    if( rc ) break;
55920  }
55921moveto_finish:
55922  pCur->info.nSize = 0;
55923  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
55924  return rc;
55925}
55926
55927
55928/*
55929** Return TRUE if the cursor is not pointing at an entry of the table.
55930**
55931** TRUE will be returned after a call to sqlite3BtreeNext() moves
55932** past the last entry in the table or sqlite3BtreePrev() moves past
55933** the first entry.  TRUE is also returned if the table is empty.
55934*/
55935SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
55936  /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
55937  ** have been deleted? This API will need to change to return an error code
55938  ** as well as the boolean result value.
55939  */
55940  return (CURSOR_VALID!=pCur->eState);
55941}
55942
55943/*
55944** Advance the cursor to the next entry in the database.  If
55945** successful then set *pRes=0.  If the cursor
55946** was already pointing to the last entry in the database before
55947** this routine was called, then set *pRes=1.
55948**
55949** The calling function will set *pRes to 0 or 1.  The initial *pRes value
55950** will be 1 if the cursor being stepped corresponds to an SQL index and
55951** if this routine could have been skipped if that SQL index had been
55952** a unique index.  Otherwise the caller will have set *pRes to zero.
55953** Zero is the common case. The btree implementation is free to use the
55954** initial *pRes value as a hint to improve performance, but the current
55955** SQLite btree implementation does not. (Note that the comdb2 btree
55956** implementation does use this hint, however.)
55957*/
55958SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
55959  int rc;
55960  int idx;
55961  MemPage *pPage;
55962
55963  assert( cursorHoldsMutex(pCur) );
55964  assert( pRes!=0 );
55965  assert( *pRes==0 || *pRes==1 );
55966  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
55967  if( pCur->eState!=CURSOR_VALID ){
55968    invalidateOverflowCache(pCur);
55969    rc = restoreCursorPosition(pCur);
55970    if( rc!=SQLITE_OK ){
55971      *pRes = 0;
55972      return rc;
55973    }
55974    if( CURSOR_INVALID==pCur->eState ){
55975      *pRes = 1;
55976      return SQLITE_OK;
55977    }
55978    if( pCur->skipNext ){
55979      assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
55980      pCur->eState = CURSOR_VALID;
55981      if( pCur->skipNext>0 ){
55982        pCur->skipNext = 0;
55983        *pRes = 0;
55984        return SQLITE_OK;
55985      }
55986      pCur->skipNext = 0;
55987    }
55988  }
55989
55990  pPage = pCur->apPage[pCur->iPage];
55991  idx = ++pCur->aiIdx[pCur->iPage];
55992  assert( pPage->isInit );
55993
55994  /* If the database file is corrupt, it is possible for the value of idx
55995  ** to be invalid here. This can only occur if a second cursor modifies
55996  ** the page while cursor pCur is holding a reference to it. Which can
55997  ** only happen if the database is corrupt in such a way as to link the
55998  ** page into more than one b-tree structure. */
55999  testcase( idx>pPage->nCell );
56000
56001  pCur->info.nSize = 0;
56002  pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
56003  if( idx>=pPage->nCell ){
56004    if( !pPage->leaf ){
56005      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
56006      if( rc ){
56007        *pRes = 0;
56008        return rc;
56009      }
56010      rc = moveToLeftmost(pCur);
56011      *pRes = 0;
56012      return rc;
56013    }
56014    do{
56015      if( pCur->iPage==0 ){
56016        *pRes = 1;
56017        pCur->eState = CURSOR_INVALID;
56018        return SQLITE_OK;
56019      }
56020      moveToParent(pCur);
56021      pPage = pCur->apPage[pCur->iPage];
56022    }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
56023    *pRes = 0;
56024    if( pPage->intKey ){
56025      rc = sqlite3BtreeNext(pCur, pRes);
56026    }else{
56027      rc = SQLITE_OK;
56028    }
56029    return rc;
56030  }
56031  *pRes = 0;
56032  if( pPage->leaf ){
56033    return SQLITE_OK;
56034  }
56035  rc = moveToLeftmost(pCur);
56036  return rc;
56037}
56038
56039
56040/*
56041** Step the cursor to the back to the previous entry in the database.  If
56042** successful then set *pRes=0.  If the cursor
56043** was already pointing to the first entry in the database before
56044** this routine was called, then set *pRes=1.
56045**
56046** The calling function will set *pRes to 0 or 1.  The initial *pRes value
56047** will be 1 if the cursor being stepped corresponds to an SQL index and
56048** if this routine could have been skipped if that SQL index had been
56049** a unique index.  Otherwise the caller will have set *pRes to zero.
56050** Zero is the common case. The btree implementation is free to use the
56051** initial *pRes value as a hint to improve performance, but the current
56052** SQLite btree implementation does not. (Note that the comdb2 btree
56053** implementation does use this hint, however.)
56054*/
56055SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
56056  int rc;
56057  MemPage *pPage;
56058
56059  assert( cursorHoldsMutex(pCur) );
56060  assert( pRes!=0 );
56061  assert( *pRes==0 || *pRes==1 );
56062  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
56063  pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl);
56064  if( pCur->eState!=CURSOR_VALID ){
56065    if( ALWAYS(pCur->eState>=CURSOR_REQUIRESEEK) ){
56066      rc = btreeRestoreCursorPosition(pCur);
56067      if( rc!=SQLITE_OK ){
56068        *pRes = 0;
56069        return rc;
56070      }
56071    }
56072    if( CURSOR_INVALID==pCur->eState ){
56073      *pRes = 1;
56074      return SQLITE_OK;
56075    }
56076    if( pCur->skipNext ){
56077      assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
56078      pCur->eState = CURSOR_VALID;
56079      if( pCur->skipNext<0 ){
56080        pCur->skipNext = 0;
56081        *pRes = 0;
56082        return SQLITE_OK;
56083      }
56084      pCur->skipNext = 0;
56085    }
56086  }
56087
56088  pPage = pCur->apPage[pCur->iPage];
56089  assert( pPage->isInit );
56090  if( !pPage->leaf ){
56091    int idx = pCur->aiIdx[pCur->iPage];
56092    rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
56093    if( rc ){
56094      *pRes = 0;
56095      return rc;
56096    }
56097    rc = moveToRightmost(pCur);
56098  }else{
56099    while( pCur->aiIdx[pCur->iPage]==0 ){
56100      if( pCur->iPage==0 ){
56101        pCur->eState = CURSOR_INVALID;
56102        *pRes = 1;
56103        return SQLITE_OK;
56104      }
56105      moveToParent(pCur);
56106    }
56107    pCur->info.nSize = 0;
56108    pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
56109
56110    pCur->aiIdx[pCur->iPage]--;
56111    pPage = pCur->apPage[pCur->iPage];
56112    if( pPage->intKey && !pPage->leaf ){
56113      rc = sqlite3BtreePrevious(pCur, pRes);
56114    }else{
56115      rc = SQLITE_OK;
56116    }
56117  }
56118  *pRes = 0;
56119  return rc;
56120}
56121
56122/*
56123** Allocate a new page from the database file.
56124**
56125** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
56126** has already been called on the new page.)  The new page has also
56127** been referenced and the calling routine is responsible for calling
56128** sqlite3PagerUnref() on the new page when it is done.
56129**
56130** SQLITE_OK is returned on success.  Any other return value indicates
56131** an error.  *ppPage and *pPgno are undefined in the event of an error.
56132** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
56133**
56134** If the "nearby" parameter is not 0, then an effort is made to
56135** locate a page close to the page number "nearby".  This can be used in an
56136** attempt to keep related pages close to each other in the database file,
56137** which in turn can make database access faster.
56138**
56139** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
56140** anywhere on the free-list, then it is guaranteed to be returned.  If
56141** eMode is BTALLOC_LT then the page returned will be less than or equal
56142** to nearby if any such page exists.  If eMode is BTALLOC_ANY then there
56143** are no restrictions on which page is returned.
56144*/
56145static int allocateBtreePage(
56146  BtShared *pBt,         /* The btree */
56147  MemPage **ppPage,      /* Store pointer to the allocated page here */
56148  Pgno *pPgno,           /* Store the page number here */
56149  Pgno nearby,           /* Search for a page near this one */
56150  u8 eMode               /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
56151){
56152  MemPage *pPage1;
56153  int rc;
56154  u32 n;     /* Number of pages on the freelist */
56155  u32 k;     /* Number of leaves on the trunk of the freelist */
56156  MemPage *pTrunk = 0;
56157  MemPage *pPrevTrunk = 0;
56158  Pgno mxPage;     /* Total size of the database file */
56159
56160  assert( sqlite3_mutex_held(pBt->mutex) );
56161  assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
56162  pPage1 = pBt->pPage1;
56163  mxPage = btreePagecount(pBt);
56164  n = get4byte(&pPage1->aData[36]);
56165  testcase( n==mxPage-1 );
56166  if( n>=mxPage ){
56167    return SQLITE_CORRUPT_BKPT;
56168  }
56169  if( n>0 ){
56170    /* There are pages on the freelist.  Reuse one of those pages. */
56171    Pgno iTrunk;
56172    u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
56173
56174    /* If eMode==BTALLOC_EXACT and a query of the pointer-map
56175    ** shows that the page 'nearby' is somewhere on the free-list, then
56176    ** the entire-list will be searched for that page.
56177    */
56178#ifndef SQLITE_OMIT_AUTOVACUUM
56179    if( eMode==BTALLOC_EXACT ){
56180      if( nearby<=mxPage ){
56181        u8 eType;
56182        assert( nearby>0 );
56183        assert( pBt->autoVacuum );
56184        rc = ptrmapGet(pBt, nearby, &eType, 0);
56185        if( rc ) return rc;
56186        if( eType==PTRMAP_FREEPAGE ){
56187          searchList = 1;
56188        }
56189      }
56190    }else if( eMode==BTALLOC_LE ){
56191      searchList = 1;
56192    }
56193#endif
56194
56195    /* Decrement the free-list count by 1. Set iTrunk to the index of the
56196    ** first free-list trunk page. iPrevTrunk is initially 1.
56197    */
56198    rc = sqlite3PagerWrite(pPage1->pDbPage);
56199    if( rc ) return rc;
56200    put4byte(&pPage1->aData[36], n-1);
56201
56202    /* The code within this loop is run only once if the 'searchList' variable
56203    ** is not true. Otherwise, it runs once for each trunk-page on the
56204    ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
56205    ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
56206    */
56207    do {
56208      pPrevTrunk = pTrunk;
56209      if( pPrevTrunk ){
56210        iTrunk = get4byte(&pPrevTrunk->aData[0]);
56211      }else{
56212        iTrunk = get4byte(&pPage1->aData[32]);
56213      }
56214      testcase( iTrunk==mxPage );
56215      if( iTrunk>mxPage ){
56216        rc = SQLITE_CORRUPT_BKPT;
56217      }else{
56218        rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
56219      }
56220      if( rc ){
56221        pTrunk = 0;
56222        goto end_allocate_page;
56223      }
56224      assert( pTrunk!=0 );
56225      assert( pTrunk->aData!=0 );
56226
56227      k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
56228      if( k==0 && !searchList ){
56229        /* The trunk has no leaves and the list is not being searched.
56230        ** So extract the trunk page itself and use it as the newly
56231        ** allocated page */
56232        assert( pPrevTrunk==0 );
56233        rc = sqlite3PagerWrite(pTrunk->pDbPage);
56234        if( rc ){
56235          goto end_allocate_page;
56236        }
56237        *pPgno = iTrunk;
56238        memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
56239        *ppPage = pTrunk;
56240        pTrunk = 0;
56241        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
56242      }else if( k>(u32)(pBt->usableSize/4 - 2) ){
56243        /* Value of k is out of range.  Database corruption */
56244        rc = SQLITE_CORRUPT_BKPT;
56245        goto end_allocate_page;
56246#ifndef SQLITE_OMIT_AUTOVACUUM
56247      }else if( searchList
56248            && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
56249      ){
56250        /* The list is being searched and this trunk page is the page
56251        ** to allocate, regardless of whether it has leaves.
56252        */
56253        *pPgno = iTrunk;
56254        *ppPage = pTrunk;
56255        searchList = 0;
56256        rc = sqlite3PagerWrite(pTrunk->pDbPage);
56257        if( rc ){
56258          goto end_allocate_page;
56259        }
56260        if( k==0 ){
56261          if( !pPrevTrunk ){
56262            memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
56263          }else{
56264            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
56265            if( rc!=SQLITE_OK ){
56266              goto end_allocate_page;
56267            }
56268            memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
56269          }
56270        }else{
56271          /* The trunk page is required by the caller but it contains
56272          ** pointers to free-list leaves. The first leaf becomes a trunk
56273          ** page in this case.
56274          */
56275          MemPage *pNewTrunk;
56276          Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
56277          if( iNewTrunk>mxPage ){
56278            rc = SQLITE_CORRUPT_BKPT;
56279            goto end_allocate_page;
56280          }
56281          testcase( iNewTrunk==mxPage );
56282          rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
56283          if( rc!=SQLITE_OK ){
56284            goto end_allocate_page;
56285          }
56286          rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
56287          if( rc!=SQLITE_OK ){
56288            releasePage(pNewTrunk);
56289            goto end_allocate_page;
56290          }
56291          memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
56292          put4byte(&pNewTrunk->aData[4], k-1);
56293          memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
56294          releasePage(pNewTrunk);
56295          if( !pPrevTrunk ){
56296            assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
56297            put4byte(&pPage1->aData[32], iNewTrunk);
56298          }else{
56299            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
56300            if( rc ){
56301              goto end_allocate_page;
56302            }
56303            put4byte(&pPrevTrunk->aData[0], iNewTrunk);
56304          }
56305        }
56306        pTrunk = 0;
56307        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
56308#endif
56309      }else if( k>0 ){
56310        /* Extract a leaf from the trunk */
56311        u32 closest;
56312        Pgno iPage;
56313        unsigned char *aData = pTrunk->aData;
56314        if( nearby>0 ){
56315          u32 i;
56316          closest = 0;
56317          if( eMode==BTALLOC_LE ){
56318            for(i=0; i<k; i++){
56319              iPage = get4byte(&aData[8+i*4]);
56320              if( iPage<=nearby ){
56321                closest = i;
56322                break;
56323              }
56324            }
56325          }else{
56326            int dist;
56327            dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
56328            for(i=1; i<k; i++){
56329              int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
56330              if( d2<dist ){
56331                closest = i;
56332                dist = d2;
56333              }
56334            }
56335          }
56336        }else{
56337          closest = 0;
56338        }
56339
56340        iPage = get4byte(&aData[8+closest*4]);
56341        testcase( iPage==mxPage );
56342        if( iPage>mxPage ){
56343          rc = SQLITE_CORRUPT_BKPT;
56344          goto end_allocate_page;
56345        }
56346        testcase( iPage==mxPage );
56347        if( !searchList
56348         || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
56349        ){
56350          int noContent;
56351          *pPgno = iPage;
56352          TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
56353                 ": %d more free pages\n",
56354                 *pPgno, closest+1, k, pTrunk->pgno, n-1));
56355          rc = sqlite3PagerWrite(pTrunk->pDbPage);
56356          if( rc ) goto end_allocate_page;
56357          if( closest<k-1 ){
56358            memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
56359          }
56360          put4byte(&aData[4], k-1);
56361          noContent = !btreeGetHasContent(pBt, *pPgno) ? PAGER_GET_NOCONTENT : 0;
56362          rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
56363          if( rc==SQLITE_OK ){
56364            rc = sqlite3PagerWrite((*ppPage)->pDbPage);
56365            if( rc!=SQLITE_OK ){
56366              releasePage(*ppPage);
56367            }
56368          }
56369          searchList = 0;
56370        }
56371      }
56372      releasePage(pPrevTrunk);
56373      pPrevTrunk = 0;
56374    }while( searchList );
56375  }else{
56376    /* There are no pages on the freelist, so append a new page to the
56377    ** database image.
56378    **
56379    ** Normally, new pages allocated by this block can be requested from the
56380    ** pager layer with the 'no-content' flag set. This prevents the pager
56381    ** from trying to read the pages content from disk. However, if the
56382    ** current transaction has already run one or more incremental-vacuum
56383    ** steps, then the page we are about to allocate may contain content
56384    ** that is required in the event of a rollback. In this case, do
56385    ** not set the no-content flag. This causes the pager to load and journal
56386    ** the current page content before overwriting it.
56387    **
56388    ** Note that the pager will not actually attempt to load or journal
56389    ** content for any page that really does lie past the end of the database
56390    ** file on disk. So the effects of disabling the no-content optimization
56391    ** here are confined to those pages that lie between the end of the
56392    ** database image and the end of the database file.
56393    */
56394    int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate)) ? PAGER_GET_NOCONTENT : 0;
56395
56396    rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
56397    if( rc ) return rc;
56398    pBt->nPage++;
56399    if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
56400
56401#ifndef SQLITE_OMIT_AUTOVACUUM
56402    if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
56403      /* If *pPgno refers to a pointer-map page, allocate two new pages
56404      ** at the end of the file instead of one. The first allocated page
56405      ** becomes a new pointer-map page, the second is used by the caller.
56406      */
56407      MemPage *pPg = 0;
56408      TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
56409      assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
56410      rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent);
56411      if( rc==SQLITE_OK ){
56412        rc = sqlite3PagerWrite(pPg->pDbPage);
56413        releasePage(pPg);
56414      }
56415      if( rc ) return rc;
56416      pBt->nPage++;
56417      if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
56418    }
56419#endif
56420    put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
56421    *pPgno = pBt->nPage;
56422
56423    assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
56424    rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent);
56425    if( rc ) return rc;
56426    rc = sqlite3PagerWrite((*ppPage)->pDbPage);
56427    if( rc!=SQLITE_OK ){
56428      releasePage(*ppPage);
56429    }
56430    TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
56431  }
56432
56433  assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
56434
56435end_allocate_page:
56436  releasePage(pTrunk);
56437  releasePage(pPrevTrunk);
56438  if( rc==SQLITE_OK ){
56439    if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
56440      releasePage(*ppPage);
56441      *ppPage = 0;
56442      return SQLITE_CORRUPT_BKPT;
56443    }
56444    (*ppPage)->isInit = 0;
56445  }else{
56446    *ppPage = 0;
56447  }
56448  assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
56449  return rc;
56450}
56451
56452/*
56453** This function is used to add page iPage to the database file free-list.
56454** It is assumed that the page is not already a part of the free-list.
56455**
56456** The value passed as the second argument to this function is optional.
56457** If the caller happens to have a pointer to the MemPage object
56458** corresponding to page iPage handy, it may pass it as the second value.
56459** Otherwise, it may pass NULL.
56460**
56461** If a pointer to a MemPage object is passed as the second argument,
56462** its reference count is not altered by this function.
56463*/
56464static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
56465  MemPage *pTrunk = 0;                /* Free-list trunk page */
56466  Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
56467  MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
56468  MemPage *pPage;                     /* Page being freed. May be NULL. */
56469  int rc;                             /* Return Code */
56470  int nFree;                          /* Initial number of pages on free-list */
56471
56472  assert( sqlite3_mutex_held(pBt->mutex) );
56473  assert( iPage>1 );
56474  assert( !pMemPage || pMemPage->pgno==iPage );
56475
56476  if( pMemPage ){
56477    pPage = pMemPage;
56478    sqlite3PagerRef(pPage->pDbPage);
56479  }else{
56480    pPage = btreePageLookup(pBt, iPage);
56481  }
56482
56483  /* Increment the free page count on pPage1 */
56484  rc = sqlite3PagerWrite(pPage1->pDbPage);
56485  if( rc ) goto freepage_out;
56486  nFree = get4byte(&pPage1->aData[36]);
56487  put4byte(&pPage1->aData[36], nFree+1);
56488
56489  if( pBt->btsFlags & BTS_SECURE_DELETE ){
56490    /* If the secure_delete option is enabled, then
56491    ** always fully overwrite deleted information with zeros.
56492    */
56493    if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
56494     ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
56495    ){
56496      goto freepage_out;
56497    }
56498    memset(pPage->aData, 0, pPage->pBt->pageSize);
56499  }
56500
56501  /* If the database supports auto-vacuum, write an entry in the pointer-map
56502  ** to indicate that the page is free.
56503  */
56504  if( ISAUTOVACUUM ){
56505    ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
56506    if( rc ) goto freepage_out;
56507  }
56508
56509  /* Now manipulate the actual database free-list structure. There are two
56510  ** possibilities. If the free-list is currently empty, or if the first
56511  ** trunk page in the free-list is full, then this page will become a
56512  ** new free-list trunk page. Otherwise, it will become a leaf of the
56513  ** first trunk page in the current free-list. This block tests if it
56514  ** is possible to add the page as a new free-list leaf.
56515  */
56516  if( nFree!=0 ){
56517    u32 nLeaf;                /* Initial number of leaf cells on trunk page */
56518
56519    iTrunk = get4byte(&pPage1->aData[32]);
56520    rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
56521    if( rc!=SQLITE_OK ){
56522      goto freepage_out;
56523    }
56524
56525    nLeaf = get4byte(&pTrunk->aData[4]);
56526    assert( pBt->usableSize>32 );
56527    if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
56528      rc = SQLITE_CORRUPT_BKPT;
56529      goto freepage_out;
56530    }
56531    if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
56532      /* In this case there is room on the trunk page to insert the page
56533      ** being freed as a new leaf.
56534      **
56535      ** Note that the trunk page is not really full until it contains
56536      ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
56537      ** coded.  But due to a coding error in versions of SQLite prior to
56538      ** 3.6.0, databases with freelist trunk pages holding more than
56539      ** usableSize/4 - 8 entries will be reported as corrupt.  In order
56540      ** to maintain backwards compatibility with older versions of SQLite,
56541      ** we will continue to restrict the number of entries to usableSize/4 - 8
56542      ** for now.  At some point in the future (once everyone has upgraded
56543      ** to 3.6.0 or later) we should consider fixing the conditional above
56544      ** to read "usableSize/4-2" instead of "usableSize/4-8".
56545      */
56546      rc = sqlite3PagerWrite(pTrunk->pDbPage);
56547      if( rc==SQLITE_OK ){
56548        put4byte(&pTrunk->aData[4], nLeaf+1);
56549        put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
56550        if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
56551          sqlite3PagerDontWrite(pPage->pDbPage);
56552        }
56553        rc = btreeSetHasContent(pBt, iPage);
56554      }
56555      TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
56556      goto freepage_out;
56557    }
56558  }
56559
56560  /* If control flows to this point, then it was not possible to add the
56561  ** the page being freed as a leaf page of the first trunk in the free-list.
56562  ** Possibly because the free-list is empty, or possibly because the
56563  ** first trunk in the free-list is full. Either way, the page being freed
56564  ** will become the new first trunk page in the free-list.
56565  */
56566  if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
56567    goto freepage_out;
56568  }
56569  rc = sqlite3PagerWrite(pPage->pDbPage);
56570  if( rc!=SQLITE_OK ){
56571    goto freepage_out;
56572  }
56573  put4byte(pPage->aData, iTrunk);
56574  put4byte(&pPage->aData[4], 0);
56575  put4byte(&pPage1->aData[32], iPage);
56576  TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
56577
56578freepage_out:
56579  if( pPage ){
56580    pPage->isInit = 0;
56581  }
56582  releasePage(pPage);
56583  releasePage(pTrunk);
56584  return rc;
56585}
56586static void freePage(MemPage *pPage, int *pRC){
56587  if( (*pRC)==SQLITE_OK ){
56588    *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
56589  }
56590}
56591
56592/*
56593** Free any overflow pages associated with the given Cell.
56594*/
56595static int clearCell(MemPage *pPage, unsigned char *pCell){
56596  BtShared *pBt = pPage->pBt;
56597  CellInfo info;
56598  Pgno ovflPgno;
56599  int rc;
56600  int nOvfl;
56601  u32 ovflPageSize;
56602
56603  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
56604  btreeParseCellPtr(pPage, pCell, &info);
56605  if( info.iOverflow==0 ){
56606    return SQLITE_OK;  /* No overflow pages. Return without doing anything */
56607  }
56608  if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
56609    return SQLITE_CORRUPT_BKPT;  /* Cell extends past end of page */
56610  }
56611  ovflPgno = get4byte(&pCell[info.iOverflow]);
56612  assert( pBt->usableSize > 4 );
56613  ovflPageSize = pBt->usableSize - 4;
56614  nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
56615  assert( ovflPgno==0 || nOvfl>0 );
56616  while( nOvfl-- ){
56617    Pgno iNext = 0;
56618    MemPage *pOvfl = 0;
56619    if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
56620      /* 0 is not a legal page number and page 1 cannot be an
56621      ** overflow page. Therefore if ovflPgno<2 or past the end of the
56622      ** file the database must be corrupt. */
56623      return SQLITE_CORRUPT_BKPT;
56624    }
56625    if( nOvfl ){
56626      rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
56627      if( rc ) return rc;
56628    }
56629
56630    if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
56631     && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
56632    ){
56633      /* There is no reason any cursor should have an outstanding reference
56634      ** to an overflow page belonging to a cell that is being deleted/updated.
56635      ** So if there exists more than one reference to this page, then it
56636      ** must not really be an overflow page and the database must be corrupt.
56637      ** It is helpful to detect this before calling freePage2(), as
56638      ** freePage2() may zero the page contents if secure-delete mode is
56639      ** enabled. If this 'overflow' page happens to be a page that the
56640      ** caller is iterating through or using in some other way, this
56641      ** can be problematic.
56642      */
56643      rc = SQLITE_CORRUPT_BKPT;
56644    }else{
56645      rc = freePage2(pBt, pOvfl, ovflPgno);
56646    }
56647
56648    if( pOvfl ){
56649      sqlite3PagerUnref(pOvfl->pDbPage);
56650    }
56651    if( rc ) return rc;
56652    ovflPgno = iNext;
56653  }
56654  return SQLITE_OK;
56655}
56656
56657/*
56658** Create the byte sequence used to represent a cell on page pPage
56659** and write that byte sequence into pCell[].  Overflow pages are
56660** allocated and filled in as necessary.  The calling procedure
56661** is responsible for making sure sufficient space has been allocated
56662** for pCell[].
56663**
56664** Note that pCell does not necessary need to point to the pPage->aData
56665** area.  pCell might point to some temporary storage.  The cell will
56666** be constructed in this temporary area then copied into pPage->aData
56667** later.
56668*/
56669static int fillInCell(
56670  MemPage *pPage,                /* The page that contains the cell */
56671  unsigned char *pCell,          /* Complete text of the cell */
56672  const void *pKey, i64 nKey,    /* The key */
56673  const void *pData,int nData,   /* The data */
56674  int nZero,                     /* Extra zero bytes to append to pData */
56675  int *pnSize                    /* Write cell size here */
56676){
56677  int nPayload;
56678  const u8 *pSrc;
56679  int nSrc, n, rc;
56680  int spaceLeft;
56681  MemPage *pOvfl = 0;
56682  MemPage *pToRelease = 0;
56683  unsigned char *pPrior;
56684  unsigned char *pPayload;
56685  BtShared *pBt = pPage->pBt;
56686  Pgno pgnoOvfl = 0;
56687  int nHeader;
56688  CellInfo info;
56689
56690  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
56691
56692  /* pPage is not necessarily writeable since pCell might be auxiliary
56693  ** buffer space that is separate from the pPage buffer area */
56694  assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
56695            || sqlite3PagerIswriteable(pPage->pDbPage) );
56696
56697  /* Fill in the header. */
56698  nHeader = 0;
56699  if( !pPage->leaf ){
56700    nHeader += 4;
56701  }
56702  if( pPage->hasData ){
56703    nHeader += putVarint32(&pCell[nHeader], nData+nZero);
56704  }else{
56705    nData = nZero = 0;
56706  }
56707  nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
56708  btreeParseCellPtr(pPage, pCell, &info);
56709  assert( info.nHeader==nHeader );
56710  assert( info.nKey==nKey );
56711  assert( info.nData==(u32)(nData+nZero) );
56712
56713  /* Fill in the payload */
56714  nPayload = nData + nZero;
56715  if( pPage->intKey ){
56716    pSrc = pData;
56717    nSrc = nData;
56718    nData = 0;
56719  }else{
56720    if( NEVER(nKey>0x7fffffff || pKey==0) ){
56721      return SQLITE_CORRUPT_BKPT;
56722    }
56723    nPayload += (int)nKey;
56724    pSrc = pKey;
56725    nSrc = (int)nKey;
56726  }
56727  *pnSize = info.nSize;
56728  spaceLeft = info.nLocal;
56729  pPayload = &pCell[nHeader];
56730  pPrior = &pCell[info.iOverflow];
56731
56732  while( nPayload>0 ){
56733    if( spaceLeft==0 ){
56734#ifndef SQLITE_OMIT_AUTOVACUUM
56735      Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
56736      if( pBt->autoVacuum ){
56737        do{
56738          pgnoOvfl++;
56739        } while(
56740          PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
56741        );
56742      }
56743#endif
56744      rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
56745#ifndef SQLITE_OMIT_AUTOVACUUM
56746      /* If the database supports auto-vacuum, and the second or subsequent
56747      ** overflow page is being allocated, add an entry to the pointer-map
56748      ** for that page now.
56749      **
56750      ** If this is the first overflow page, then write a partial entry
56751      ** to the pointer-map. If we write nothing to this pointer-map slot,
56752      ** then the optimistic overflow chain processing in clearCell()
56753      ** may misinterpret the uninitialized values and delete the
56754      ** wrong pages from the database.
56755      */
56756      if( pBt->autoVacuum && rc==SQLITE_OK ){
56757        u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
56758        ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
56759        if( rc ){
56760          releasePage(pOvfl);
56761        }
56762      }
56763#endif
56764      if( rc ){
56765        releasePage(pToRelease);
56766        return rc;
56767      }
56768
56769      /* If pToRelease is not zero than pPrior points into the data area
56770      ** of pToRelease.  Make sure pToRelease is still writeable. */
56771      assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
56772
56773      /* If pPrior is part of the data area of pPage, then make sure pPage
56774      ** is still writeable */
56775      assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
56776            || sqlite3PagerIswriteable(pPage->pDbPage) );
56777
56778      put4byte(pPrior, pgnoOvfl);
56779      releasePage(pToRelease);
56780      pToRelease = pOvfl;
56781      pPrior = pOvfl->aData;
56782      put4byte(pPrior, 0);
56783      pPayload = &pOvfl->aData[4];
56784      spaceLeft = pBt->usableSize - 4;
56785    }
56786    n = nPayload;
56787    if( n>spaceLeft ) n = spaceLeft;
56788
56789    /* If pToRelease is not zero than pPayload points into the data area
56790    ** of pToRelease.  Make sure pToRelease is still writeable. */
56791    assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
56792
56793    /* If pPayload is part of the data area of pPage, then make sure pPage
56794    ** is still writeable */
56795    assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
56796            || sqlite3PagerIswriteable(pPage->pDbPage) );
56797
56798    if( nSrc>0 ){
56799      if( n>nSrc ) n = nSrc;
56800      assert( pSrc );
56801      memcpy(pPayload, pSrc, n);
56802    }else{
56803      memset(pPayload, 0, n);
56804    }
56805    nPayload -= n;
56806    pPayload += n;
56807    pSrc += n;
56808    nSrc -= n;
56809    spaceLeft -= n;
56810    if( nSrc==0 ){
56811      nSrc = nData;
56812      pSrc = pData;
56813    }
56814  }
56815  releasePage(pToRelease);
56816  return SQLITE_OK;
56817}
56818
56819/*
56820** Remove the i-th cell from pPage.  This routine effects pPage only.
56821** The cell content is not freed or deallocated.  It is assumed that
56822** the cell content has been copied someplace else.  This routine just
56823** removes the reference to the cell from pPage.
56824**
56825** "sz" must be the number of bytes in the cell.
56826*/
56827static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
56828  u32 pc;         /* Offset to cell content of cell being deleted */
56829  u8 *data;       /* pPage->aData */
56830  u8 *ptr;        /* Used to move bytes around within data[] */
56831  int rc;         /* The return code */
56832  int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
56833
56834  if( *pRC ) return;
56835
56836  assert( idx>=0 && idx<pPage->nCell );
56837  assert( sz==cellSize(pPage, idx) );
56838  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
56839  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
56840  data = pPage->aData;
56841  ptr = &pPage->aCellIdx[2*idx];
56842  pc = get2byte(ptr);
56843  hdr = pPage->hdrOffset;
56844  testcase( pc==get2byte(&data[hdr+5]) );
56845  testcase( pc+sz==pPage->pBt->usableSize );
56846  if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
56847    *pRC = SQLITE_CORRUPT_BKPT;
56848    return;
56849  }
56850  rc = freeSpace(pPage, pc, sz);
56851  if( rc ){
56852    *pRC = rc;
56853    return;
56854  }
56855  pPage->nCell--;
56856  memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
56857  put2byte(&data[hdr+3], pPage->nCell);
56858  pPage->nFree += 2;
56859}
56860
56861/*
56862** Insert a new cell on pPage at cell index "i".  pCell points to the
56863** content of the cell.
56864**
56865** If the cell content will fit on the page, then put it there.  If it
56866** will not fit, then make a copy of the cell content into pTemp if
56867** pTemp is not null.  Regardless of pTemp, allocate a new entry
56868** in pPage->apOvfl[] and make it point to the cell content (either
56869** in pTemp or the original pCell) and also record its index.
56870** Allocating a new entry in pPage->aCell[] implies that
56871** pPage->nOverflow is incremented.
56872**
56873** If nSkip is non-zero, then do not copy the first nSkip bytes of the
56874** cell. The caller will overwrite them after this function returns. If
56875** nSkip is non-zero, then pCell may not point to an invalid memory location
56876** (but pCell+nSkip is always valid).
56877*/
56878static void insertCell(
56879  MemPage *pPage,   /* Page into which we are copying */
56880  int i,            /* New cell becomes the i-th cell of the page */
56881  u8 *pCell,        /* Content of the new cell */
56882  int sz,           /* Bytes of content in pCell */
56883  u8 *pTemp,        /* Temp storage space for pCell, if needed */
56884  Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
56885  int *pRC          /* Read and write return code from here */
56886){
56887  int idx = 0;      /* Where to write new cell content in data[] */
56888  int j;            /* Loop counter */
56889  int end;          /* First byte past the last cell pointer in data[] */
56890  int ins;          /* Index in data[] where new cell pointer is inserted */
56891  int cellOffset;   /* Address of first cell pointer in data[] */
56892  u8 *data;         /* The content of the whole page */
56893  int nSkip = (iChild ? 4 : 0);
56894
56895  if( *pRC ) return;
56896
56897  assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
56898  assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
56899  assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
56900  assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
56901  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
56902  /* The cell should normally be sized correctly.  However, when moving a
56903  ** malformed cell from a leaf page to an interior page, if the cell size
56904  ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
56905  ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
56906  ** the term after the || in the following assert(). */
56907  assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
56908  if( pPage->nOverflow || sz+2>pPage->nFree ){
56909    if( pTemp ){
56910      memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
56911      pCell = pTemp;
56912    }
56913    if( iChild ){
56914      put4byte(pCell, iChild);
56915    }
56916    j = pPage->nOverflow++;
56917    assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
56918    pPage->apOvfl[j] = pCell;
56919    pPage->aiOvfl[j] = (u16)i;
56920  }else{
56921    int rc = sqlite3PagerWrite(pPage->pDbPage);
56922    if( rc!=SQLITE_OK ){
56923      *pRC = rc;
56924      return;
56925    }
56926    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
56927    data = pPage->aData;
56928    cellOffset = pPage->cellOffset;
56929    end = cellOffset + 2*pPage->nCell;
56930    ins = cellOffset + 2*i;
56931    rc = allocateSpace(pPage, sz, &idx);
56932    if( rc ){ *pRC = rc; return; }
56933    /* The allocateSpace() routine guarantees the following two properties
56934    ** if it returns success */
56935    assert( idx >= end+2 );
56936    assert( idx+sz <= (int)pPage->pBt->usableSize );
56937    pPage->nCell++;
56938    pPage->nFree -= (u16)(2 + sz);
56939    memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
56940    if( iChild ){
56941      put4byte(&data[idx], iChild);
56942    }
56943    memmove(&data[ins+2], &data[ins], end-ins);
56944    put2byte(&data[ins], idx);
56945    put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
56946#ifndef SQLITE_OMIT_AUTOVACUUM
56947    if( pPage->pBt->autoVacuum ){
56948      /* The cell may contain a pointer to an overflow page. If so, write
56949      ** the entry for the overflow page into the pointer map.
56950      */
56951      ptrmapPutOvflPtr(pPage, pCell, pRC);
56952    }
56953#endif
56954  }
56955}
56956
56957/*
56958** Add a list of cells to a page.  The page should be initially empty.
56959** The cells are guaranteed to fit on the page.
56960*/
56961static void assemblePage(
56962  MemPage *pPage,   /* The page to be assemblied */
56963  int nCell,        /* The number of cells to add to this page */
56964  u8 **apCell,      /* Pointers to cell bodies */
56965  u16 *aSize        /* Sizes of the cells */
56966){
56967  int i;            /* Loop counter */
56968  u8 *pCellptr;     /* Address of next cell pointer */
56969  int cellbody;     /* Address of next cell body */
56970  u8 * const data = pPage->aData;             /* Pointer to data for pPage */
56971  const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
56972  const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
56973
56974  assert( pPage->nOverflow==0 );
56975  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
56976  assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
56977            && (int)MX_CELL(pPage->pBt)<=10921);
56978  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
56979
56980  /* Check that the page has just been zeroed by zeroPage() */
56981  assert( pPage->nCell==0 );
56982  assert( get2byteNotZero(&data[hdr+5])==nUsable );
56983
56984  pCellptr = &pPage->aCellIdx[nCell*2];
56985  cellbody = nUsable;
56986  for(i=nCell-1; i>=0; i--){
56987    u16 sz = aSize[i];
56988    pCellptr -= 2;
56989    cellbody -= sz;
56990    put2byte(pCellptr, cellbody);
56991    memcpy(&data[cellbody], apCell[i], sz);
56992  }
56993  put2byte(&data[hdr+3], nCell);
56994  put2byte(&data[hdr+5], cellbody);
56995  pPage->nFree -= (nCell*2 + nUsable - cellbody);
56996  pPage->nCell = (u16)nCell;
56997}
56998
56999/*
57000** The following parameters determine how many adjacent pages get involved
57001** in a balancing operation.  NN is the number of neighbors on either side
57002** of the page that participate in the balancing operation.  NB is the
57003** total number of pages that participate, including the target page and
57004** NN neighbors on either side.
57005**
57006** The minimum value of NN is 1 (of course).  Increasing NN above 1
57007** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
57008** in exchange for a larger degradation in INSERT and UPDATE performance.
57009** The value of NN appears to give the best results overall.
57010*/
57011#define NN 1             /* Number of neighbors on either side of pPage */
57012#define NB (NN*2+1)      /* Total pages involved in the balance */
57013
57014
57015#ifndef SQLITE_OMIT_QUICKBALANCE
57016/*
57017** This version of balance() handles the common special case where
57018** a new entry is being inserted on the extreme right-end of the
57019** tree, in other words, when the new entry will become the largest
57020** entry in the tree.
57021**
57022** Instead of trying to balance the 3 right-most leaf pages, just add
57023** a new page to the right-hand side and put the one new entry in
57024** that page.  This leaves the right side of the tree somewhat
57025** unbalanced.  But odds are that we will be inserting new entries
57026** at the end soon afterwards so the nearly empty page will quickly
57027** fill up.  On average.
57028**
57029** pPage is the leaf page which is the right-most page in the tree.
57030** pParent is its parent.  pPage must have a single overflow entry
57031** which is also the right-most entry on the page.
57032**
57033** The pSpace buffer is used to store a temporary copy of the divider
57034** cell that will be inserted into pParent. Such a cell consists of a 4
57035** byte page number followed by a variable length integer. In other
57036** words, at most 13 bytes. Hence the pSpace buffer must be at
57037** least 13 bytes in size.
57038*/
57039static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
57040  BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
57041  MemPage *pNew;                       /* Newly allocated page */
57042  int rc;                              /* Return Code */
57043  Pgno pgnoNew;                        /* Page number of pNew */
57044
57045  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
57046  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
57047  assert( pPage->nOverflow==1 );
57048
57049  /* This error condition is now caught prior to reaching this function */
57050  if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;
57051
57052  /* Allocate a new page. This page will become the right-sibling of
57053  ** pPage. Make the parent page writable, so that the new divider cell
57054  ** may be inserted. If both these operations are successful, proceed.
57055  */
57056  rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
57057
57058  if( rc==SQLITE_OK ){
57059
57060    u8 *pOut = &pSpace[4];
57061    u8 *pCell = pPage->apOvfl[0];
57062    u16 szCell = cellSizePtr(pPage, pCell);
57063    u8 *pStop;
57064
57065    assert( sqlite3PagerIswriteable(pNew->pDbPage) );
57066    assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
57067    zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
57068    assemblePage(pNew, 1, &pCell, &szCell);
57069
57070    /* If this is an auto-vacuum database, update the pointer map
57071    ** with entries for the new page, and any pointer from the
57072    ** cell on the page to an overflow page. If either of these
57073    ** operations fails, the return code is set, but the contents
57074    ** of the parent page are still manipulated by thh code below.
57075    ** That is Ok, at this point the parent page is guaranteed to
57076    ** be marked as dirty. Returning an error code will cause a
57077    ** rollback, undoing any changes made to the parent page.
57078    */
57079    if( ISAUTOVACUUM ){
57080      ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
57081      if( szCell>pNew->minLocal ){
57082        ptrmapPutOvflPtr(pNew, pCell, &rc);
57083      }
57084    }
57085
57086    /* Create a divider cell to insert into pParent. The divider cell
57087    ** consists of a 4-byte page number (the page number of pPage) and
57088    ** a variable length key value (which must be the same value as the
57089    ** largest key on pPage).
57090    **
57091    ** To find the largest key value on pPage, first find the right-most
57092    ** cell on pPage. The first two fields of this cell are the
57093    ** record-length (a variable length integer at most 32-bits in size)
57094    ** and the key value (a variable length integer, may have any value).
57095    ** The first of the while(...) loops below skips over the record-length
57096    ** field. The second while(...) loop copies the key value from the
57097    ** cell on pPage into the pSpace buffer.
57098    */
57099    pCell = findCell(pPage, pPage->nCell-1);
57100    pStop = &pCell[9];
57101    while( (*(pCell++)&0x80) && pCell<pStop );
57102    pStop = &pCell[9];
57103    while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
57104
57105    /* Insert the new divider cell into pParent. */
57106    insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
57107               0, pPage->pgno, &rc);
57108
57109    /* Set the right-child pointer of pParent to point to the new page. */
57110    put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
57111
57112    /* Release the reference to the new page. */
57113    releasePage(pNew);
57114  }
57115
57116  return rc;
57117}
57118#endif /* SQLITE_OMIT_QUICKBALANCE */
57119
57120#if 0
57121/*
57122** This function does not contribute anything to the operation of SQLite.
57123** it is sometimes activated temporarily while debugging code responsible
57124** for setting pointer-map entries.
57125*/
57126static int ptrmapCheckPages(MemPage **apPage, int nPage){
57127  int i, j;
57128  for(i=0; i<nPage; i++){
57129    Pgno n;
57130    u8 e;
57131    MemPage *pPage = apPage[i];
57132    BtShared *pBt = pPage->pBt;
57133    assert( pPage->isInit );
57134
57135    for(j=0; j<pPage->nCell; j++){
57136      CellInfo info;
57137      u8 *z;
57138
57139      z = findCell(pPage, j);
57140      btreeParseCellPtr(pPage, z, &info);
57141      if( info.iOverflow ){
57142        Pgno ovfl = get4byte(&z[info.iOverflow]);
57143        ptrmapGet(pBt, ovfl, &e, &n);
57144        assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
57145      }
57146      if( !pPage->leaf ){
57147        Pgno child = get4byte(z);
57148        ptrmapGet(pBt, child, &e, &n);
57149        assert( n==pPage->pgno && e==PTRMAP_BTREE );
57150      }
57151    }
57152    if( !pPage->leaf ){
57153      Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
57154      ptrmapGet(pBt, child, &e, &n);
57155      assert( n==pPage->pgno && e==PTRMAP_BTREE );
57156    }
57157  }
57158  return 1;
57159}
57160#endif
57161
57162/*
57163** This function is used to copy the contents of the b-tree node stored
57164** on page pFrom to page pTo. If page pFrom was not a leaf page, then
57165** the pointer-map entries for each child page are updated so that the
57166** parent page stored in the pointer map is page pTo. If pFrom contained
57167** any cells with overflow page pointers, then the corresponding pointer
57168** map entries are also updated so that the parent page is page pTo.
57169**
57170** If pFrom is currently carrying any overflow cells (entries in the
57171** MemPage.apOvfl[] array), they are not copied to pTo.
57172**
57173** Before returning, page pTo is reinitialized using btreeInitPage().
57174**
57175** The performance of this function is not critical. It is only used by
57176** the balance_shallower() and balance_deeper() procedures, neither of
57177** which are called often under normal circumstances.
57178*/
57179static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
57180  if( (*pRC)==SQLITE_OK ){
57181    BtShared * const pBt = pFrom->pBt;
57182    u8 * const aFrom = pFrom->aData;
57183    u8 * const aTo = pTo->aData;
57184    int const iFromHdr = pFrom->hdrOffset;
57185    int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
57186    int rc;
57187    int iData;
57188
57189
57190    assert( pFrom->isInit );
57191    assert( pFrom->nFree>=iToHdr );
57192    assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
57193
57194    /* Copy the b-tree node content from page pFrom to page pTo. */
57195    iData = get2byte(&aFrom[iFromHdr+5]);
57196    memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
57197    memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
57198
57199    /* Reinitialize page pTo so that the contents of the MemPage structure
57200    ** match the new data. The initialization of pTo can actually fail under
57201    ** fairly obscure circumstances, even though it is a copy of initialized
57202    ** page pFrom.
57203    */
57204    pTo->isInit = 0;
57205    rc = btreeInitPage(pTo);
57206    if( rc!=SQLITE_OK ){
57207      *pRC = rc;
57208      return;
57209    }
57210
57211    /* If this is an auto-vacuum database, update the pointer-map entries
57212    ** for any b-tree or overflow pages that pTo now contains the pointers to.
57213    */
57214    if( ISAUTOVACUUM ){
57215      *pRC = setChildPtrmaps(pTo);
57216    }
57217  }
57218}
57219
57220/*
57221** This routine redistributes cells on the iParentIdx'th child of pParent
57222** (hereafter "the page") and up to 2 siblings so that all pages have about the
57223** same amount of free space. Usually a single sibling on either side of the
57224** page are used in the balancing, though both siblings might come from one
57225** side if the page is the first or last child of its parent. If the page
57226** has fewer than 2 siblings (something which can only happen if the page
57227** is a root page or a child of a root page) then all available siblings
57228** participate in the balancing.
57229**
57230** The number of siblings of the page might be increased or decreased by
57231** one or two in an effort to keep pages nearly full but not over full.
57232**
57233** Note that when this routine is called, some of the cells on the page
57234** might not actually be stored in MemPage.aData[]. This can happen
57235** if the page is overfull. This routine ensures that all cells allocated
57236** to the page and its siblings fit into MemPage.aData[] before returning.
57237**
57238** In the course of balancing the page and its siblings, cells may be
57239** inserted into or removed from the parent page (pParent). Doing so
57240** may cause the parent page to become overfull or underfull. If this
57241** happens, it is the responsibility of the caller to invoke the correct
57242** balancing routine to fix this problem (see the balance() routine).
57243**
57244** If this routine fails for any reason, it might leave the database
57245** in a corrupted state. So if this routine fails, the database should
57246** be rolled back.
57247**
57248** The third argument to this function, aOvflSpace, is a pointer to a
57249** buffer big enough to hold one page. If while inserting cells into the parent
57250** page (pParent) the parent page becomes overfull, this buffer is
57251** used to store the parent's overflow cells. Because this function inserts
57252** a maximum of four divider cells into the parent page, and the maximum
57253** size of a cell stored within an internal node is always less than 1/4
57254** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
57255** enough for all overflow cells.
57256**
57257** If aOvflSpace is set to a null pointer, this function returns
57258** SQLITE_NOMEM.
57259*/
57260#if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
57261#pragma optimize("", off)
57262#endif
57263static int balance_nonroot(
57264  MemPage *pParent,               /* Parent page of siblings being balanced */
57265  int iParentIdx,                 /* Index of "the page" in pParent */
57266  u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
57267  int isRoot,                     /* True if pParent is a root-page */
57268  int bBulk                       /* True if this call is part of a bulk load */
57269){
57270  BtShared *pBt;               /* The whole database */
57271  int nCell = 0;               /* Number of cells in apCell[] */
57272  int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
57273  int nNew = 0;                /* Number of pages in apNew[] */
57274  int nOld;                    /* Number of pages in apOld[] */
57275  int i, j, k;                 /* Loop counters */
57276  int nxDiv;                   /* Next divider slot in pParent->aCell[] */
57277  int rc = SQLITE_OK;          /* The return code */
57278  u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
57279  int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
57280  int usableSpace;             /* Bytes in pPage beyond the header */
57281  int pageFlags;               /* Value of pPage->aData[0] */
57282  int subtotal;                /* Subtotal of bytes in cells on one page */
57283  int iSpace1 = 0;             /* First unused byte of aSpace1[] */
57284  int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
57285  int szScratch;               /* Size of scratch memory requested */
57286  MemPage *apOld[NB];          /* pPage and up to two siblings */
57287  MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
57288  MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
57289  u8 *pRight;                  /* Location in parent of right-sibling pointer */
57290  u8 *apDiv[NB-1];             /* Divider cells in pParent */
57291  int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
57292  int szNew[NB+2];             /* Combined size of cells place on i-th page */
57293  u8 **apCell = 0;             /* All cells begin balanced */
57294  u16 *szCell;                 /* Local size of all cells in apCell[] */
57295  u8 *aSpace1;                 /* Space for copies of dividers cells */
57296  Pgno pgno;                   /* Temp var to store a page number in */
57297
57298  pBt = pParent->pBt;
57299  assert( sqlite3_mutex_held(pBt->mutex) );
57300  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
57301
57302#if 0
57303  TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
57304#endif
57305
57306  /* At this point pParent may have at most one overflow cell. And if
57307  ** this overflow cell is present, it must be the cell with
57308  ** index iParentIdx. This scenario comes about when this function
57309  ** is called (indirectly) from sqlite3BtreeDelete().
57310  */
57311  assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
57312  assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
57313
57314  if( !aOvflSpace ){
57315    return SQLITE_NOMEM;
57316  }
57317
57318  /* Find the sibling pages to balance. Also locate the cells in pParent
57319  ** that divide the siblings. An attempt is made to find NN siblings on
57320  ** either side of pPage. More siblings are taken from one side, however,
57321  ** if there are fewer than NN siblings on the other side. If pParent
57322  ** has NB or fewer children then all children of pParent are taken.
57323  **
57324  ** This loop also drops the divider cells from the parent page. This
57325  ** way, the remainder of the function does not have to deal with any
57326  ** overflow cells in the parent page, since if any existed they will
57327  ** have already been removed.
57328  */
57329  i = pParent->nOverflow + pParent->nCell;
57330  if( i<2 ){
57331    nxDiv = 0;
57332  }else{
57333    assert( bBulk==0 || bBulk==1 );
57334    if( iParentIdx==0 ){
57335      nxDiv = 0;
57336    }else if( iParentIdx==i ){
57337      nxDiv = i-2+bBulk;
57338    }else{
57339      assert( bBulk==0 );
57340      nxDiv = iParentIdx-1;
57341    }
57342    i = 2-bBulk;
57343  }
57344  nOld = i+1;
57345  if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
57346    pRight = &pParent->aData[pParent->hdrOffset+8];
57347  }else{
57348    pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
57349  }
57350  pgno = get4byte(pRight);
57351  while( 1 ){
57352    rc = getAndInitPage(pBt, pgno, &apOld[i], 0);
57353    if( rc ){
57354      memset(apOld, 0, (i+1)*sizeof(MemPage*));
57355      goto balance_cleanup;
57356    }
57357    nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
57358    if( (i--)==0 ) break;
57359
57360    if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
57361      apDiv[i] = pParent->apOvfl[0];
57362      pgno = get4byte(apDiv[i]);
57363      szNew[i] = cellSizePtr(pParent, apDiv[i]);
57364      pParent->nOverflow = 0;
57365    }else{
57366      apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
57367      pgno = get4byte(apDiv[i]);
57368      szNew[i] = cellSizePtr(pParent, apDiv[i]);
57369
57370      /* Drop the cell from the parent page. apDiv[i] still points to
57371      ** the cell within the parent, even though it has been dropped.
57372      ** This is safe because dropping a cell only overwrites the first
57373      ** four bytes of it, and this function does not need the first
57374      ** four bytes of the divider cell. So the pointer is safe to use
57375      ** later on.
57376      **
57377      ** But not if we are in secure-delete mode. In secure-delete mode,
57378      ** the dropCell() routine will overwrite the entire cell with zeroes.
57379      ** In this case, temporarily copy the cell into the aOvflSpace[]
57380      ** buffer. It will be copied out again as soon as the aSpace[] buffer
57381      ** is allocated.  */
57382      if( pBt->btsFlags & BTS_SECURE_DELETE ){
57383        int iOff;
57384
57385        iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
57386        if( (iOff+szNew[i])>(int)pBt->usableSize ){
57387          rc = SQLITE_CORRUPT_BKPT;
57388          memset(apOld, 0, (i+1)*sizeof(MemPage*));
57389          goto balance_cleanup;
57390        }else{
57391          memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
57392          apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
57393        }
57394      }
57395      dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
57396    }
57397  }
57398
57399  /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
57400  ** alignment */
57401  nMaxCells = (nMaxCells + 3)&~3;
57402
57403  /*
57404  ** Allocate space for memory structures
57405  */
57406  k = pBt->pageSize + ROUND8(sizeof(MemPage));
57407  szScratch =
57408       nMaxCells*sizeof(u8*)                       /* apCell */
57409     + nMaxCells*sizeof(u16)                       /* szCell */
57410     + pBt->pageSize                               /* aSpace1 */
57411     + k*nOld;                                     /* Page copies (apCopy) */
57412  apCell = sqlite3ScratchMalloc( szScratch );
57413  if( apCell==0 ){
57414    rc = SQLITE_NOMEM;
57415    goto balance_cleanup;
57416  }
57417  szCell = (u16*)&apCell[nMaxCells];
57418  aSpace1 = (u8*)&szCell[nMaxCells];
57419  assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
57420
57421  /*
57422  ** Load pointers to all cells on sibling pages and the divider cells
57423  ** into the local apCell[] array.  Make copies of the divider cells
57424  ** into space obtained from aSpace1[] and remove the divider cells
57425  ** from pParent.
57426  **
57427  ** If the siblings are on leaf pages, then the child pointers of the
57428  ** divider cells are stripped from the cells before they are copied
57429  ** into aSpace1[].  In this way, all cells in apCell[] are without
57430  ** child pointers.  If siblings are not leaves, then all cell in
57431  ** apCell[] include child pointers.  Either way, all cells in apCell[]
57432  ** are alike.
57433  **
57434  ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
57435  **       leafData:  1 if pPage holds key+data and pParent holds only keys.
57436  */
57437  leafCorrection = apOld[0]->leaf*4;
57438  leafData = apOld[0]->hasData;
57439  for(i=0; i<nOld; i++){
57440    int limit;
57441
57442    /* Before doing anything else, take a copy of the i'th original sibling
57443    ** The rest of this function will use data from the copies rather
57444    ** that the original pages since the original pages will be in the
57445    ** process of being overwritten.  */
57446    MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
57447    memcpy(pOld, apOld[i], sizeof(MemPage));
57448    pOld->aData = (void*)&pOld[1];
57449    memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
57450
57451    limit = pOld->nCell+pOld->nOverflow;
57452    if( pOld->nOverflow>0 ){
57453      for(j=0; j<limit; j++){
57454        assert( nCell<nMaxCells );
57455        apCell[nCell] = findOverflowCell(pOld, j);
57456        szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
57457        nCell++;
57458      }
57459    }else{
57460      u8 *aData = pOld->aData;
57461      u16 maskPage = pOld->maskPage;
57462      u16 cellOffset = pOld->cellOffset;
57463      for(j=0; j<limit; j++){
57464        assert( nCell<nMaxCells );
57465        apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
57466        szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
57467        nCell++;
57468      }
57469    }
57470    if( i<nOld-1 && !leafData){
57471      u16 sz = (u16)szNew[i];
57472      u8 *pTemp;
57473      assert( nCell<nMaxCells );
57474      szCell[nCell] = sz;
57475      pTemp = &aSpace1[iSpace1];
57476      iSpace1 += sz;
57477      assert( sz<=pBt->maxLocal+23 );
57478      assert( iSpace1 <= (int)pBt->pageSize );
57479      memcpy(pTemp, apDiv[i], sz);
57480      apCell[nCell] = pTemp+leafCorrection;
57481      assert( leafCorrection==0 || leafCorrection==4 );
57482      szCell[nCell] = szCell[nCell] - leafCorrection;
57483      if( !pOld->leaf ){
57484        assert( leafCorrection==0 );
57485        assert( pOld->hdrOffset==0 );
57486        /* The right pointer of the child page pOld becomes the left
57487        ** pointer of the divider cell */
57488        memcpy(apCell[nCell], &pOld->aData[8], 4);
57489      }else{
57490        assert( leafCorrection==4 );
57491        if( szCell[nCell]<4 ){
57492          /* Do not allow any cells smaller than 4 bytes. */
57493          szCell[nCell] = 4;
57494        }
57495      }
57496      nCell++;
57497    }
57498  }
57499
57500  /*
57501  ** Figure out the number of pages needed to hold all nCell cells.
57502  ** Store this number in "k".  Also compute szNew[] which is the total
57503  ** size of all cells on the i-th page and cntNew[] which is the index
57504  ** in apCell[] of the cell that divides page i from page i+1.
57505  ** cntNew[k] should equal nCell.
57506  **
57507  ** Values computed by this block:
57508  **
57509  **           k: The total number of sibling pages
57510  **    szNew[i]: Spaced used on the i-th sibling page.
57511  **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
57512  **              the right of the i-th sibling page.
57513  ** usableSpace: Number of bytes of space available on each sibling.
57514  **
57515  */
57516  usableSpace = pBt->usableSize - 12 + leafCorrection;
57517  for(subtotal=k=i=0; i<nCell; i++){
57518    assert( i<nMaxCells );
57519    subtotal += szCell[i] + 2;
57520    if( subtotal > usableSpace ){
57521      szNew[k] = subtotal - szCell[i];
57522      cntNew[k] = i;
57523      if( leafData ){ i--; }
57524      subtotal = 0;
57525      k++;
57526      if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
57527    }
57528  }
57529  szNew[k] = subtotal;
57530  cntNew[k] = nCell;
57531  k++;
57532
57533  /*
57534  ** The packing computed by the previous block is biased toward the siblings
57535  ** on the left side.  The left siblings are always nearly full, while the
57536  ** right-most sibling might be nearly empty.  This block of code attempts
57537  ** to adjust the packing of siblings to get a better balance.
57538  **
57539  ** This adjustment is more than an optimization.  The packing above might
57540  ** be so out of balance as to be illegal.  For example, the right-most
57541  ** sibling might be completely empty.  This adjustment is not optional.
57542  */
57543  for(i=k-1; i>0; i--){
57544    int szRight = szNew[i];  /* Size of sibling on the right */
57545    int szLeft = szNew[i-1]; /* Size of sibling on the left */
57546    int r;              /* Index of right-most cell in left sibling */
57547    int d;              /* Index of first cell to the left of right sibling */
57548
57549    r = cntNew[i-1] - 1;
57550    d = r + 1 - leafData;
57551    assert( d<nMaxCells );
57552    assert( r<nMaxCells );
57553    while( szRight==0
57554       || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2))
57555    ){
57556      szRight += szCell[d] + 2;
57557      szLeft -= szCell[r] + 2;
57558      cntNew[i-1]--;
57559      r = cntNew[i-1] - 1;
57560      d = r + 1 - leafData;
57561    }
57562    szNew[i] = szRight;
57563    szNew[i-1] = szLeft;
57564  }
57565
57566  /* Either we found one or more cells (cntnew[0])>0) or pPage is
57567  ** a virtual root page.  A virtual root page is when the real root
57568  ** page is page 1 and we are the only child of that page.
57569  **
57570  ** UPDATE:  The assert() below is not necessarily true if the database
57571  ** file is corrupt.  The corruption will be detected and reported later
57572  ** in this procedure so there is no need to act upon it now.
57573  */
57574#if 0
57575  assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
57576#endif
57577
57578  TRACE(("BALANCE: old: %d %d %d  ",
57579    apOld[0]->pgno,
57580    nOld>=2 ? apOld[1]->pgno : 0,
57581    nOld>=3 ? apOld[2]->pgno : 0
57582  ));
57583
57584  /*
57585  ** Allocate k new pages.  Reuse old pages where possible.
57586  */
57587  if( apOld[0]->pgno<=1 ){
57588    rc = SQLITE_CORRUPT_BKPT;
57589    goto balance_cleanup;
57590  }
57591  pageFlags = apOld[0]->aData[0];
57592  for(i=0; i<k; i++){
57593    MemPage *pNew;
57594    if( i<nOld ){
57595      pNew = apNew[i] = apOld[i];
57596      apOld[i] = 0;
57597      rc = sqlite3PagerWrite(pNew->pDbPage);
57598      nNew++;
57599      if( rc ) goto balance_cleanup;
57600    }else{
57601      assert( i>0 );
57602      rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
57603      if( rc ) goto balance_cleanup;
57604      apNew[i] = pNew;
57605      nNew++;
57606
57607      /* Set the pointer-map entry for the new sibling page. */
57608      if( ISAUTOVACUUM ){
57609        ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
57610        if( rc!=SQLITE_OK ){
57611          goto balance_cleanup;
57612        }
57613      }
57614    }
57615  }
57616
57617  /* Free any old pages that were not reused as new pages.
57618  */
57619  while( i<nOld ){
57620    freePage(apOld[i], &rc);
57621    if( rc ) goto balance_cleanup;
57622    releasePage(apOld[i]);
57623    apOld[i] = 0;
57624    i++;
57625  }
57626
57627  /*
57628  ** Put the new pages in accending order.  This helps to
57629  ** keep entries in the disk file in order so that a scan
57630  ** of the table is a linear scan through the file.  That
57631  ** in turn helps the operating system to deliver pages
57632  ** from the disk more rapidly.
57633  **
57634  ** An O(n^2) insertion sort algorithm is used, but since
57635  ** n is never more than NB (a small constant), that should
57636  ** not be a problem.
57637  **
57638  ** When NB==3, this one optimization makes the database
57639  ** about 25% faster for large insertions and deletions.
57640  */
57641  for(i=0; i<k-1; i++){
57642    int minV = apNew[i]->pgno;
57643    int minI = i;
57644    for(j=i+1; j<k; j++){
57645      if( apNew[j]->pgno<(unsigned)minV ){
57646        minI = j;
57647        minV = apNew[j]->pgno;
57648      }
57649    }
57650    if( minI>i ){
57651      MemPage *pT;
57652      pT = apNew[i];
57653      apNew[i] = apNew[minI];
57654      apNew[minI] = pT;
57655    }
57656  }
57657  TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
57658    apNew[0]->pgno, szNew[0],
57659    nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
57660    nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
57661    nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
57662    nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
57663
57664  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
57665  put4byte(pRight, apNew[nNew-1]->pgno);
57666
57667  /*
57668  ** Evenly distribute the data in apCell[] across the new pages.
57669  ** Insert divider cells into pParent as necessary.
57670  */
57671  j = 0;
57672  for(i=0; i<nNew; i++){
57673    /* Assemble the new sibling page. */
57674    MemPage *pNew = apNew[i];
57675    assert( j<nMaxCells );
57676    zeroPage(pNew, pageFlags);
57677    assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
57678    assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
57679    assert( pNew->nOverflow==0 );
57680
57681    j = cntNew[i];
57682
57683    /* If the sibling page assembled above was not the right-most sibling,
57684    ** insert a divider cell into the parent page.
57685    */
57686    assert( i<nNew-1 || j==nCell );
57687    if( j<nCell ){
57688      u8 *pCell;
57689      u8 *pTemp;
57690      int sz;
57691
57692      assert( j<nMaxCells );
57693      pCell = apCell[j];
57694      sz = szCell[j] + leafCorrection;
57695      pTemp = &aOvflSpace[iOvflSpace];
57696      if( !pNew->leaf ){
57697        memcpy(&pNew->aData[8], pCell, 4);
57698      }else if( leafData ){
57699        /* If the tree is a leaf-data tree, and the siblings are leaves,
57700        ** then there is no divider cell in apCell[]. Instead, the divider
57701        ** cell consists of the integer key for the right-most cell of
57702        ** the sibling-page assembled above only.
57703        */
57704        CellInfo info;
57705        j--;
57706        btreeParseCellPtr(pNew, apCell[j], &info);
57707        pCell = pTemp;
57708        sz = 4 + putVarint(&pCell[4], info.nKey);
57709        pTemp = 0;
57710      }else{
57711        pCell -= 4;
57712        /* Obscure case for non-leaf-data trees: If the cell at pCell was
57713        ** previously stored on a leaf node, and its reported size was 4
57714        ** bytes, then it may actually be smaller than this
57715        ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
57716        ** any cell). But it is important to pass the correct size to
57717        ** insertCell(), so reparse the cell now.
57718        **
57719        ** Note that this can never happen in an SQLite data file, as all
57720        ** cells are at least 4 bytes. It only happens in b-trees used
57721        ** to evaluate "IN (SELECT ...)" and similar clauses.
57722        */
57723        if( szCell[j]==4 ){
57724          assert(leafCorrection==4);
57725          sz = cellSizePtr(pParent, pCell);
57726        }
57727      }
57728      iOvflSpace += sz;
57729      assert( sz<=pBt->maxLocal+23 );
57730      assert( iOvflSpace <= (int)pBt->pageSize );
57731      insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
57732      if( rc!=SQLITE_OK ) goto balance_cleanup;
57733      assert( sqlite3PagerIswriteable(pParent->pDbPage) );
57734
57735      j++;
57736      nxDiv++;
57737    }
57738  }
57739  assert( j==nCell );
57740  assert( nOld>0 );
57741  assert( nNew>0 );
57742  if( (pageFlags & PTF_LEAF)==0 ){
57743    u8 *zChild = &apCopy[nOld-1]->aData[8];
57744    memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
57745  }
57746
57747  if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
57748    /* The root page of the b-tree now contains no cells. The only sibling
57749    ** page is the right-child of the parent. Copy the contents of the
57750    ** child page into the parent, decreasing the overall height of the
57751    ** b-tree structure by one. This is described as the "balance-shallower"
57752    ** sub-algorithm in some documentation.
57753    **
57754    ** If this is an auto-vacuum database, the call to copyNodeContent()
57755    ** sets all pointer-map entries corresponding to database image pages
57756    ** for which the pointer is stored within the content being copied.
57757    **
57758    ** The second assert below verifies that the child page is defragmented
57759    ** (it must be, as it was just reconstructed using assemblePage()). This
57760    ** is important if the parent page happens to be page 1 of the database
57761    ** image.  */
57762    assert( nNew==1 );
57763    assert( apNew[0]->nFree ==
57764        (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
57765    );
57766    copyNodeContent(apNew[0], pParent, &rc);
57767    freePage(apNew[0], &rc);
57768  }else if( ISAUTOVACUUM ){
57769    /* Fix the pointer-map entries for all the cells that were shifted around.
57770    ** There are several different types of pointer-map entries that need to
57771    ** be dealt with by this routine. Some of these have been set already, but
57772    ** many have not. The following is a summary:
57773    **
57774    **   1) The entries associated with new sibling pages that were not
57775    **      siblings when this function was called. These have already
57776    **      been set. We don't need to worry about old siblings that were
57777    **      moved to the free-list - the freePage() code has taken care
57778    **      of those.
57779    **
57780    **   2) The pointer-map entries associated with the first overflow
57781    **      page in any overflow chains used by new divider cells. These
57782    **      have also already been taken care of by the insertCell() code.
57783    **
57784    **   3) If the sibling pages are not leaves, then the child pages of
57785    **      cells stored on the sibling pages may need to be updated.
57786    **
57787    **   4) If the sibling pages are not internal intkey nodes, then any
57788    **      overflow pages used by these cells may need to be updated
57789    **      (internal intkey nodes never contain pointers to overflow pages).
57790    **
57791    **   5) If the sibling pages are not leaves, then the pointer-map
57792    **      entries for the right-child pages of each sibling may need
57793    **      to be updated.
57794    **
57795    ** Cases 1 and 2 are dealt with above by other code. The next
57796    ** block deals with cases 3 and 4 and the one after that, case 5. Since
57797    ** setting a pointer map entry is a relatively expensive operation, this
57798    ** code only sets pointer map entries for child or overflow pages that have
57799    ** actually moved between pages.  */
57800    MemPage *pNew = apNew[0];
57801    MemPage *pOld = apCopy[0];
57802    int nOverflow = pOld->nOverflow;
57803    int iNextOld = pOld->nCell + nOverflow;
57804    int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);
57805    j = 0;                             /* Current 'old' sibling page */
57806    k = 0;                             /* Current 'new' sibling page */
57807    for(i=0; i<nCell; i++){
57808      int isDivider = 0;
57809      while( i==iNextOld ){
57810        /* Cell i is the cell immediately following the last cell on old
57811        ** sibling page j. If the siblings are not leaf pages of an
57812        ** intkey b-tree, then cell i was a divider cell. */
57813        assert( j+1 < ArraySize(apCopy) );
57814        assert( j+1 < nOld );
57815        pOld = apCopy[++j];
57816        iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
57817        if( pOld->nOverflow ){
57818          nOverflow = pOld->nOverflow;
57819          iOverflow = i + !leafData + pOld->aiOvfl[0];
57820        }
57821        isDivider = !leafData;
57822      }
57823
57824      assert(nOverflow>0 || iOverflow<i );
57825      assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);
57826      assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);
57827      if( i==iOverflow ){
57828        isDivider = 1;
57829        if( (--nOverflow)>0 ){
57830          iOverflow++;
57831        }
57832      }
57833
57834      if( i==cntNew[k] ){
57835        /* Cell i is the cell immediately following the last cell on new
57836        ** sibling page k. If the siblings are not leaf pages of an
57837        ** intkey b-tree, then cell i is a divider cell.  */
57838        pNew = apNew[++k];
57839        if( !leafData ) continue;
57840      }
57841      assert( j<nOld );
57842      assert( k<nNew );
57843
57844      /* If the cell was originally divider cell (and is not now) or
57845      ** an overflow cell, or if the cell was located on a different sibling
57846      ** page before the balancing, then the pointer map entries associated
57847      ** with any child or overflow pages need to be updated.  */
57848      if( isDivider || pOld->pgno!=pNew->pgno ){
57849        if( !leafCorrection ){
57850          ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
57851        }
57852        if( szCell[i]>pNew->minLocal ){
57853          ptrmapPutOvflPtr(pNew, apCell[i], &rc);
57854        }
57855      }
57856    }
57857
57858    if( !leafCorrection ){
57859      for(i=0; i<nNew; i++){
57860        u32 key = get4byte(&apNew[i]->aData[8]);
57861        ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
57862      }
57863    }
57864
57865#if 0
57866    /* The ptrmapCheckPages() contains assert() statements that verify that
57867    ** all pointer map pages are set correctly. This is helpful while
57868    ** debugging. This is usually disabled because a corrupt database may
57869    ** cause an assert() statement to fail.  */
57870    ptrmapCheckPages(apNew, nNew);
57871    ptrmapCheckPages(&pParent, 1);
57872#endif
57873  }
57874
57875  assert( pParent->isInit );
57876  TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
57877          nOld, nNew, nCell));
57878
57879  /*
57880  ** Cleanup before returning.
57881  */
57882balance_cleanup:
57883  sqlite3ScratchFree(apCell);
57884  for(i=0; i<nOld; i++){
57885    releasePage(apOld[i]);
57886  }
57887  for(i=0; i<nNew; i++){
57888    releasePage(apNew[i]);
57889  }
57890
57891  return rc;
57892}
57893#if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
57894#pragma optimize("", on)
57895#endif
57896
57897
57898/*
57899** This function is called when the root page of a b-tree structure is
57900** overfull (has one or more overflow pages).
57901**
57902** A new child page is allocated and the contents of the current root
57903** page, including overflow cells, are copied into the child. The root
57904** page is then overwritten to make it an empty page with the right-child
57905** pointer pointing to the new page.
57906**
57907** Before returning, all pointer-map entries corresponding to pages
57908** that the new child-page now contains pointers to are updated. The
57909** entry corresponding to the new right-child pointer of the root
57910** page is also updated.
57911**
57912** If successful, *ppChild is set to contain a reference to the child
57913** page and SQLITE_OK is returned. In this case the caller is required
57914** to call releasePage() on *ppChild exactly once. If an error occurs,
57915** an error code is returned and *ppChild is set to 0.
57916*/
57917static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
57918  int rc;                        /* Return value from subprocedures */
57919  MemPage *pChild = 0;           /* Pointer to a new child page */
57920  Pgno pgnoChild = 0;            /* Page number of the new child page */
57921  BtShared *pBt = pRoot->pBt;    /* The BTree */
57922
57923  assert( pRoot->nOverflow>0 );
57924  assert( sqlite3_mutex_held(pBt->mutex) );
57925
57926  /* Make pRoot, the root page of the b-tree, writable. Allocate a new
57927  ** page that will become the new right-child of pPage. Copy the contents
57928  ** of the node stored on pRoot into the new child page.
57929  */
57930  rc = sqlite3PagerWrite(pRoot->pDbPage);
57931  if( rc==SQLITE_OK ){
57932    rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
57933    copyNodeContent(pRoot, pChild, &rc);
57934    if( ISAUTOVACUUM ){
57935      ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
57936    }
57937  }
57938  if( rc ){
57939    *ppChild = 0;
57940    releasePage(pChild);
57941    return rc;
57942  }
57943  assert( sqlite3PagerIswriteable(pChild->pDbPage) );
57944  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
57945  assert( pChild->nCell==pRoot->nCell );
57946
57947  TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
57948
57949  /* Copy the overflow cells from pRoot to pChild */
57950  memcpy(pChild->aiOvfl, pRoot->aiOvfl,
57951         pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
57952  memcpy(pChild->apOvfl, pRoot->apOvfl,
57953         pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
57954  pChild->nOverflow = pRoot->nOverflow;
57955
57956  /* Zero the contents of pRoot. Then install pChild as the right-child. */
57957  zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
57958  put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
57959
57960  *ppChild = pChild;
57961  return SQLITE_OK;
57962}
57963
57964/*
57965** The page that pCur currently points to has just been modified in
57966** some way. This function figures out if this modification means the
57967** tree needs to be balanced, and if so calls the appropriate balancing
57968** routine. Balancing routines are:
57969**
57970**   balance_quick()
57971**   balance_deeper()
57972**   balance_nonroot()
57973*/
57974static int balance(BtCursor *pCur){
57975  int rc = SQLITE_OK;
57976  const int nMin = pCur->pBt->usableSize * 2 / 3;
57977  u8 aBalanceQuickSpace[13];
57978  u8 *pFree = 0;
57979
57980  TESTONLY( int balance_quick_called = 0 );
57981  TESTONLY( int balance_deeper_called = 0 );
57982
57983  do {
57984    int iPage = pCur->iPage;
57985    MemPage *pPage = pCur->apPage[iPage];
57986
57987    if( iPage==0 ){
57988      if( pPage->nOverflow ){
57989        /* The root page of the b-tree is overfull. In this case call the
57990        ** balance_deeper() function to create a new child for the root-page
57991        ** and copy the current contents of the root-page to it. The
57992        ** next iteration of the do-loop will balance the child page.
57993        */
57994        assert( (balance_deeper_called++)==0 );
57995        rc = balance_deeper(pPage, &pCur->apPage[1]);
57996        if( rc==SQLITE_OK ){
57997          pCur->iPage = 1;
57998          pCur->aiIdx[0] = 0;
57999          pCur->aiIdx[1] = 0;
58000          assert( pCur->apPage[1]->nOverflow );
58001        }
58002      }else{
58003        break;
58004      }
58005    }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
58006      break;
58007    }else{
58008      MemPage * const pParent = pCur->apPage[iPage-1];
58009      int const iIdx = pCur->aiIdx[iPage-1];
58010
58011      rc = sqlite3PagerWrite(pParent->pDbPage);
58012      if( rc==SQLITE_OK ){
58013#ifndef SQLITE_OMIT_QUICKBALANCE
58014        if( pPage->hasData
58015         && pPage->nOverflow==1
58016         && pPage->aiOvfl[0]==pPage->nCell
58017         && pParent->pgno!=1
58018         && pParent->nCell==iIdx
58019        ){
58020          /* Call balance_quick() to create a new sibling of pPage on which
58021          ** to store the overflow cell. balance_quick() inserts a new cell
58022          ** into pParent, which may cause pParent overflow. If this
58023          ** happens, the next interation of the do-loop will balance pParent
58024          ** use either balance_nonroot() or balance_deeper(). Until this
58025          ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
58026          ** buffer.
58027          **
58028          ** The purpose of the following assert() is to check that only a
58029          ** single call to balance_quick() is made for each call to this
58030          ** function. If this were not verified, a subtle bug involving reuse
58031          ** of the aBalanceQuickSpace[] might sneak in.
58032          */
58033          assert( (balance_quick_called++)==0 );
58034          rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
58035        }else
58036#endif
58037        {
58038          /* In this case, call balance_nonroot() to redistribute cells
58039          ** between pPage and up to 2 of its sibling pages. This involves
58040          ** modifying the contents of pParent, which may cause pParent to
58041          ** become overfull or underfull. The next iteration of the do-loop
58042          ** will balance the parent page to correct this.
58043          **
58044          ** If the parent page becomes overfull, the overflow cell or cells
58045          ** are stored in the pSpace buffer allocated immediately below.
58046          ** A subsequent iteration of the do-loop will deal with this by
58047          ** calling balance_nonroot() (balance_deeper() may be called first,
58048          ** but it doesn't deal with overflow cells - just moves them to a
58049          ** different page). Once this subsequent call to balance_nonroot()
58050          ** has completed, it is safe to release the pSpace buffer used by
58051          ** the previous call, as the overflow cell data will have been
58052          ** copied either into the body of a database page or into the new
58053          ** pSpace buffer passed to the latter call to balance_nonroot().
58054          */
58055          u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
58056          rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints);
58057          if( pFree ){
58058            /* If pFree is not NULL, it points to the pSpace buffer used
58059            ** by a previous call to balance_nonroot(). Its contents are
58060            ** now stored either on real database pages or within the
58061            ** new pSpace buffer, so it may be safely freed here. */
58062            sqlite3PageFree(pFree);
58063          }
58064
58065          /* The pSpace buffer will be freed after the next call to
58066          ** balance_nonroot(), or just before this function returns, whichever
58067          ** comes first. */
58068          pFree = pSpace;
58069        }
58070      }
58071
58072      pPage->nOverflow = 0;
58073
58074      /* The next iteration of the do-loop balances the parent page. */
58075      releasePage(pPage);
58076      pCur->iPage--;
58077    }
58078  }while( rc==SQLITE_OK );
58079
58080  if( pFree ){
58081    sqlite3PageFree(pFree);
58082  }
58083  return rc;
58084}
58085
58086
58087/*
58088** Insert a new record into the BTree.  The key is given by (pKey,nKey)
58089** and the data is given by (pData,nData).  The cursor is used only to
58090** define what table the record should be inserted into.  The cursor
58091** is left pointing at a random location.
58092**
58093** For an INTKEY table, only the nKey value of the key is used.  pKey is
58094** ignored.  For a ZERODATA table, the pData and nData are both ignored.
58095**
58096** If the seekResult parameter is non-zero, then a successful call to
58097** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
58098** been performed. seekResult is the search result returned (a negative
58099** number if pCur points at an entry that is smaller than (pKey, nKey), or
58100** a positive value if pCur points at an etry that is larger than
58101** (pKey, nKey)).
58102**
58103** If the seekResult parameter is non-zero, then the caller guarantees that
58104** cursor pCur is pointing at the existing copy of a row that is to be
58105** overwritten.  If the seekResult parameter is 0, then cursor pCur may
58106** point to any entry or to no entry at all and so this function has to seek
58107** the cursor before the new key can be inserted.
58108*/
58109SQLITE_PRIVATE int sqlite3BtreeInsert(
58110  BtCursor *pCur,                /* Insert data into the table of this cursor */
58111  const void *pKey, i64 nKey,    /* The key of the new record */
58112  const void *pData, int nData,  /* The data of the new record */
58113  int nZero,                     /* Number of extra 0 bytes to append to data */
58114  int appendBias,                /* True if this is likely an append */
58115  int seekResult                 /* Result of prior MovetoUnpacked() call */
58116){
58117  int rc;
58118  int loc = seekResult;          /* -1: before desired location  +1: after */
58119  int szNew = 0;
58120  int idx;
58121  MemPage *pPage;
58122  Btree *p = pCur->pBtree;
58123  BtShared *pBt = p->pBt;
58124  unsigned char *oldCell;
58125  unsigned char *newCell = 0;
58126
58127  if( pCur->eState==CURSOR_FAULT ){
58128    assert( pCur->skipNext!=SQLITE_OK );
58129    return pCur->skipNext;
58130  }
58131
58132  assert( cursorHoldsMutex(pCur) );
58133  assert( (pCur->curFlags & BTCF_WriteFlag)!=0 && pBt->inTransaction==TRANS_WRITE
58134              && (pBt->btsFlags & BTS_READ_ONLY)==0 );
58135  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
58136
58137  /* Assert that the caller has been consistent. If this cursor was opened
58138  ** expecting an index b-tree, then the caller should be inserting blob
58139  ** keys with no associated data. If the cursor was opened expecting an
58140  ** intkey table, the caller should be inserting integer keys with a
58141  ** blob of associated data.  */
58142  assert( (pKey==0)==(pCur->pKeyInfo==0) );
58143
58144  /* Save the positions of any other cursors open on this table.
58145  **
58146  ** In some cases, the call to btreeMoveto() below is a no-op. For
58147  ** example, when inserting data into a table with auto-generated integer
58148  ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
58149  ** integer key to use. It then calls this function to actually insert the
58150  ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
58151  ** that the cursor is already where it needs to be and returns without
58152  ** doing any work. To avoid thwarting these optimizations, it is important
58153  ** not to clear the cursor here.
58154  */
58155  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
58156  if( rc ) return rc;
58157
58158  if( pCur->pKeyInfo==0 ){
58159    /* If this is an insert into a table b-tree, invalidate any incrblob
58160    ** cursors open on the row being replaced */
58161    invalidateIncrblobCursors(p, nKey, 0);
58162
58163    /* If the cursor is currently on the last row and we are appending a
58164    ** new row onto the end, set the "loc" to avoid an unnecessary btreeMoveto()
58165    ** call */
58166    if( (pCur->curFlags&BTCF_ValidNKey)!=0 && nKey>0 && pCur->info.nKey==nKey-1 ){
58167      loc = -1;
58168    }
58169  }
58170
58171  if( !loc ){
58172    rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
58173    if( rc ) return rc;
58174  }
58175  assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
58176
58177  pPage = pCur->apPage[pCur->iPage];
58178  assert( pPage->intKey || nKey>=0 );
58179  assert( pPage->leaf || !pPage->intKey );
58180
58181  TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
58182          pCur->pgnoRoot, nKey, nData, pPage->pgno,
58183          loc==0 ? "overwrite" : "new entry"));
58184  assert( pPage->isInit );
58185  allocateTempSpace(pBt);
58186  newCell = pBt->pTmpSpace;
58187  if( newCell==0 ) return SQLITE_NOMEM;
58188  rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
58189  if( rc ) goto end_insert;
58190  assert( szNew==cellSizePtr(pPage, newCell) );
58191  assert( szNew <= MX_CELL_SIZE(pBt) );
58192  idx = pCur->aiIdx[pCur->iPage];
58193  if( loc==0 ){
58194    u16 szOld;
58195    assert( idx<pPage->nCell );
58196    rc = sqlite3PagerWrite(pPage->pDbPage);
58197    if( rc ){
58198      goto end_insert;
58199    }
58200    oldCell = findCell(pPage, idx);
58201    if( !pPage->leaf ){
58202      memcpy(newCell, oldCell, 4);
58203    }
58204    szOld = cellSizePtr(pPage, oldCell);
58205    rc = clearCell(pPage, oldCell);
58206    dropCell(pPage, idx, szOld, &rc);
58207    if( rc ) goto end_insert;
58208  }else if( loc<0 && pPage->nCell>0 ){
58209    assert( pPage->leaf );
58210    idx = ++pCur->aiIdx[pCur->iPage];
58211  }else{
58212    assert( pPage->leaf );
58213  }
58214  insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
58215  assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
58216
58217  /* If no error has occurred and pPage has an overflow cell, call balance()
58218  ** to redistribute the cells within the tree. Since balance() may move
58219  ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
58220  ** variables.
58221  **
58222  ** Previous versions of SQLite called moveToRoot() to move the cursor
58223  ** back to the root page as balance() used to invalidate the contents
58224  ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
58225  ** set the cursor state to "invalid". This makes common insert operations
58226  ** slightly faster.
58227  **
58228  ** There is a subtle but important optimization here too. When inserting
58229  ** multiple records into an intkey b-tree using a single cursor (as can
58230  ** happen while processing an "INSERT INTO ... SELECT" statement), it
58231  ** is advantageous to leave the cursor pointing to the last entry in
58232  ** the b-tree if possible. If the cursor is left pointing to the last
58233  ** entry in the table, and the next row inserted has an integer key
58234  ** larger than the largest existing key, it is possible to insert the
58235  ** row without seeking the cursor. This can be a big performance boost.
58236  */
58237  pCur->info.nSize = 0;
58238  if( rc==SQLITE_OK && pPage->nOverflow ){
58239    pCur->curFlags &= ~(BTCF_ValidNKey);
58240    rc = balance(pCur);
58241
58242    /* Must make sure nOverflow is reset to zero even if the balance()
58243    ** fails. Internal data structure corruption will result otherwise.
58244    ** Also, set the cursor state to invalid. This stops saveCursorPosition()
58245    ** from trying to save the current position of the cursor.  */
58246    pCur->apPage[pCur->iPage]->nOverflow = 0;
58247    pCur->eState = CURSOR_INVALID;
58248  }
58249  assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
58250
58251end_insert:
58252  return rc;
58253}
58254
58255/*
58256** Delete the entry that the cursor is pointing to.  The cursor
58257** is left pointing at a arbitrary location.
58258*/
58259SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
58260  Btree *p = pCur->pBtree;
58261  BtShared *pBt = p->pBt;
58262  int rc;                              /* Return code */
58263  MemPage *pPage;                      /* Page to delete cell from */
58264  unsigned char *pCell;                /* Pointer to cell to delete */
58265  int iCellIdx;                        /* Index of cell to delete */
58266  int iCellDepth;                      /* Depth of node containing pCell */
58267
58268  assert( cursorHoldsMutex(pCur) );
58269  assert( pBt->inTransaction==TRANS_WRITE );
58270  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
58271  assert( pCur->curFlags & BTCF_WriteFlag );
58272  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
58273  assert( !hasReadConflicts(p, pCur->pgnoRoot) );
58274
58275  if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
58276   || NEVER(pCur->eState!=CURSOR_VALID)
58277  ){
58278    return SQLITE_ERROR;  /* Something has gone awry. */
58279  }
58280
58281  iCellDepth = pCur->iPage;
58282  iCellIdx = pCur->aiIdx[iCellDepth];
58283  pPage = pCur->apPage[iCellDepth];
58284  pCell = findCell(pPage, iCellIdx);
58285
58286  /* If the page containing the entry to delete is not a leaf page, move
58287  ** the cursor to the largest entry in the tree that is smaller than
58288  ** the entry being deleted. This cell will replace the cell being deleted
58289  ** from the internal node. The 'previous' entry is used for this instead
58290  ** of the 'next' entry, as the previous entry is always a part of the
58291  ** sub-tree headed by the child page of the cell being deleted. This makes
58292  ** balancing the tree following the delete operation easier.  */
58293  if( !pPage->leaf ){
58294    int notUsed = 0;
58295    rc = sqlite3BtreePrevious(pCur, &notUsed);
58296    if( rc ) return rc;
58297  }
58298
58299  /* Save the positions of any other cursors open on this table before
58300  ** making any modifications. Make the page containing the entry to be
58301  ** deleted writable. Then free any overflow pages associated with the
58302  ** entry and finally remove the cell itself from within the page.
58303  */
58304  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
58305  if( rc ) return rc;
58306
58307  /* If this is a delete operation to remove a row from a table b-tree,
58308  ** invalidate any incrblob cursors open on the row being deleted.  */
58309  if( pCur->pKeyInfo==0 ){
58310    invalidateIncrblobCursors(p, pCur->info.nKey, 0);
58311  }
58312
58313  rc = sqlite3PagerWrite(pPage->pDbPage);
58314  if( rc ) return rc;
58315  rc = clearCell(pPage, pCell);
58316  dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
58317  if( rc ) return rc;
58318
58319  /* If the cell deleted was not located on a leaf page, then the cursor
58320  ** is currently pointing to the largest entry in the sub-tree headed
58321  ** by the child-page of the cell that was just deleted from an internal
58322  ** node. The cell from the leaf node needs to be moved to the internal
58323  ** node to replace the deleted cell.  */
58324  if( !pPage->leaf ){
58325    MemPage *pLeaf = pCur->apPage[pCur->iPage];
58326    int nCell;
58327    Pgno n = pCur->apPage[iCellDepth+1]->pgno;
58328    unsigned char *pTmp;
58329
58330    pCell = findCell(pLeaf, pLeaf->nCell-1);
58331    nCell = cellSizePtr(pLeaf, pCell);
58332    assert( MX_CELL_SIZE(pBt) >= nCell );
58333
58334    allocateTempSpace(pBt);
58335    pTmp = pBt->pTmpSpace;
58336
58337    rc = sqlite3PagerWrite(pLeaf->pDbPage);
58338    insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
58339    dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
58340    if( rc ) return rc;
58341  }
58342
58343  /* Balance the tree. If the entry deleted was located on a leaf page,
58344  ** then the cursor still points to that page. In this case the first
58345  ** call to balance() repairs the tree, and the if(...) condition is
58346  ** never true.
58347  **
58348  ** Otherwise, if the entry deleted was on an internal node page, then
58349  ** pCur is pointing to the leaf page from which a cell was removed to
58350  ** replace the cell deleted from the internal node. This is slightly
58351  ** tricky as the leaf node may be underfull, and the internal node may
58352  ** be either under or overfull. In this case run the balancing algorithm
58353  ** on the leaf node first. If the balance proceeds far enough up the
58354  ** tree that we can be sure that any problem in the internal node has
58355  ** been corrected, so be it. Otherwise, after balancing the leaf node,
58356  ** walk the cursor up the tree to the internal node and balance it as
58357  ** well.  */
58358  rc = balance(pCur);
58359  if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
58360    while( pCur->iPage>iCellDepth ){
58361      releasePage(pCur->apPage[pCur->iPage--]);
58362    }
58363    rc = balance(pCur);
58364  }
58365
58366  if( rc==SQLITE_OK ){
58367    moveToRoot(pCur);
58368  }
58369  return rc;
58370}
58371
58372/*
58373** Create a new BTree table.  Write into *piTable the page
58374** number for the root page of the new table.
58375**
58376** The type of type is determined by the flags parameter.  Only the
58377** following values of flags are currently in use.  Other values for
58378** flags might not work:
58379**
58380**     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
58381**     BTREE_ZERODATA                  Used for SQL indices
58382*/
58383static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
58384  BtShared *pBt = p->pBt;
58385  MemPage *pRoot;
58386  Pgno pgnoRoot;
58387  int rc;
58388  int ptfFlags;          /* Page-type flage for the root page of new table */
58389
58390  assert( sqlite3BtreeHoldsMutex(p) );
58391  assert( pBt->inTransaction==TRANS_WRITE );
58392  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
58393
58394#ifdef SQLITE_OMIT_AUTOVACUUM
58395  rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
58396  if( rc ){
58397    return rc;
58398  }
58399#else
58400  if( pBt->autoVacuum ){
58401    Pgno pgnoMove;      /* Move a page here to make room for the root-page */
58402    MemPage *pPageMove; /* The page to move to. */
58403
58404    /* Creating a new table may probably require moving an existing database
58405    ** to make room for the new tables root page. In case this page turns
58406    ** out to be an overflow page, delete all overflow page-map caches
58407    ** held by open cursors.
58408    */
58409    invalidateAllOverflowCache(pBt);
58410
58411    /* Read the value of meta[3] from the database to determine where the
58412    ** root page of the new table should go. meta[3] is the largest root-page
58413    ** created so far, so the new root-page is (meta[3]+1).
58414    */
58415    sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
58416    pgnoRoot++;
58417
58418    /* The new root-page may not be allocated on a pointer-map page, or the
58419    ** PENDING_BYTE page.
58420    */
58421    while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
58422        pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
58423      pgnoRoot++;
58424    }
58425    assert( pgnoRoot>=3 );
58426
58427    /* Allocate a page. The page that currently resides at pgnoRoot will
58428    ** be moved to the allocated page (unless the allocated page happens
58429    ** to reside at pgnoRoot).
58430    */
58431    rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
58432    if( rc!=SQLITE_OK ){
58433      return rc;
58434    }
58435
58436    if( pgnoMove!=pgnoRoot ){
58437      /* pgnoRoot is the page that will be used for the root-page of
58438      ** the new table (assuming an error did not occur). But we were
58439      ** allocated pgnoMove. If required (i.e. if it was not allocated
58440      ** by extending the file), the current page at position pgnoMove
58441      ** is already journaled.
58442      */
58443      u8 eType = 0;
58444      Pgno iPtrPage = 0;
58445
58446      /* Save the positions of any open cursors. This is required in
58447      ** case they are holding a reference to an xFetch reference
58448      ** corresponding to page pgnoRoot.  */
58449      rc = saveAllCursors(pBt, 0, 0);
58450      releasePage(pPageMove);
58451      if( rc!=SQLITE_OK ){
58452        return rc;
58453      }
58454
58455      /* Move the page currently at pgnoRoot to pgnoMove. */
58456      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
58457      if( rc!=SQLITE_OK ){
58458        return rc;
58459      }
58460      rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
58461      if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
58462        rc = SQLITE_CORRUPT_BKPT;
58463      }
58464      if( rc!=SQLITE_OK ){
58465        releasePage(pRoot);
58466        return rc;
58467      }
58468      assert( eType!=PTRMAP_ROOTPAGE );
58469      assert( eType!=PTRMAP_FREEPAGE );
58470      rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
58471      releasePage(pRoot);
58472
58473      /* Obtain the page at pgnoRoot */
58474      if( rc!=SQLITE_OK ){
58475        return rc;
58476      }
58477      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
58478      if( rc!=SQLITE_OK ){
58479        return rc;
58480      }
58481      rc = sqlite3PagerWrite(pRoot->pDbPage);
58482      if( rc!=SQLITE_OK ){
58483        releasePage(pRoot);
58484        return rc;
58485      }
58486    }else{
58487      pRoot = pPageMove;
58488    }
58489
58490    /* Update the pointer-map and meta-data with the new root-page number. */
58491    ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
58492    if( rc ){
58493      releasePage(pRoot);
58494      return rc;
58495    }
58496
58497    /* When the new root page was allocated, page 1 was made writable in
58498    ** order either to increase the database filesize, or to decrement the
58499    ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
58500    */
58501    assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
58502    rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
58503    if( NEVER(rc) ){
58504      releasePage(pRoot);
58505      return rc;
58506    }
58507
58508  }else{
58509    rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
58510    if( rc ) return rc;
58511  }
58512#endif
58513  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
58514  if( createTabFlags & BTREE_INTKEY ){
58515    ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
58516  }else{
58517    ptfFlags = PTF_ZERODATA | PTF_LEAF;
58518  }
58519  zeroPage(pRoot, ptfFlags);
58520  sqlite3PagerUnref(pRoot->pDbPage);
58521  assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
58522  *piTable = (int)pgnoRoot;
58523  return SQLITE_OK;
58524}
58525SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
58526  int rc;
58527  sqlite3BtreeEnter(p);
58528  rc = btreeCreateTable(p, piTable, flags);
58529  sqlite3BtreeLeave(p);
58530  return rc;
58531}
58532
58533/*
58534** Erase the given database page and all its children.  Return
58535** the page to the freelist.
58536*/
58537static int clearDatabasePage(
58538  BtShared *pBt,           /* The BTree that contains the table */
58539  Pgno pgno,               /* Page number to clear */
58540  int freePageFlag,        /* Deallocate page if true */
58541  int *pnChange            /* Add number of Cells freed to this counter */
58542){
58543  MemPage *pPage;
58544  int rc;
58545  unsigned char *pCell;
58546  int i;
58547  int hdr;
58548
58549  assert( sqlite3_mutex_held(pBt->mutex) );
58550  if( pgno>btreePagecount(pBt) ){
58551    return SQLITE_CORRUPT_BKPT;
58552  }
58553
58554  rc = getAndInitPage(pBt, pgno, &pPage, 0);
58555  if( rc ) return rc;
58556  hdr = pPage->hdrOffset;
58557  for(i=0; i<pPage->nCell; i++){
58558    pCell = findCell(pPage, i);
58559    if( !pPage->leaf ){
58560      rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
58561      if( rc ) goto cleardatabasepage_out;
58562    }
58563    rc = clearCell(pPage, pCell);
58564    if( rc ) goto cleardatabasepage_out;
58565  }
58566  if( !pPage->leaf ){
58567    rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
58568    if( rc ) goto cleardatabasepage_out;
58569  }else if( pnChange ){
58570    assert( pPage->intKey );
58571    *pnChange += pPage->nCell;
58572  }
58573  if( freePageFlag ){
58574    freePage(pPage, &rc);
58575  }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
58576    zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
58577  }
58578
58579cleardatabasepage_out:
58580  releasePage(pPage);
58581  return rc;
58582}
58583
58584/*
58585** Delete all information from a single table in the database.  iTable is
58586** the page number of the root of the table.  After this routine returns,
58587** the root page is empty, but still exists.
58588**
58589** This routine will fail with SQLITE_LOCKED if there are any open
58590** read cursors on the table.  Open write cursors are moved to the
58591** root of the table.
58592**
58593** If pnChange is not NULL, then table iTable must be an intkey table. The
58594** integer value pointed to by pnChange is incremented by the number of
58595** entries in the table.
58596*/
58597SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
58598  int rc;
58599  BtShared *pBt = p->pBt;
58600  sqlite3BtreeEnter(p);
58601  assert( p->inTrans==TRANS_WRITE );
58602
58603  rc = saveAllCursors(pBt, (Pgno)iTable, 0);
58604
58605  if( SQLITE_OK==rc ){
58606    /* Invalidate all incrblob cursors open on table iTable (assuming iTable
58607    ** is the root of a table b-tree - if it is not, the following call is
58608    ** a no-op).  */
58609    invalidateIncrblobCursors(p, 0, 1);
58610    rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
58611  }
58612  sqlite3BtreeLeave(p);
58613  return rc;
58614}
58615
58616/*
58617** Delete all information from the single table that pCur is open on.
58618**
58619** This routine only work for pCur on an ephemeral table.
58620*/
58621SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
58622  return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
58623}
58624
58625/*
58626** Erase all information in a table and add the root of the table to
58627** the freelist.  Except, the root of the principle table (the one on
58628** page 1) is never added to the freelist.
58629**
58630** This routine will fail with SQLITE_LOCKED if there are any open
58631** cursors on the table.
58632**
58633** If AUTOVACUUM is enabled and the page at iTable is not the last
58634** root page in the database file, then the last root page
58635** in the database file is moved into the slot formerly occupied by
58636** iTable and that last slot formerly occupied by the last root page
58637** is added to the freelist instead of iTable.  In this say, all
58638** root pages are kept at the beginning of the database file, which
58639** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
58640** page number that used to be the last root page in the file before
58641** the move.  If no page gets moved, *piMoved is set to 0.
58642** The last root page is recorded in meta[3] and the value of
58643** meta[3] is updated by this procedure.
58644*/
58645static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
58646  int rc;
58647  MemPage *pPage = 0;
58648  BtShared *pBt = p->pBt;
58649
58650  assert( sqlite3BtreeHoldsMutex(p) );
58651  assert( p->inTrans==TRANS_WRITE );
58652
58653  /* It is illegal to drop a table if any cursors are open on the
58654  ** database. This is because in auto-vacuum mode the backend may
58655  ** need to move another root-page to fill a gap left by the deleted
58656  ** root page. If an open cursor was using this page a problem would
58657  ** occur.
58658  **
58659  ** This error is caught long before control reaches this point.
58660  */
58661  if( NEVER(pBt->pCursor) ){
58662    sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
58663    return SQLITE_LOCKED_SHAREDCACHE;
58664  }
58665
58666  rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
58667  if( rc ) return rc;
58668  rc = sqlite3BtreeClearTable(p, iTable, 0);
58669  if( rc ){
58670    releasePage(pPage);
58671    return rc;
58672  }
58673
58674  *piMoved = 0;
58675
58676  if( iTable>1 ){
58677#ifdef SQLITE_OMIT_AUTOVACUUM
58678    freePage(pPage, &rc);
58679    releasePage(pPage);
58680#else
58681    if( pBt->autoVacuum ){
58682      Pgno maxRootPgno;
58683      sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
58684
58685      if( iTable==maxRootPgno ){
58686        /* If the table being dropped is the table with the largest root-page
58687        ** number in the database, put the root page on the free list.
58688        */
58689        freePage(pPage, &rc);
58690        releasePage(pPage);
58691        if( rc!=SQLITE_OK ){
58692          return rc;
58693        }
58694      }else{
58695        /* The table being dropped does not have the largest root-page
58696        ** number in the database. So move the page that does into the
58697        ** gap left by the deleted root-page.
58698        */
58699        MemPage *pMove;
58700        releasePage(pPage);
58701        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
58702        if( rc!=SQLITE_OK ){
58703          return rc;
58704        }
58705        rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
58706        releasePage(pMove);
58707        if( rc!=SQLITE_OK ){
58708          return rc;
58709        }
58710        pMove = 0;
58711        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
58712        freePage(pMove, &rc);
58713        releasePage(pMove);
58714        if( rc!=SQLITE_OK ){
58715          return rc;
58716        }
58717        *piMoved = maxRootPgno;
58718      }
58719
58720      /* Set the new 'max-root-page' value in the database header. This
58721      ** is the old value less one, less one more if that happens to
58722      ** be a root-page number, less one again if that is the
58723      ** PENDING_BYTE_PAGE.
58724      */
58725      maxRootPgno--;
58726      while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
58727             || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
58728        maxRootPgno--;
58729      }
58730      assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
58731
58732      rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
58733    }else{
58734      freePage(pPage, &rc);
58735      releasePage(pPage);
58736    }
58737#endif
58738  }else{
58739    /* If sqlite3BtreeDropTable was called on page 1.
58740    ** This really never should happen except in a corrupt
58741    ** database.
58742    */
58743    zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
58744    releasePage(pPage);
58745  }
58746  return rc;
58747}
58748SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
58749  int rc;
58750  sqlite3BtreeEnter(p);
58751  rc = btreeDropTable(p, iTable, piMoved);
58752  sqlite3BtreeLeave(p);
58753  return rc;
58754}
58755
58756
58757/*
58758** This function may only be called if the b-tree connection already
58759** has a read or write transaction open on the database.
58760**
58761** Read the meta-information out of a database file.  Meta[0]
58762** is the number of free pages currently in the database.  Meta[1]
58763** through meta[15] are available for use by higher layers.  Meta[0]
58764** is read-only, the others are read/write.
58765**
58766** The schema layer numbers meta values differently.  At the schema
58767** layer (and the SetCookie and ReadCookie opcodes) the number of
58768** free pages is not visible.  So Cookie[0] is the same as Meta[1].
58769*/
58770SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
58771  BtShared *pBt = p->pBt;
58772
58773  sqlite3BtreeEnter(p);
58774  assert( p->inTrans>TRANS_NONE );
58775  assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
58776  assert( pBt->pPage1 );
58777  assert( idx>=0 && idx<=15 );
58778
58779  *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
58780
58781  /* If auto-vacuum is disabled in this build and this is an auto-vacuum
58782  ** database, mark the database as read-only.  */
58783#ifdef SQLITE_OMIT_AUTOVACUUM
58784  if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
58785    pBt->btsFlags |= BTS_READ_ONLY;
58786  }
58787#endif
58788
58789  sqlite3BtreeLeave(p);
58790}
58791
58792/*
58793** Write meta-information back into the database.  Meta[0] is
58794** read-only and may not be written.
58795*/
58796SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
58797  BtShared *pBt = p->pBt;
58798  unsigned char *pP1;
58799  int rc;
58800  assert( idx>=1 && idx<=15 );
58801  sqlite3BtreeEnter(p);
58802  assert( p->inTrans==TRANS_WRITE );
58803  assert( pBt->pPage1!=0 );
58804  pP1 = pBt->pPage1->aData;
58805  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
58806  if( rc==SQLITE_OK ){
58807    put4byte(&pP1[36 + idx*4], iMeta);
58808#ifndef SQLITE_OMIT_AUTOVACUUM
58809    if( idx==BTREE_INCR_VACUUM ){
58810      assert( pBt->autoVacuum || iMeta==0 );
58811      assert( iMeta==0 || iMeta==1 );
58812      pBt->incrVacuum = (u8)iMeta;
58813    }
58814#endif
58815  }
58816  sqlite3BtreeLeave(p);
58817  return rc;
58818}
58819
58820#ifndef SQLITE_OMIT_BTREECOUNT
58821/*
58822** The first argument, pCur, is a cursor opened on some b-tree. Count the
58823** number of entries in the b-tree and write the result to *pnEntry.
58824**
58825** SQLITE_OK is returned if the operation is successfully executed.
58826** Otherwise, if an error is encountered (i.e. an IO error or database
58827** corruption) an SQLite error code is returned.
58828*/
58829SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
58830  i64 nEntry = 0;                      /* Value to return in *pnEntry */
58831  int rc;                              /* Return code */
58832
58833  if( pCur->pgnoRoot==0 ){
58834    *pnEntry = 0;
58835    return SQLITE_OK;
58836  }
58837  rc = moveToRoot(pCur);
58838
58839  /* Unless an error occurs, the following loop runs one iteration for each
58840  ** page in the B-Tree structure (not including overflow pages).
58841  */
58842  while( rc==SQLITE_OK ){
58843    int iIdx;                          /* Index of child node in parent */
58844    MemPage *pPage;                    /* Current page of the b-tree */
58845
58846    /* If this is a leaf page or the tree is not an int-key tree, then
58847    ** this page contains countable entries. Increment the entry counter
58848    ** accordingly.
58849    */
58850    pPage = pCur->apPage[pCur->iPage];
58851    if( pPage->leaf || !pPage->intKey ){
58852      nEntry += pPage->nCell;
58853    }
58854
58855    /* pPage is a leaf node. This loop navigates the cursor so that it
58856    ** points to the first interior cell that it points to the parent of
58857    ** the next page in the tree that has not yet been visited. The
58858    ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
58859    ** of the page, or to the number of cells in the page if the next page
58860    ** to visit is the right-child of its parent.
58861    **
58862    ** If all pages in the tree have been visited, return SQLITE_OK to the
58863    ** caller.
58864    */
58865    if( pPage->leaf ){
58866      do {
58867        if( pCur->iPage==0 ){
58868          /* All pages of the b-tree have been visited. Return successfully. */
58869          *pnEntry = nEntry;
58870          return SQLITE_OK;
58871        }
58872        moveToParent(pCur);
58873      }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
58874
58875      pCur->aiIdx[pCur->iPage]++;
58876      pPage = pCur->apPage[pCur->iPage];
58877    }
58878
58879    /* Descend to the child node of the cell that the cursor currently
58880    ** points at. This is the right-child if (iIdx==pPage->nCell).
58881    */
58882    iIdx = pCur->aiIdx[pCur->iPage];
58883    if( iIdx==pPage->nCell ){
58884      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
58885    }else{
58886      rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
58887    }
58888  }
58889
58890  /* An error has occurred. Return an error code. */
58891  return rc;
58892}
58893#endif
58894
58895/*
58896** Return the pager associated with a BTree.  This routine is used for
58897** testing and debugging only.
58898*/
58899SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
58900  return p->pBt->pPager;
58901}
58902
58903#ifndef SQLITE_OMIT_INTEGRITY_CHECK
58904/*
58905** Append a message to the error message string.
58906*/
58907static void checkAppendMsg(
58908  IntegrityCk *pCheck,
58909  char *zMsg1,
58910  const char *zFormat,
58911  ...
58912){
58913  va_list ap;
58914  if( !pCheck->mxErr ) return;
58915  pCheck->mxErr--;
58916  pCheck->nErr++;
58917  va_start(ap, zFormat);
58918  if( pCheck->errMsg.nChar ){
58919    sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
58920  }
58921  if( zMsg1 ){
58922    sqlite3StrAccumAppendAll(&pCheck->errMsg, zMsg1);
58923  }
58924  sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
58925  va_end(ap);
58926  if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
58927    pCheck->mallocFailed = 1;
58928  }
58929}
58930#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
58931
58932#ifndef SQLITE_OMIT_INTEGRITY_CHECK
58933
58934/*
58935** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
58936** corresponds to page iPg is already set.
58937*/
58938static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
58939  assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
58940  return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
58941}
58942
58943/*
58944** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
58945*/
58946static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
58947  assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
58948  pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
58949}
58950
58951
58952/*
58953** Add 1 to the reference count for page iPage.  If this is the second
58954** reference to the page, add an error message to pCheck->zErrMsg.
58955** Return 1 if there are 2 ore more references to the page and 0 if
58956** if this is the first reference to the page.
58957**
58958** Also check that the page number is in bounds.
58959*/
58960static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
58961  if( iPage==0 ) return 1;
58962  if( iPage>pCheck->nPage ){
58963    checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
58964    return 1;
58965  }
58966  if( getPageReferenced(pCheck, iPage) ){
58967    checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
58968    return 1;
58969  }
58970  setPageReferenced(pCheck, iPage);
58971  return 0;
58972}
58973
58974#ifndef SQLITE_OMIT_AUTOVACUUM
58975/*
58976** Check that the entry in the pointer-map for page iChild maps to
58977** page iParent, pointer type ptrType. If not, append an error message
58978** to pCheck.
58979*/
58980static void checkPtrmap(
58981  IntegrityCk *pCheck,   /* Integrity check context */
58982  Pgno iChild,           /* Child page number */
58983  u8 eType,              /* Expected pointer map type */
58984  Pgno iParent,          /* Expected pointer map parent page number */
58985  char *zContext         /* Context description (used for error msg) */
58986){
58987  int rc;
58988  u8 ePtrmapType;
58989  Pgno iPtrmapParent;
58990
58991  rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
58992  if( rc!=SQLITE_OK ){
58993    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
58994    checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
58995    return;
58996  }
58997
58998  if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
58999    checkAppendMsg(pCheck, zContext,
59000      "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
59001      iChild, eType, iParent, ePtrmapType, iPtrmapParent);
59002  }
59003}
59004#endif
59005
59006/*
59007** Check the integrity of the freelist or of an overflow page list.
59008** Verify that the number of pages on the list is N.
59009*/
59010static void checkList(
59011  IntegrityCk *pCheck,  /* Integrity checking context */
59012  int isFreeList,       /* True for a freelist.  False for overflow page list */
59013  int iPage,            /* Page number for first page in the list */
59014  int N,                /* Expected number of pages in the list */
59015  char *zContext        /* Context for error messages */
59016){
59017  int i;
59018  int expected = N;
59019  int iFirst = iPage;
59020  while( N-- > 0 && pCheck->mxErr ){
59021    DbPage *pOvflPage;
59022    unsigned char *pOvflData;
59023    if( iPage<1 ){
59024      checkAppendMsg(pCheck, zContext,
59025         "%d of %d pages missing from overflow list starting at %d",
59026          N+1, expected, iFirst);
59027      break;
59028    }
59029    if( checkRef(pCheck, iPage, zContext) ) break;
59030    if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
59031      checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
59032      break;
59033    }
59034    pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
59035    if( isFreeList ){
59036      int n = get4byte(&pOvflData[4]);
59037#ifndef SQLITE_OMIT_AUTOVACUUM
59038      if( pCheck->pBt->autoVacuum ){
59039        checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
59040      }
59041#endif
59042      if( n>(int)pCheck->pBt->usableSize/4-2 ){
59043        checkAppendMsg(pCheck, zContext,
59044           "freelist leaf count too big on page %d", iPage);
59045        N--;
59046      }else{
59047        for(i=0; i<n; i++){
59048          Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
59049#ifndef SQLITE_OMIT_AUTOVACUUM
59050          if( pCheck->pBt->autoVacuum ){
59051            checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
59052          }
59053#endif
59054          checkRef(pCheck, iFreePage, zContext);
59055        }
59056        N -= n;
59057      }
59058    }
59059#ifndef SQLITE_OMIT_AUTOVACUUM
59060    else{
59061      /* If this database supports auto-vacuum and iPage is not the last
59062      ** page in this overflow list, check that the pointer-map entry for
59063      ** the following page matches iPage.
59064      */
59065      if( pCheck->pBt->autoVacuum && N>0 ){
59066        i = get4byte(pOvflData);
59067        checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
59068      }
59069    }
59070#endif
59071    iPage = get4byte(pOvflData);
59072    sqlite3PagerUnref(pOvflPage);
59073  }
59074}
59075#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
59076
59077#ifndef SQLITE_OMIT_INTEGRITY_CHECK
59078/*
59079** Do various sanity checks on a single page of a tree.  Return
59080** the tree depth.  Root pages return 0.  Parents of root pages
59081** return 1, and so forth.
59082**
59083** These checks are done:
59084**
59085**      1.  Make sure that cells and freeblocks do not overlap
59086**          but combine to completely cover the page.
59087**  NO  2.  Make sure cell keys are in order.
59088**  NO  3.  Make sure no key is less than or equal to zLowerBound.
59089**  NO  4.  Make sure no key is greater than or equal to zUpperBound.
59090**      5.  Check the integrity of overflow pages.
59091**      6.  Recursively call checkTreePage on all children.
59092**      7.  Verify that the depth of all children is the same.
59093**      8.  Make sure this page is at least 33% full or else it is
59094**          the root of the tree.
59095*/
59096static int checkTreePage(
59097  IntegrityCk *pCheck,  /* Context for the sanity check */
59098  int iPage,            /* Page number of the page to check */
59099  char *zParentContext, /* Parent context */
59100  i64 *pnParentMinKey,
59101  i64 *pnParentMaxKey
59102){
59103  MemPage *pPage;
59104  int i, rc, depth, d2, pgno, cnt;
59105  int hdr, cellStart;
59106  int nCell;
59107  u8 *data;
59108  BtShared *pBt;
59109  int usableSize;
59110  char zContext[100];
59111  char *hit = 0;
59112  i64 nMinKey = 0;
59113  i64 nMaxKey = 0;
59114
59115  sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
59116
59117  /* Check that the page exists
59118  */
59119  pBt = pCheck->pBt;
59120  usableSize = pBt->usableSize;
59121  if( iPage==0 ) return 0;
59122  if( checkRef(pCheck, iPage, zParentContext) ) return 0;
59123  if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
59124    checkAppendMsg(pCheck, zContext,
59125       "unable to get the page. error code=%d", rc);
59126    return 0;
59127  }
59128
59129  /* Clear MemPage.isInit to make sure the corruption detection code in
59130  ** btreeInitPage() is executed.  */
59131  pPage->isInit = 0;
59132  if( (rc = btreeInitPage(pPage))!=0 ){
59133    assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
59134    checkAppendMsg(pCheck, zContext,
59135                   "btreeInitPage() returns error code %d", rc);
59136    releasePage(pPage);
59137    return 0;
59138  }
59139
59140  /* Check out all the cells.
59141  */
59142  depth = 0;
59143  for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
59144    u8 *pCell;
59145    u32 sz;
59146    CellInfo info;
59147
59148    /* Check payload overflow pages
59149    */
59150    sqlite3_snprintf(sizeof(zContext), zContext,
59151             "On tree page %d cell %d: ", iPage, i);
59152    pCell = findCell(pPage,i);
59153    btreeParseCellPtr(pPage, pCell, &info);
59154    sz = info.nData;
59155    if( !pPage->intKey ) sz += (int)info.nKey;
59156    /* For intKey pages, check that the keys are in order.
59157    */
59158    else if( i==0 ) nMinKey = nMaxKey = info.nKey;
59159    else{
59160      if( info.nKey <= nMaxKey ){
59161        checkAppendMsg(pCheck, zContext,
59162            "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
59163      }
59164      nMaxKey = info.nKey;
59165    }
59166    assert( sz==info.nPayload );
59167    if( (sz>info.nLocal)
59168     && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
59169    ){
59170      int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
59171      Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
59172#ifndef SQLITE_OMIT_AUTOVACUUM
59173      if( pBt->autoVacuum ){
59174        checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
59175      }
59176#endif
59177      checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
59178    }
59179
59180    /* Check sanity of left child page.
59181    */
59182    if( !pPage->leaf ){
59183      pgno = get4byte(pCell);
59184#ifndef SQLITE_OMIT_AUTOVACUUM
59185      if( pBt->autoVacuum ){
59186        checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
59187      }
59188#endif
59189      d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
59190      if( i>0 && d2!=depth ){
59191        checkAppendMsg(pCheck, zContext, "Child page depth differs");
59192      }
59193      depth = d2;
59194    }
59195  }
59196
59197  if( !pPage->leaf ){
59198    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
59199    sqlite3_snprintf(sizeof(zContext), zContext,
59200                     "On page %d at right child: ", iPage);
59201#ifndef SQLITE_OMIT_AUTOVACUUM
59202    if( pBt->autoVacuum ){
59203      checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
59204    }
59205#endif
59206    checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
59207  }
59208
59209  /* For intKey leaf pages, check that the min/max keys are in order
59210  ** with any left/parent/right pages.
59211  */
59212  if( pPage->leaf && pPage->intKey ){
59213    /* if we are a left child page */
59214    if( pnParentMinKey ){
59215      /* if we are the left most child page */
59216      if( !pnParentMaxKey ){
59217        if( nMaxKey > *pnParentMinKey ){
59218          checkAppendMsg(pCheck, zContext,
59219              "Rowid %lld out of order (max larger than parent min of %lld)",
59220              nMaxKey, *pnParentMinKey);
59221        }
59222      }else{
59223        if( nMinKey <= *pnParentMinKey ){
59224          checkAppendMsg(pCheck, zContext,
59225              "Rowid %lld out of order (min less than parent min of %lld)",
59226              nMinKey, *pnParentMinKey);
59227        }
59228        if( nMaxKey > *pnParentMaxKey ){
59229          checkAppendMsg(pCheck, zContext,
59230              "Rowid %lld out of order (max larger than parent max of %lld)",
59231              nMaxKey, *pnParentMaxKey);
59232        }
59233        *pnParentMinKey = nMaxKey;
59234      }
59235    /* else if we're a right child page */
59236    } else if( pnParentMaxKey ){
59237      if( nMinKey <= *pnParentMaxKey ){
59238        checkAppendMsg(pCheck, zContext,
59239            "Rowid %lld out of order (min less than parent max of %lld)",
59240            nMinKey, *pnParentMaxKey);
59241      }
59242    }
59243  }
59244
59245  /* Check for complete coverage of the page
59246  */
59247  data = pPage->aData;
59248  hdr = pPage->hdrOffset;
59249  hit = sqlite3PageMalloc( pBt->pageSize );
59250  if( hit==0 ){
59251    pCheck->mallocFailed = 1;
59252  }else{
59253    int contentOffset = get2byteNotZero(&data[hdr+5]);
59254    assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
59255    memset(hit+contentOffset, 0, usableSize-contentOffset);
59256    memset(hit, 1, contentOffset);
59257    nCell = get2byte(&data[hdr+3]);
59258    cellStart = hdr + 12 - 4*pPage->leaf;
59259    for(i=0; i<nCell; i++){
59260      int pc = get2byte(&data[cellStart+i*2]);
59261      u32 size = 65536;
59262      int j;
59263      if( pc<=usableSize-4 ){
59264        size = cellSizePtr(pPage, &data[pc]);
59265      }
59266      if( (int)(pc+size-1)>=usableSize ){
59267        checkAppendMsg(pCheck, 0,
59268            "Corruption detected in cell %d on page %d",i,iPage);
59269      }else{
59270        for(j=pc+size-1; j>=pc; j--) hit[j]++;
59271      }
59272    }
59273    i = get2byte(&data[hdr+1]);
59274    while( i>0 ){
59275      int size, j;
59276      assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
59277      size = get2byte(&data[i+2]);
59278      assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
59279      for(j=i+size-1; j>=i; j--) hit[j]++;
59280      j = get2byte(&data[i]);
59281      assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
59282      assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
59283      i = j;
59284    }
59285    for(i=cnt=0; i<usableSize; i++){
59286      if( hit[i]==0 ){
59287        cnt++;
59288      }else if( hit[i]>1 ){
59289        checkAppendMsg(pCheck, 0,
59290          "Multiple uses for byte %d of page %d", i, iPage);
59291        break;
59292      }
59293    }
59294    if( cnt!=data[hdr+7] ){
59295      checkAppendMsg(pCheck, 0,
59296          "Fragmentation of %d bytes reported as %d on page %d",
59297          cnt, data[hdr+7], iPage);
59298    }
59299  }
59300  sqlite3PageFree(hit);
59301  releasePage(pPage);
59302  return depth+1;
59303}
59304#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
59305
59306#ifndef SQLITE_OMIT_INTEGRITY_CHECK
59307/*
59308** This routine does a complete check of the given BTree file.  aRoot[] is
59309** an array of pages numbers were each page number is the root page of
59310** a table.  nRoot is the number of entries in aRoot.
59311**
59312** A read-only or read-write transaction must be opened before calling
59313** this function.
59314**
59315** Write the number of error seen in *pnErr.  Except for some memory
59316** allocation errors,  an error message held in memory obtained from
59317** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
59318** returned.  If a memory allocation error occurs, NULL is returned.
59319*/
59320SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
59321  Btree *p,     /* The btree to be checked */
59322  int *aRoot,   /* An array of root pages numbers for individual trees */
59323  int nRoot,    /* Number of entries in aRoot[] */
59324  int mxErr,    /* Stop reporting errors after this many */
59325  int *pnErr    /* Write number of errors seen to this variable */
59326){
59327  Pgno i;
59328  int nRef;
59329  IntegrityCk sCheck;
59330  BtShared *pBt = p->pBt;
59331  char zErr[100];
59332
59333  sqlite3BtreeEnter(p);
59334  assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
59335  nRef = sqlite3PagerRefcount(pBt->pPager);
59336  sCheck.pBt = pBt;
59337  sCheck.pPager = pBt->pPager;
59338  sCheck.nPage = btreePagecount(sCheck.pBt);
59339  sCheck.mxErr = mxErr;
59340  sCheck.nErr = 0;
59341  sCheck.mallocFailed = 0;
59342  *pnErr = 0;
59343  if( sCheck.nPage==0 ){
59344    sqlite3BtreeLeave(p);
59345    return 0;
59346  }
59347
59348  sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
59349  if( !sCheck.aPgRef ){
59350    *pnErr = 1;
59351    sqlite3BtreeLeave(p);
59352    return 0;
59353  }
59354  i = PENDING_BYTE_PAGE(pBt);
59355  if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
59356  sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
59357  sCheck.errMsg.useMalloc = 2;
59358
59359  /* Check the integrity of the freelist
59360  */
59361  checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
59362            get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
59363
59364  /* Check all the tables.
59365  */
59366  for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
59367    if( aRoot[i]==0 ) continue;
59368#ifndef SQLITE_OMIT_AUTOVACUUM
59369    if( pBt->autoVacuum && aRoot[i]>1 ){
59370      checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
59371    }
59372#endif
59373    checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
59374  }
59375
59376  /* Make sure every page in the file is referenced
59377  */
59378  for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
59379#ifdef SQLITE_OMIT_AUTOVACUUM
59380    if( getPageReferenced(&sCheck, i)==0 ){
59381      checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
59382    }
59383#else
59384    /* If the database supports auto-vacuum, make sure no tables contain
59385    ** references to pointer-map pages.
59386    */
59387    if( getPageReferenced(&sCheck, i)==0 &&
59388       (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
59389      checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
59390    }
59391    if( getPageReferenced(&sCheck, i)!=0 &&
59392       (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
59393      checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
59394    }
59395#endif
59396  }
59397
59398  /* Make sure this analysis did not leave any unref() pages.
59399  ** This is an internal consistency check; an integrity check
59400  ** of the integrity check.
59401  */
59402  if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
59403    checkAppendMsg(&sCheck, 0,
59404      "Outstanding page count goes from %d to %d during this analysis",
59405      nRef, sqlite3PagerRefcount(pBt->pPager)
59406    );
59407  }
59408
59409  /* Clean  up and report errors.
59410  */
59411  sqlite3BtreeLeave(p);
59412  sqlite3_free(sCheck.aPgRef);
59413  if( sCheck.mallocFailed ){
59414    sqlite3StrAccumReset(&sCheck.errMsg);
59415    *pnErr = sCheck.nErr+1;
59416    return 0;
59417  }
59418  *pnErr = sCheck.nErr;
59419  if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
59420  return sqlite3StrAccumFinish(&sCheck.errMsg);
59421}
59422#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
59423
59424/*
59425** Return the full pathname of the underlying database file.  Return
59426** an empty string if the database is in-memory or a TEMP database.
59427**
59428** The pager filename is invariant as long as the pager is
59429** open so it is safe to access without the BtShared mutex.
59430*/
59431SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
59432  assert( p->pBt->pPager!=0 );
59433  return sqlite3PagerFilename(p->pBt->pPager, 1);
59434}
59435
59436/*
59437** Return the pathname of the journal file for this database. The return
59438** value of this routine is the same regardless of whether the journal file
59439** has been created or not.
59440**
59441** The pager journal filename is invariant as long as the pager is
59442** open so it is safe to access without the BtShared mutex.
59443*/
59444SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
59445  assert( p->pBt->pPager!=0 );
59446  return sqlite3PagerJournalname(p->pBt->pPager);
59447}
59448
59449/*
59450** Return non-zero if a transaction is active.
59451*/
59452SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
59453  assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
59454  return (p && (p->inTrans==TRANS_WRITE));
59455}
59456
59457#ifndef SQLITE_OMIT_WAL
59458/*
59459** Run a checkpoint on the Btree passed as the first argument.
59460**
59461** Return SQLITE_LOCKED if this or any other connection has an open
59462** transaction on the shared-cache the argument Btree is connected to.
59463**
59464** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
59465*/
59466SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
59467  int rc = SQLITE_OK;
59468  if( p ){
59469    BtShared *pBt = p->pBt;
59470    sqlite3BtreeEnter(p);
59471    if( pBt->inTransaction!=TRANS_NONE ){
59472      rc = SQLITE_LOCKED;
59473    }else{
59474      rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
59475    }
59476    sqlite3BtreeLeave(p);
59477  }
59478  return rc;
59479}
59480#endif
59481
59482/*
59483** Return non-zero if a read (or write) transaction is active.
59484*/
59485SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
59486  assert( p );
59487  assert( sqlite3_mutex_held(p->db->mutex) );
59488  return p->inTrans!=TRANS_NONE;
59489}
59490
59491SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
59492  assert( p );
59493  assert( sqlite3_mutex_held(p->db->mutex) );
59494  return p->nBackup!=0;
59495}
59496
59497/*
59498** This function returns a pointer to a blob of memory associated with
59499** a single shared-btree. The memory is used by client code for its own
59500** purposes (for example, to store a high-level schema associated with
59501** the shared-btree). The btree layer manages reference counting issues.
59502**
59503** The first time this is called on a shared-btree, nBytes bytes of memory
59504** are allocated, zeroed, and returned to the caller. For each subsequent
59505** call the nBytes parameter is ignored and a pointer to the same blob
59506** of memory returned.
59507**
59508** If the nBytes parameter is 0 and the blob of memory has not yet been
59509** allocated, a null pointer is returned. If the blob has already been
59510** allocated, it is returned as normal.
59511**
59512** Just before the shared-btree is closed, the function passed as the
59513** xFree argument when the memory allocation was made is invoked on the
59514** blob of allocated memory. The xFree function should not call sqlite3_free()
59515** on the memory, the btree layer does that.
59516*/
59517SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
59518  BtShared *pBt = p->pBt;
59519  sqlite3BtreeEnter(p);
59520  if( !pBt->pSchema && nBytes ){
59521    pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
59522    pBt->xFreeSchema = xFree;
59523  }
59524  sqlite3BtreeLeave(p);
59525  return pBt->pSchema;
59526}
59527
59528/*
59529** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
59530** btree as the argument handle holds an exclusive lock on the
59531** sqlite_master table. Otherwise SQLITE_OK.
59532*/
59533SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
59534  int rc;
59535  assert( sqlite3_mutex_held(p->db->mutex) );
59536  sqlite3BtreeEnter(p);
59537  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
59538  assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
59539  sqlite3BtreeLeave(p);
59540  return rc;
59541}
59542
59543
59544#ifndef SQLITE_OMIT_SHARED_CACHE
59545/*
59546** Obtain a lock on the table whose root page is iTab.  The
59547** lock is a write lock if isWritelock is true or a read lock
59548** if it is false.
59549*/
59550SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
59551  int rc = SQLITE_OK;
59552  assert( p->inTrans!=TRANS_NONE );
59553  if( p->sharable ){
59554    u8 lockType = READ_LOCK + isWriteLock;
59555    assert( READ_LOCK+1==WRITE_LOCK );
59556    assert( isWriteLock==0 || isWriteLock==1 );
59557
59558    sqlite3BtreeEnter(p);
59559    rc = querySharedCacheTableLock(p, iTab, lockType);
59560    if( rc==SQLITE_OK ){
59561      rc = setSharedCacheTableLock(p, iTab, lockType);
59562    }
59563    sqlite3BtreeLeave(p);
59564  }
59565  return rc;
59566}
59567#endif
59568
59569#ifndef SQLITE_OMIT_INCRBLOB
59570/*
59571** Argument pCsr must be a cursor opened for writing on an
59572** INTKEY table currently pointing at a valid table entry.
59573** This function modifies the data stored as part of that entry.
59574**
59575** Only the data content may only be modified, it is not possible to
59576** change the length of the data stored. If this function is called with
59577** parameters that attempt to write past the end of the existing data,
59578** no modifications are made and SQLITE_CORRUPT is returned.
59579*/
59580SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
59581  int rc;
59582  assert( cursorHoldsMutex(pCsr) );
59583  assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
59584  assert( pCsr->curFlags & BTCF_Incrblob );
59585
59586  rc = restoreCursorPosition(pCsr);
59587  if( rc!=SQLITE_OK ){
59588    return rc;
59589  }
59590  assert( pCsr->eState!=CURSOR_REQUIRESEEK );
59591  if( pCsr->eState!=CURSOR_VALID ){
59592    return SQLITE_ABORT;
59593  }
59594
59595  /* Save the positions of all other cursors open on this table. This is
59596  ** required in case any of them are holding references to an xFetch
59597  ** version of the b-tree page modified by the accessPayload call below.
59598  **
59599  ** Note that pCsr must be open on a BTREE_INTKEY table and saveCursorPosition()
59600  ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
59601  ** saveAllCursors can only return SQLITE_OK.
59602  */
59603  VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
59604  assert( rc==SQLITE_OK );
59605
59606  /* Check some assumptions:
59607  **   (a) the cursor is open for writing,
59608  **   (b) there is a read/write transaction open,
59609  **   (c) the connection holds a write-lock on the table (if required),
59610  **   (d) there are no conflicting read-locks, and
59611  **   (e) the cursor points at a valid row of an intKey table.
59612  */
59613  if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
59614    return SQLITE_READONLY;
59615  }
59616  assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
59617              && pCsr->pBt->inTransaction==TRANS_WRITE );
59618  assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
59619  assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
59620  assert( pCsr->apPage[pCsr->iPage]->intKey );
59621
59622  return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
59623}
59624
59625/*
59626** Mark this cursor as an incremental blob cursor.
59627*/
59628SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
59629  pCur->curFlags |= BTCF_Incrblob;
59630}
59631#endif
59632
59633/*
59634** Set both the "read version" (single byte at byte offset 18) and
59635** "write version" (single byte at byte offset 19) fields in the database
59636** header to iVersion.
59637*/
59638SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
59639  BtShared *pBt = pBtree->pBt;
59640  int rc;                         /* Return code */
59641
59642  assert( iVersion==1 || iVersion==2 );
59643
59644  /* If setting the version fields to 1, do not automatically open the
59645  ** WAL connection, even if the version fields are currently set to 2.
59646  */
59647  pBt->btsFlags &= ~BTS_NO_WAL;
59648  if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
59649
59650  rc = sqlite3BtreeBeginTrans(pBtree, 0);
59651  if( rc==SQLITE_OK ){
59652    u8 *aData = pBt->pPage1->aData;
59653    if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
59654      rc = sqlite3BtreeBeginTrans(pBtree, 2);
59655      if( rc==SQLITE_OK ){
59656        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
59657        if( rc==SQLITE_OK ){
59658          aData[18] = (u8)iVersion;
59659          aData[19] = (u8)iVersion;
59660        }
59661      }
59662    }
59663  }
59664
59665  pBt->btsFlags &= ~BTS_NO_WAL;
59666  return rc;
59667}
59668
59669/*
59670** set the mask of hint flags for cursor pCsr. Currently the only valid
59671** values are 0 and BTREE_BULKLOAD.
59672*/
59673SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
59674  assert( mask==BTREE_BULKLOAD || mask==0 );
59675  pCsr->hints = mask;
59676}
59677
59678/*
59679** Return true if the given Btree is read-only.
59680*/
59681SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
59682  return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
59683}
59684
59685/************** End of btree.c ***********************************************/
59686/************** Begin file backup.c ******************************************/
59687/*
59688** 2009 January 28
59689**
59690** The author disclaims copyright to this source code.  In place of
59691** a legal notice, here is a blessing:
59692**
59693**    May you do good and not evil.
59694**    May you find forgiveness for yourself and forgive others.
59695**    May you share freely, never taking more than you give.
59696**
59697*************************************************************************
59698** This file contains the implementation of the sqlite3_backup_XXX()
59699** API functions and the related features.
59700*/
59701
59702/*
59703** Structure allocated for each backup operation.
59704*/
59705struct sqlite3_backup {
59706  sqlite3* pDestDb;        /* Destination database handle */
59707  Btree *pDest;            /* Destination b-tree file */
59708  u32 iDestSchema;         /* Original schema cookie in destination */
59709  int bDestLocked;         /* True once a write-transaction is open on pDest */
59710
59711  Pgno iNext;              /* Page number of the next source page to copy */
59712  sqlite3* pSrcDb;         /* Source database handle */
59713  Btree *pSrc;             /* Source b-tree file */
59714
59715  int rc;                  /* Backup process error code */
59716
59717  /* These two variables are set by every call to backup_step(). They are
59718  ** read by calls to backup_remaining() and backup_pagecount().
59719  */
59720  Pgno nRemaining;         /* Number of pages left to copy */
59721  Pgno nPagecount;         /* Total number of pages to copy */
59722
59723  int isAttached;          /* True once backup has been registered with pager */
59724  sqlite3_backup *pNext;   /* Next backup associated with source pager */
59725};
59726
59727/*
59728** THREAD SAFETY NOTES:
59729**
59730**   Once it has been created using backup_init(), a single sqlite3_backup
59731**   structure may be accessed via two groups of thread-safe entry points:
59732**
59733**     * Via the sqlite3_backup_XXX() API function backup_step() and
59734**       backup_finish(). Both these functions obtain the source database
59735**       handle mutex and the mutex associated with the source BtShared
59736**       structure, in that order.
59737**
59738**     * Via the BackupUpdate() and BackupRestart() functions, which are
59739**       invoked by the pager layer to report various state changes in
59740**       the page cache associated with the source database. The mutex
59741**       associated with the source database BtShared structure will always
59742**       be held when either of these functions are invoked.
59743**
59744**   The other sqlite3_backup_XXX() API functions, backup_remaining() and
59745**   backup_pagecount() are not thread-safe functions. If they are called
59746**   while some other thread is calling backup_step() or backup_finish(),
59747**   the values returned may be invalid. There is no way for a call to
59748**   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
59749**   or backup_pagecount().
59750**
59751**   Depending on the SQLite configuration, the database handles and/or
59752**   the Btree objects may have their own mutexes that require locking.
59753**   Non-sharable Btrees (in-memory databases for example), do not have
59754**   associated mutexes.
59755*/
59756
59757/*
59758** Return a pointer corresponding to database zDb (i.e. "main", "temp")
59759** in connection handle pDb. If such a database cannot be found, return
59760** a NULL pointer and write an error message to pErrorDb.
59761**
59762** If the "temp" database is requested, it may need to be opened by this
59763** function. If an error occurs while doing so, return 0 and write an
59764** error message to pErrorDb.
59765*/
59766static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
59767  int i = sqlite3FindDbName(pDb, zDb);
59768
59769  if( i==1 ){
59770    Parse *pParse;
59771    int rc = 0;
59772    pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
59773    if( pParse==0 ){
59774      sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
59775      rc = SQLITE_NOMEM;
59776    }else{
59777      pParse->db = pDb;
59778      if( sqlite3OpenTempDatabase(pParse) ){
59779        sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
59780        rc = SQLITE_ERROR;
59781      }
59782      sqlite3DbFree(pErrorDb, pParse->zErrMsg);
59783      sqlite3ParserReset(pParse);
59784      sqlite3StackFree(pErrorDb, pParse);
59785    }
59786    if( rc ){
59787      return 0;
59788    }
59789  }
59790
59791  if( i<0 ){
59792    sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
59793    return 0;
59794  }
59795
59796  return pDb->aDb[i].pBt;
59797}
59798
59799/*
59800** Attempt to set the page size of the destination to match the page size
59801** of the source.
59802*/
59803static int setDestPgsz(sqlite3_backup *p){
59804  int rc;
59805  rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
59806  return rc;
59807}
59808
59809/*
59810** Create an sqlite3_backup process to copy the contents of zSrcDb from
59811** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
59812** a pointer to the new sqlite3_backup object.
59813**
59814** If an error occurs, NULL is returned and an error code and error message
59815** stored in database handle pDestDb.
59816*/
59817SQLITE_API sqlite3_backup *sqlite3_backup_init(
59818  sqlite3* pDestDb,                     /* Database to write to */
59819  const char *zDestDb,                  /* Name of database within pDestDb */
59820  sqlite3* pSrcDb,                      /* Database connection to read from */
59821  const char *zSrcDb                    /* Name of database within pSrcDb */
59822){
59823  sqlite3_backup *p;                    /* Value to return */
59824
59825  /* Lock the source database handle. The destination database
59826  ** handle is not locked in this routine, but it is locked in
59827  ** sqlite3_backup_step(). The user is required to ensure that no
59828  ** other thread accesses the destination handle for the duration
59829  ** of the backup operation.  Any attempt to use the destination
59830  ** database connection while a backup is in progress may cause
59831  ** a malfunction or a deadlock.
59832  */
59833  sqlite3_mutex_enter(pSrcDb->mutex);
59834  sqlite3_mutex_enter(pDestDb->mutex);
59835
59836  if( pSrcDb==pDestDb ){
59837    sqlite3Error(
59838        pDestDb, SQLITE_ERROR, "source and destination must be distinct"
59839    );
59840    p = 0;
59841  }else {
59842    /* Allocate space for a new sqlite3_backup object...
59843    ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
59844    ** call to sqlite3_backup_init() and is destroyed by a call to
59845    ** sqlite3_backup_finish(). */
59846    p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
59847    if( !p ){
59848      sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
59849    }
59850  }
59851
59852  /* If the allocation succeeded, populate the new object. */
59853  if( p ){
59854    p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
59855    p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
59856    p->pDestDb = pDestDb;
59857    p->pSrcDb = pSrcDb;
59858    p->iNext = 1;
59859    p->isAttached = 0;
59860
59861    if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
59862      /* One (or both) of the named databases did not exist or an OOM
59863      ** error was hit.  The error has already been written into the
59864      ** pDestDb handle.  All that is left to do here is free the
59865      ** sqlite3_backup structure.
59866      */
59867      sqlite3_free(p);
59868      p = 0;
59869    }
59870  }
59871  if( p ){
59872    p->pSrc->nBackup++;
59873  }
59874
59875  sqlite3_mutex_leave(pDestDb->mutex);
59876  sqlite3_mutex_leave(pSrcDb->mutex);
59877  return p;
59878}
59879
59880/*
59881** Argument rc is an SQLite error code. Return true if this error is
59882** considered fatal if encountered during a backup operation. All errors
59883** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
59884*/
59885static int isFatalError(int rc){
59886  return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
59887}
59888
59889/*
59890** Parameter zSrcData points to a buffer containing the data for
59891** page iSrcPg from the source database. Copy this data into the
59892** destination database.
59893*/
59894static int backupOnePage(
59895  sqlite3_backup *p,              /* Backup handle */
59896  Pgno iSrcPg,                    /* Source database page to backup */
59897  const u8 *zSrcData,             /* Source database page data */
59898  int bUpdate                     /* True for an update, false otherwise */
59899){
59900  Pager * const pDestPager = sqlite3BtreePager(p->pDest);
59901  const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
59902  int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
59903  const int nCopy = MIN(nSrcPgsz, nDestPgsz);
59904  const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
59905#ifdef SQLITE_HAS_CODEC
59906  /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
59907  ** guaranteed that the shared-mutex is held by this thread, handle
59908  ** p->pSrc may not actually be the owner.  */
59909  int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
59910  int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
59911#endif
59912  int rc = SQLITE_OK;
59913  i64 iOff;
59914
59915  assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
59916  assert( p->bDestLocked );
59917  assert( !isFatalError(p->rc) );
59918  assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
59919  assert( zSrcData );
59920
59921  /* Catch the case where the destination is an in-memory database and the
59922  ** page sizes of the source and destination differ.
59923  */
59924  if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
59925    rc = SQLITE_READONLY;
59926  }
59927
59928#ifdef SQLITE_HAS_CODEC
59929  /* Backup is not possible if the page size of the destination is changing
59930  ** and a codec is in use.
59931  */
59932  if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
59933    rc = SQLITE_READONLY;
59934  }
59935
59936  /* Backup is not possible if the number of bytes of reserve space differ
59937  ** between source and destination.  If there is a difference, try to
59938  ** fix the destination to agree with the source.  If that is not possible,
59939  ** then the backup cannot proceed.
59940  */
59941  if( nSrcReserve!=nDestReserve ){
59942    u32 newPgsz = nSrcPgsz;
59943    rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
59944    if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
59945  }
59946#endif
59947
59948  /* This loop runs once for each destination page spanned by the source
59949  ** page. For each iteration, variable iOff is set to the byte offset
59950  ** of the destination page.
59951  */
59952  for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
59953    DbPage *pDestPg = 0;
59954    Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
59955    if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
59956    if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
59957     && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
59958    ){
59959      const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
59960      u8 *zDestData = sqlite3PagerGetData(pDestPg);
59961      u8 *zOut = &zDestData[iOff%nDestPgsz];
59962
59963      /* Copy the data from the source page into the destination page.
59964      ** Then clear the Btree layer MemPage.isInit flag. Both this module
59965      ** and the pager code use this trick (clearing the first byte
59966      ** of the page 'extra' space to invalidate the Btree layers
59967      ** cached parse of the page). MemPage.isInit is marked
59968      ** "MUST BE FIRST" for this purpose.
59969      */
59970      memcpy(zOut, zIn, nCopy);
59971      ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
59972      if( iOff==0 && bUpdate==0 ){
59973        sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
59974      }
59975    }
59976    sqlite3PagerUnref(pDestPg);
59977  }
59978
59979  return rc;
59980}
59981
59982/*
59983** If pFile is currently larger than iSize bytes, then truncate it to
59984** exactly iSize bytes. If pFile is not larger than iSize bytes, then
59985** this function is a no-op.
59986**
59987** Return SQLITE_OK if everything is successful, or an SQLite error
59988** code if an error occurs.
59989*/
59990static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
59991  i64 iCurrent;
59992  int rc = sqlite3OsFileSize(pFile, &iCurrent);
59993  if( rc==SQLITE_OK && iCurrent>iSize ){
59994    rc = sqlite3OsTruncate(pFile, iSize);
59995  }
59996  return rc;
59997}
59998
59999/*
60000** Register this backup object with the associated source pager for
60001** callbacks when pages are changed or the cache invalidated.
60002*/
60003static void attachBackupObject(sqlite3_backup *p){
60004  sqlite3_backup **pp;
60005  assert( sqlite3BtreeHoldsMutex(p->pSrc) );
60006  pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
60007  p->pNext = *pp;
60008  *pp = p;
60009  p->isAttached = 1;
60010}
60011
60012/*
60013** Copy nPage pages from the source b-tree to the destination.
60014*/
60015SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
60016  int rc;
60017  int destMode;       /* Destination journal mode */
60018  int pgszSrc = 0;    /* Source page size */
60019  int pgszDest = 0;   /* Destination page size */
60020
60021  sqlite3_mutex_enter(p->pSrcDb->mutex);
60022  sqlite3BtreeEnter(p->pSrc);
60023  if( p->pDestDb ){
60024    sqlite3_mutex_enter(p->pDestDb->mutex);
60025  }
60026
60027  rc = p->rc;
60028  if( !isFatalError(rc) ){
60029    Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
60030    Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
60031    int ii;                            /* Iterator variable */
60032    int nSrcPage = -1;                 /* Size of source db in pages */
60033    int bCloseTrans = 0;               /* True if src db requires unlocking */
60034
60035    /* If the source pager is currently in a write-transaction, return
60036    ** SQLITE_BUSY immediately.
60037    */
60038    if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
60039      rc = SQLITE_BUSY;
60040    }else{
60041      rc = SQLITE_OK;
60042    }
60043
60044    /* Lock the destination database, if it is not locked already. */
60045    if( SQLITE_OK==rc && p->bDestLocked==0
60046     && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
60047    ){
60048      p->bDestLocked = 1;
60049      sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
60050    }
60051
60052    /* If there is no open read-transaction on the source database, open
60053    ** one now. If a transaction is opened here, then it will be closed
60054    ** before this function exits.
60055    */
60056    if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
60057      rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
60058      bCloseTrans = 1;
60059    }
60060
60061    /* Do not allow backup if the destination database is in WAL mode
60062    ** and the page sizes are different between source and destination */
60063    pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
60064    pgszDest = sqlite3BtreeGetPageSize(p->pDest);
60065    destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
60066    if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
60067      rc = SQLITE_READONLY;
60068    }
60069
60070    /* Now that there is a read-lock on the source database, query the
60071    ** source pager for the number of pages in the database.
60072    */
60073    nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
60074    assert( nSrcPage>=0 );
60075    for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
60076      const Pgno iSrcPg = p->iNext;                 /* Source page number */
60077      if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
60078        DbPage *pSrcPg;                             /* Source page object */
60079        rc = sqlite3PagerAcquire(pSrcPager, iSrcPg, &pSrcPg,
60080                                 PAGER_GET_READONLY);
60081        if( rc==SQLITE_OK ){
60082          rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
60083          sqlite3PagerUnref(pSrcPg);
60084        }
60085      }
60086      p->iNext++;
60087    }
60088    if( rc==SQLITE_OK ){
60089      p->nPagecount = nSrcPage;
60090      p->nRemaining = nSrcPage+1-p->iNext;
60091      if( p->iNext>(Pgno)nSrcPage ){
60092        rc = SQLITE_DONE;
60093      }else if( !p->isAttached ){
60094        attachBackupObject(p);
60095      }
60096    }
60097
60098    /* Update the schema version field in the destination database. This
60099    ** is to make sure that the schema-version really does change in
60100    ** the case where the source and destination databases have the
60101    ** same schema version.
60102    */
60103    if( rc==SQLITE_DONE ){
60104      if( nSrcPage==0 ){
60105        rc = sqlite3BtreeNewDb(p->pDest);
60106        nSrcPage = 1;
60107      }
60108      if( rc==SQLITE_OK || rc==SQLITE_DONE ){
60109        rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
60110      }
60111      if( rc==SQLITE_OK ){
60112        if( p->pDestDb ){
60113          sqlite3ResetAllSchemasOfConnection(p->pDestDb);
60114        }
60115        if( destMode==PAGER_JOURNALMODE_WAL ){
60116          rc = sqlite3BtreeSetVersion(p->pDest, 2);
60117        }
60118      }
60119      if( rc==SQLITE_OK ){
60120        int nDestTruncate;
60121        /* Set nDestTruncate to the final number of pages in the destination
60122        ** database. The complication here is that the destination page
60123        ** size may be different to the source page size.
60124        **
60125        ** If the source page size is smaller than the destination page size,
60126        ** round up. In this case the call to sqlite3OsTruncate() below will
60127        ** fix the size of the file. However it is important to call
60128        ** sqlite3PagerTruncateImage() here so that any pages in the
60129        ** destination file that lie beyond the nDestTruncate page mark are
60130        ** journalled by PagerCommitPhaseOne() before they are destroyed
60131        ** by the file truncation.
60132        */
60133        assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
60134        assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
60135        if( pgszSrc<pgszDest ){
60136          int ratio = pgszDest/pgszSrc;
60137          nDestTruncate = (nSrcPage+ratio-1)/ratio;
60138          if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
60139            nDestTruncate--;
60140          }
60141        }else{
60142          nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
60143        }
60144        assert( nDestTruncate>0 );
60145
60146        if( pgszSrc<pgszDest ){
60147          /* If the source page-size is smaller than the destination page-size,
60148          ** two extra things may need to happen:
60149          **
60150          **   * The destination may need to be truncated, and
60151          **
60152          **   * Data stored on the pages immediately following the
60153          **     pending-byte page in the source database may need to be
60154          **     copied into the destination database.
60155          */
60156          const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
60157          sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
60158          Pgno iPg;
60159          int nDstPage;
60160          i64 iOff;
60161          i64 iEnd;
60162
60163          assert( pFile );
60164          assert( nDestTruncate==0
60165              || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
60166                nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
60167             && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
60168          ));
60169
60170          /* This block ensures that all data required to recreate the original
60171          ** database has been stored in the journal for pDestPager and the
60172          ** journal synced to disk. So at this point we may safely modify
60173          ** the database file in any way, knowing that if a power failure
60174          ** occurs, the original database will be reconstructed from the
60175          ** journal file.  */
60176          sqlite3PagerPagecount(pDestPager, &nDstPage);
60177          for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
60178            if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
60179              DbPage *pPg;
60180              rc = sqlite3PagerGet(pDestPager, iPg, &pPg);
60181              if( rc==SQLITE_OK ){
60182                rc = sqlite3PagerWrite(pPg);
60183                sqlite3PagerUnref(pPg);
60184              }
60185            }
60186          }
60187          if( rc==SQLITE_OK ){
60188            rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
60189          }
60190
60191          /* Write the extra pages and truncate the database file as required */
60192          iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
60193          for(
60194            iOff=PENDING_BYTE+pgszSrc;
60195            rc==SQLITE_OK && iOff<iEnd;
60196            iOff+=pgszSrc
60197          ){
60198            PgHdr *pSrcPg = 0;
60199            const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
60200            rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
60201            if( rc==SQLITE_OK ){
60202              u8 *zData = sqlite3PagerGetData(pSrcPg);
60203              rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
60204            }
60205            sqlite3PagerUnref(pSrcPg);
60206          }
60207          if( rc==SQLITE_OK ){
60208            rc = backupTruncateFile(pFile, iSize);
60209          }
60210
60211          /* Sync the database file to disk. */
60212          if( rc==SQLITE_OK ){
60213            rc = sqlite3PagerSync(pDestPager, 0);
60214          }
60215        }else{
60216          sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
60217          rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
60218        }
60219
60220        /* Finish committing the transaction to the destination database. */
60221        if( SQLITE_OK==rc
60222         && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
60223        ){
60224          rc = SQLITE_DONE;
60225        }
60226      }
60227    }
60228
60229    /* If bCloseTrans is true, then this function opened a read transaction
60230    ** on the source database. Close the read transaction here. There is
60231    ** no need to check the return values of the btree methods here, as
60232    ** "committing" a read-only transaction cannot fail.
60233    */
60234    if( bCloseTrans ){
60235      TESTONLY( int rc2 );
60236      TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
60237      TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
60238      assert( rc2==SQLITE_OK );
60239    }
60240
60241    if( rc==SQLITE_IOERR_NOMEM ){
60242      rc = SQLITE_NOMEM;
60243    }
60244    p->rc = rc;
60245  }
60246  if( p->pDestDb ){
60247    sqlite3_mutex_leave(p->pDestDb->mutex);
60248  }
60249  sqlite3BtreeLeave(p->pSrc);
60250  sqlite3_mutex_leave(p->pSrcDb->mutex);
60251  return rc;
60252}
60253
60254/*
60255** Release all resources associated with an sqlite3_backup* handle.
60256*/
60257SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
60258  sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
60259  sqlite3 *pSrcDb;                     /* Source database connection */
60260  int rc;                              /* Value to return */
60261
60262  /* Enter the mutexes */
60263  if( p==0 ) return SQLITE_OK;
60264  pSrcDb = p->pSrcDb;
60265  sqlite3_mutex_enter(pSrcDb->mutex);
60266  sqlite3BtreeEnter(p->pSrc);
60267  if( p->pDestDb ){
60268    sqlite3_mutex_enter(p->pDestDb->mutex);
60269  }
60270
60271  /* Detach this backup from the source pager. */
60272  if( p->pDestDb ){
60273    p->pSrc->nBackup--;
60274  }
60275  if( p->isAttached ){
60276    pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
60277    while( *pp!=p ){
60278      pp = &(*pp)->pNext;
60279    }
60280    *pp = p->pNext;
60281  }
60282
60283  /* If a transaction is still open on the Btree, roll it back. */
60284  sqlite3BtreeRollback(p->pDest, SQLITE_OK);
60285
60286  /* Set the error code of the destination database handle. */
60287  rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
60288  if( p->pDestDb ){
60289    sqlite3Error(p->pDestDb, rc, 0);
60290
60291    /* Exit the mutexes and free the backup context structure. */
60292    sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
60293  }
60294  sqlite3BtreeLeave(p->pSrc);
60295  if( p->pDestDb ){
60296    /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
60297    ** call to sqlite3_backup_init() and is destroyed by a call to
60298    ** sqlite3_backup_finish(). */
60299    sqlite3_free(p);
60300  }
60301  sqlite3LeaveMutexAndCloseZombie(pSrcDb);
60302  return rc;
60303}
60304
60305/*
60306** Return the number of pages still to be backed up as of the most recent
60307** call to sqlite3_backup_step().
60308*/
60309SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
60310  return p->nRemaining;
60311}
60312
60313/*
60314** Return the total number of pages in the source database as of the most
60315** recent call to sqlite3_backup_step().
60316*/
60317SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
60318  return p->nPagecount;
60319}
60320
60321/*
60322** This function is called after the contents of page iPage of the
60323** source database have been modified. If page iPage has already been
60324** copied into the destination database, then the data written to the
60325** destination is now invalidated. The destination copy of iPage needs
60326** to be updated with the new data before the backup operation is
60327** complete.
60328**
60329** It is assumed that the mutex associated with the BtShared object
60330** corresponding to the source database is held when this function is
60331** called.
60332*/
60333SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
60334  sqlite3_backup *p;                   /* Iterator variable */
60335  for(p=pBackup; p; p=p->pNext){
60336    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
60337    if( !isFatalError(p->rc) && iPage<p->iNext ){
60338      /* The backup process p has already copied page iPage. But now it
60339      ** has been modified by a transaction on the source pager. Copy
60340      ** the new data into the backup.
60341      */
60342      int rc;
60343      assert( p->pDestDb );
60344      sqlite3_mutex_enter(p->pDestDb->mutex);
60345      rc = backupOnePage(p, iPage, aData, 1);
60346      sqlite3_mutex_leave(p->pDestDb->mutex);
60347      assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
60348      if( rc!=SQLITE_OK ){
60349        p->rc = rc;
60350      }
60351    }
60352  }
60353}
60354
60355/*
60356** Restart the backup process. This is called when the pager layer
60357** detects that the database has been modified by an external database
60358** connection. In this case there is no way of knowing which of the
60359** pages that have been copied into the destination database are still
60360** valid and which are not, so the entire process needs to be restarted.
60361**
60362** It is assumed that the mutex associated with the BtShared object
60363** corresponding to the source database is held when this function is
60364** called.
60365*/
60366SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
60367  sqlite3_backup *p;                   /* Iterator variable */
60368  for(p=pBackup; p; p=p->pNext){
60369    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
60370    p->iNext = 1;
60371  }
60372}
60373
60374#ifndef SQLITE_OMIT_VACUUM
60375/*
60376** Copy the complete content of pBtFrom into pBtTo.  A transaction
60377** must be active for both files.
60378**
60379** The size of file pTo may be reduced by this operation. If anything
60380** goes wrong, the transaction on pTo is rolled back. If successful, the
60381** transaction is committed before returning.
60382*/
60383SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
60384  int rc;
60385  sqlite3_file *pFd;              /* File descriptor for database pTo */
60386  sqlite3_backup b;
60387  sqlite3BtreeEnter(pTo);
60388  sqlite3BtreeEnter(pFrom);
60389
60390  assert( sqlite3BtreeIsInTrans(pTo) );
60391  pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
60392  if( pFd->pMethods ){
60393    i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
60394    rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
60395    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
60396    if( rc ) goto copy_finished;
60397  }
60398
60399  /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
60400  ** to 0. This is used by the implementations of sqlite3_backup_step()
60401  ** and sqlite3_backup_finish() to detect that they are being called
60402  ** from this function, not directly by the user.
60403  */
60404  memset(&b, 0, sizeof(b));
60405  b.pSrcDb = pFrom->db;
60406  b.pSrc = pFrom;
60407  b.pDest = pTo;
60408  b.iNext = 1;
60409
60410  /* 0x7FFFFFFF is the hard limit for the number of pages in a database
60411  ** file. By passing this as the number of pages to copy to
60412  ** sqlite3_backup_step(), we can guarantee that the copy finishes
60413  ** within a single call (unless an error occurs). The assert() statement
60414  ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
60415  ** or an error code.
60416  */
60417  sqlite3_backup_step(&b, 0x7FFFFFFF);
60418  assert( b.rc!=SQLITE_OK );
60419  rc = sqlite3_backup_finish(&b);
60420  if( rc==SQLITE_OK ){
60421    pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
60422  }else{
60423    sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
60424  }
60425
60426  assert( sqlite3BtreeIsInTrans(pTo)==0 );
60427copy_finished:
60428  sqlite3BtreeLeave(pFrom);
60429  sqlite3BtreeLeave(pTo);
60430  return rc;
60431}
60432#endif /* SQLITE_OMIT_VACUUM */
60433
60434/************** End of backup.c **********************************************/
60435/************** Begin file vdbemem.c *****************************************/
60436/*
60437** 2004 May 26
60438**
60439** The author disclaims copyright to this source code.  In place of
60440** a legal notice, here is a blessing:
60441**
60442**    May you do good and not evil.
60443**    May you find forgiveness for yourself and forgive others.
60444**    May you share freely, never taking more than you give.
60445**
60446*************************************************************************
60447**
60448** This file contains code use to manipulate "Mem" structure.  A "Mem"
60449** stores a single value in the VDBE.  Mem is an opaque structure visible
60450** only within the VDBE.  Interface routines refer to a Mem using the
60451** name sqlite_value
60452*/
60453
60454#ifdef SQLITE_DEBUG
60455/*
60456** Check invariants on a Mem object.
60457**
60458** This routine is intended for use inside of assert() statements, like
60459** this:    assert( sqlite3VdbeCheckMemInvariants(pMem) );
60460*/
60461SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
60462  /* The MEM_Dyn bit is set if and only if Mem.xDel is a non-NULL destructor
60463  ** function for Mem.z
60464  */
60465  assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
60466  assert( (p->flags & MEM_Dyn)!=0 || p->xDel==0 );
60467
60468  /* If p holds a string or blob, the Mem.z must point to exactly
60469  ** one of the following:
60470  **
60471  **   (1) Memory in Mem.zMalloc and managed by the Mem object
60472  **   (2) Memory to be freed using Mem.xDel
60473  **   (3) An ephermal string or blob
60474  **   (4) A static string or blob
60475  */
60476  if( (p->flags & (MEM_Str|MEM_Blob)) && p->z!=0 ){
60477    assert(
60478      ((p->z==p->zMalloc)? 1 : 0) +
60479      ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
60480      ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
60481      ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
60482    );
60483  }
60484
60485  return 1;
60486}
60487#endif
60488
60489
60490/*
60491** If pMem is an object with a valid string representation, this routine
60492** ensures the internal encoding for the string representation is
60493** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
60494**
60495** If pMem is not a string object, or the encoding of the string
60496** representation is already stored using the requested encoding, then this
60497** routine is a no-op.
60498**
60499** SQLITE_OK is returned if the conversion is successful (or not required).
60500** SQLITE_NOMEM may be returned if a malloc() fails during conversion
60501** between formats.
60502*/
60503SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
60504#ifndef SQLITE_OMIT_UTF16
60505  int rc;
60506#endif
60507  assert( (pMem->flags&MEM_RowSet)==0 );
60508  assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
60509           || desiredEnc==SQLITE_UTF16BE );
60510  if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
60511    return SQLITE_OK;
60512  }
60513  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
60514#ifdef SQLITE_OMIT_UTF16
60515  return SQLITE_ERROR;
60516#else
60517
60518  /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
60519  ** then the encoding of the value may not have changed.
60520  */
60521  rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
60522  assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
60523  assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
60524  assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
60525  return rc;
60526#endif
60527}
60528
60529/*
60530** Make sure pMem->z points to a writable allocation of at least
60531** min(n,32) bytes.
60532**
60533** If the bPreserve argument is true, then copy of the content of
60534** pMem->z into the new allocation.  pMem must be either a string or
60535** blob if bPreserve is true.  If bPreserve is false, any prior content
60536** in pMem->z is discarded.
60537*/
60538SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
60539  assert( sqlite3VdbeCheckMemInvariants(pMem) );
60540  assert( (pMem->flags&MEM_RowSet)==0 );
60541
60542  /* If the bPreserve flag is set to true, then the memory cell must already
60543  ** contain a valid string or blob value.  */
60544  assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
60545  testcase( bPreserve && pMem->z==0 );
60546
60547  if( pMem->zMalloc==0 || sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
60548    if( n<32 ) n = 32;
60549    if( bPreserve && pMem->z==pMem->zMalloc ){
60550      pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
60551      bPreserve = 0;
60552    }else{
60553      sqlite3DbFree(pMem->db, pMem->zMalloc);
60554      pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
60555    }
60556    if( pMem->zMalloc==0 ){
60557      VdbeMemRelease(pMem);
60558      pMem->z = 0;
60559      pMem->flags = MEM_Null;
60560      return SQLITE_NOMEM;
60561    }
60562  }
60563
60564  if( pMem->z && bPreserve && pMem->z!=pMem->zMalloc ){
60565    memcpy(pMem->zMalloc, pMem->z, pMem->n);
60566  }
60567  if( (pMem->flags&MEM_Dyn)!=0 ){
60568    assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
60569    pMem->xDel((void *)(pMem->z));
60570  }
60571
60572  pMem->z = pMem->zMalloc;
60573  pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
60574  pMem->xDel = 0;
60575  return SQLITE_OK;
60576}
60577
60578/*
60579** Make the given Mem object MEM_Dyn.  In other words, make it so
60580** that any TEXT or BLOB content is stored in memory obtained from
60581** malloc().  In this way, we know that the memory is safe to be
60582** overwritten or altered.
60583**
60584** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
60585*/
60586SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
60587  int f;
60588  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
60589  assert( (pMem->flags&MEM_RowSet)==0 );
60590  ExpandBlob(pMem);
60591  f = pMem->flags;
60592  if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
60593    if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
60594      return SQLITE_NOMEM;
60595    }
60596    pMem->z[pMem->n] = 0;
60597    pMem->z[pMem->n+1] = 0;
60598    pMem->flags |= MEM_Term;
60599#ifdef SQLITE_DEBUG
60600    pMem->pScopyFrom = 0;
60601#endif
60602  }
60603
60604  return SQLITE_OK;
60605}
60606
60607/*
60608** If the given Mem* has a zero-filled tail, turn it into an ordinary
60609** blob stored in dynamically allocated space.
60610*/
60611#ifndef SQLITE_OMIT_INCRBLOB
60612SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
60613  if( pMem->flags & MEM_Zero ){
60614    int nByte;
60615    assert( pMem->flags&MEM_Blob );
60616    assert( (pMem->flags&MEM_RowSet)==0 );
60617    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
60618
60619    /* Set nByte to the number of bytes required to store the expanded blob. */
60620    nByte = pMem->n + pMem->u.nZero;
60621    if( nByte<=0 ){
60622      nByte = 1;
60623    }
60624    if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
60625      return SQLITE_NOMEM;
60626    }
60627
60628    memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
60629    pMem->n += pMem->u.nZero;
60630    pMem->flags &= ~(MEM_Zero|MEM_Term);
60631  }
60632  return SQLITE_OK;
60633}
60634#endif
60635
60636
60637/*
60638** Make sure the given Mem is \u0000 terminated.
60639*/
60640SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
60641  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
60642  if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
60643    return SQLITE_OK;   /* Nothing to do */
60644  }
60645  if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
60646    return SQLITE_NOMEM;
60647  }
60648  pMem->z[pMem->n] = 0;
60649  pMem->z[pMem->n+1] = 0;
60650  pMem->flags |= MEM_Term;
60651  return SQLITE_OK;
60652}
60653
60654/*
60655** Add MEM_Str to the set of representations for the given Mem.  Numbers
60656** are converted using sqlite3_snprintf().  Converting a BLOB to a string
60657** is a no-op.
60658**
60659** Existing representations MEM_Int and MEM_Real are *not* invalidated.
60660**
60661** A MEM_Null value will never be passed to this function. This function is
60662** used for converting values to text for returning to the user (i.e. via
60663** sqlite3_value_text()), or for ensuring that values to be used as btree
60664** keys are strings. In the former case a NULL pointer is returned the
60665** user and the later is an internal programming error.
60666*/
60667SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
60668  int rc = SQLITE_OK;
60669  int fg = pMem->flags;
60670  const int nByte = 32;
60671
60672  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
60673  assert( !(fg&MEM_Zero) );
60674  assert( !(fg&(MEM_Str|MEM_Blob)) );
60675  assert( fg&(MEM_Int|MEM_Real) );
60676  assert( (pMem->flags&MEM_RowSet)==0 );
60677  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
60678
60679
60680  if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
60681    return SQLITE_NOMEM;
60682  }
60683
60684  /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
60685  ** string representation of the value. Then, if the required encoding
60686  ** is UTF-16le or UTF-16be do a translation.
60687  **
60688  ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
60689  */
60690  if( fg & MEM_Int ){
60691    sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
60692  }else{
60693    assert( fg & MEM_Real );
60694    sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
60695  }
60696  pMem->n = sqlite3Strlen30(pMem->z);
60697  pMem->enc = SQLITE_UTF8;
60698  pMem->flags |= MEM_Str|MEM_Term;
60699  sqlite3VdbeChangeEncoding(pMem, enc);
60700  return rc;
60701}
60702
60703/*
60704** Memory cell pMem contains the context of an aggregate function.
60705** This routine calls the finalize method for that function.  The
60706** result of the aggregate is stored back into pMem.
60707**
60708** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
60709** otherwise.
60710*/
60711SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
60712  int rc = SQLITE_OK;
60713  if( ALWAYS(pFunc && pFunc->xFinalize) ){
60714    sqlite3_context ctx;
60715    assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
60716    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
60717    memset(&ctx, 0, sizeof(ctx));
60718    ctx.s.flags = MEM_Null;
60719    ctx.s.db = pMem->db;
60720    ctx.pMem = pMem;
60721    ctx.pFunc = pFunc;
60722    pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
60723    assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
60724    sqlite3DbFree(pMem->db, pMem->zMalloc);
60725    memcpy(pMem, &ctx.s, sizeof(ctx.s));
60726    rc = ctx.isError;
60727  }
60728  return rc;
60729}
60730
60731/*
60732** If the memory cell contains a string value that must be freed by
60733** invoking an external callback, free it now. Calling this function
60734** does not free any Mem.zMalloc buffer.
60735*/
60736SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
60737  assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
60738  if( p->flags&MEM_Agg ){
60739    sqlite3VdbeMemFinalize(p, p->u.pDef);
60740    assert( (p->flags & MEM_Agg)==0 );
60741    sqlite3VdbeMemRelease(p);
60742  }else if( p->flags&MEM_Dyn ){
60743    assert( (p->flags&MEM_RowSet)==0 );
60744    assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
60745    p->xDel((void *)p->z);
60746    p->xDel = 0;
60747  }else if( p->flags&MEM_RowSet ){
60748    sqlite3RowSetClear(p->u.pRowSet);
60749  }else if( p->flags&MEM_Frame ){
60750    sqlite3VdbeMemSetNull(p);
60751  }
60752}
60753
60754/*
60755** Release any memory held by the Mem. This may leave the Mem in an
60756** inconsistent state, for example with (Mem.z==0) and
60757** (Mem.flags==MEM_Str).
60758*/
60759SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
60760  assert( sqlite3VdbeCheckMemInvariants(p) );
60761  VdbeMemRelease(p);
60762  if( p->zMalloc ){
60763    sqlite3DbFree(p->db, p->zMalloc);
60764    p->zMalloc = 0;
60765  }
60766  p->z = 0;
60767  assert( p->xDel==0 );  /* Zeroed by VdbeMemRelease() above */
60768}
60769
60770/*
60771** Convert a 64-bit IEEE double into a 64-bit signed integer.
60772** If the double is out of range of a 64-bit signed integer then
60773** return the closest available 64-bit signed integer.
60774*/
60775static i64 doubleToInt64(double r){
60776#ifdef SQLITE_OMIT_FLOATING_POINT
60777  /* When floating-point is omitted, double and int64 are the same thing */
60778  return r;
60779#else
60780  /*
60781  ** Many compilers we encounter do not define constants for the
60782  ** minimum and maximum 64-bit integers, or they define them
60783  ** inconsistently.  And many do not understand the "LL" notation.
60784  ** So we define our own static constants here using nothing
60785  ** larger than a 32-bit integer constant.
60786  */
60787  static const i64 maxInt = LARGEST_INT64;
60788  static const i64 minInt = SMALLEST_INT64;
60789
60790  if( r<=(double)minInt ){
60791    return minInt;
60792  }else if( r>=(double)maxInt ){
60793    return maxInt;
60794  }else{
60795    return (i64)r;
60796  }
60797#endif
60798}
60799
60800/*
60801** Return some kind of integer value which is the best we can do
60802** at representing the value that *pMem describes as an integer.
60803** If pMem is an integer, then the value is exact.  If pMem is
60804** a floating-point then the value returned is the integer part.
60805** If pMem is a string or blob, then we make an attempt to convert
60806** it into a integer and return that.  If pMem represents an
60807** an SQL-NULL value, return 0.
60808**
60809** If pMem represents a string value, its encoding might be changed.
60810*/
60811SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
60812  int flags;
60813  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
60814  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
60815  flags = pMem->flags;
60816  if( flags & MEM_Int ){
60817    return pMem->u.i;
60818  }else if( flags & MEM_Real ){
60819    return doubleToInt64(pMem->r);
60820  }else if( flags & (MEM_Str|MEM_Blob) ){
60821    i64 value = 0;
60822    assert( pMem->z || pMem->n==0 );
60823    testcase( pMem->z==0 );
60824    sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
60825    return value;
60826  }else{
60827    return 0;
60828  }
60829}
60830
60831/*
60832** Return the best representation of pMem that we can get into a
60833** double.  If pMem is already a double or an integer, return its
60834** value.  If it is a string or blob, try to convert it to a double.
60835** If it is a NULL, return 0.0.
60836*/
60837SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
60838  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
60839  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
60840  if( pMem->flags & MEM_Real ){
60841    return pMem->r;
60842  }else if( pMem->flags & MEM_Int ){
60843    return (double)pMem->u.i;
60844  }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
60845    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
60846    double val = (double)0;
60847    sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
60848    return val;
60849  }else{
60850    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
60851    return (double)0;
60852  }
60853}
60854
60855/*
60856** The MEM structure is already a MEM_Real.  Try to also make it a
60857** MEM_Int if we can.
60858*/
60859SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
60860  assert( pMem->flags & MEM_Real );
60861  assert( (pMem->flags & MEM_RowSet)==0 );
60862  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
60863  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
60864
60865  pMem->u.i = doubleToInt64(pMem->r);
60866
60867  /* Only mark the value as an integer if
60868  **
60869  **    (1) the round-trip conversion real->int->real is a no-op, and
60870  **    (2) The integer is neither the largest nor the smallest
60871  **        possible integer (ticket #3922)
60872  **
60873  ** The second and third terms in the following conditional enforces
60874  ** the second condition under the assumption that addition overflow causes
60875  ** values to wrap around.
60876  */
60877  if( pMem->r==(double)pMem->u.i
60878   && pMem->u.i>SMALLEST_INT64
60879   && pMem->u.i<LARGEST_INT64
60880  ){
60881    pMem->flags |= MEM_Int;
60882  }
60883}
60884
60885/*
60886** Convert pMem to type integer.  Invalidate any prior representations.
60887*/
60888SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
60889  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
60890  assert( (pMem->flags & MEM_RowSet)==0 );
60891  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
60892
60893  pMem->u.i = sqlite3VdbeIntValue(pMem);
60894  MemSetTypeFlag(pMem, MEM_Int);
60895  return SQLITE_OK;
60896}
60897
60898/*
60899** Convert pMem so that it is of type MEM_Real.
60900** Invalidate any prior representations.
60901*/
60902SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
60903  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
60904  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
60905
60906  pMem->r = sqlite3VdbeRealValue(pMem);
60907  MemSetTypeFlag(pMem, MEM_Real);
60908  return SQLITE_OK;
60909}
60910
60911/*
60912** Convert pMem so that it has types MEM_Real or MEM_Int or both.
60913** Invalidate any prior representations.
60914**
60915** Every effort is made to force the conversion, even if the input
60916** is a string that does not look completely like a number.  Convert
60917** as much of the string as we can and ignore the rest.
60918*/
60919SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
60920  if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
60921    assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
60922    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
60923    if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
60924      MemSetTypeFlag(pMem, MEM_Int);
60925    }else{
60926      pMem->r = sqlite3VdbeRealValue(pMem);
60927      MemSetTypeFlag(pMem, MEM_Real);
60928      sqlite3VdbeIntegerAffinity(pMem);
60929    }
60930  }
60931  assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
60932  pMem->flags &= ~(MEM_Str|MEM_Blob);
60933  return SQLITE_OK;
60934}
60935
60936/*
60937** Delete any previous value and set the value stored in *pMem to NULL.
60938*/
60939SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
60940  if( pMem->flags & MEM_Frame ){
60941    VdbeFrame *pFrame = pMem->u.pFrame;
60942    pFrame->pParent = pFrame->v->pDelFrame;
60943    pFrame->v->pDelFrame = pFrame;
60944  }
60945  if( pMem->flags & MEM_RowSet ){
60946    sqlite3RowSetClear(pMem->u.pRowSet);
60947  }
60948  MemSetTypeFlag(pMem, MEM_Null);
60949}
60950SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
60951  sqlite3VdbeMemSetNull((Mem*)p);
60952}
60953
60954/*
60955** Delete any previous value and set the value to be a BLOB of length
60956** n containing all zeros.
60957*/
60958SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
60959  sqlite3VdbeMemRelease(pMem);
60960  pMem->flags = MEM_Blob|MEM_Zero;
60961  pMem->n = 0;
60962  if( n<0 ) n = 0;
60963  pMem->u.nZero = n;
60964  pMem->enc = SQLITE_UTF8;
60965
60966#ifdef SQLITE_OMIT_INCRBLOB
60967  sqlite3VdbeMemGrow(pMem, n, 0);
60968  if( pMem->z ){
60969    pMem->n = n;
60970    memset(pMem->z, 0, n);
60971  }
60972#endif
60973}
60974
60975/*
60976** Delete any previous value and set the value stored in *pMem to val,
60977** manifest type INTEGER.
60978*/
60979SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
60980  sqlite3VdbeMemRelease(pMem);
60981  pMem->u.i = val;
60982  pMem->flags = MEM_Int;
60983}
60984
60985#ifndef SQLITE_OMIT_FLOATING_POINT
60986/*
60987** Delete any previous value and set the value stored in *pMem to val,
60988** manifest type REAL.
60989*/
60990SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
60991  if( sqlite3IsNaN(val) ){
60992    sqlite3VdbeMemSetNull(pMem);
60993  }else{
60994    sqlite3VdbeMemRelease(pMem);
60995    pMem->r = val;
60996    pMem->flags = MEM_Real;
60997  }
60998}
60999#endif
61000
61001/*
61002** Delete any previous value and set the value of pMem to be an
61003** empty boolean index.
61004*/
61005SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
61006  sqlite3 *db = pMem->db;
61007  assert( db!=0 );
61008  assert( (pMem->flags & MEM_RowSet)==0 );
61009  sqlite3VdbeMemRelease(pMem);
61010  pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
61011  if( db->mallocFailed ){
61012    pMem->flags = MEM_Null;
61013  }else{
61014    assert( pMem->zMalloc );
61015    pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
61016                                       sqlite3DbMallocSize(db, pMem->zMalloc));
61017    assert( pMem->u.pRowSet!=0 );
61018    pMem->flags = MEM_RowSet;
61019  }
61020}
61021
61022/*
61023** Return true if the Mem object contains a TEXT or BLOB that is
61024** too large - whose size exceeds SQLITE_MAX_LENGTH.
61025*/
61026SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
61027  assert( p->db!=0 );
61028  if( p->flags & (MEM_Str|MEM_Blob) ){
61029    int n = p->n;
61030    if( p->flags & MEM_Zero ){
61031      n += p->u.nZero;
61032    }
61033    return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
61034  }
61035  return 0;
61036}
61037
61038#ifdef SQLITE_DEBUG
61039/*
61040** This routine prepares a memory cell for modication by breaking
61041** its link to a shallow copy and by marking any current shallow
61042** copies of this cell as invalid.
61043**
61044** This is used for testing and debugging only - to make sure shallow
61045** copies are not misused.
61046*/
61047SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
61048  int i;
61049  Mem *pX;
61050  for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
61051    if( pX->pScopyFrom==pMem ){
61052      pX->flags |= MEM_Undefined;
61053      pX->pScopyFrom = 0;
61054    }
61055  }
61056  pMem->pScopyFrom = 0;
61057}
61058#endif /* SQLITE_DEBUG */
61059
61060/*
61061** Size of struct Mem not including the Mem.zMalloc member.
61062*/
61063#define MEMCELLSIZE offsetof(Mem,zMalloc)
61064
61065/*
61066** Make an shallow copy of pFrom into pTo.  Prior contents of
61067** pTo are freed.  The pFrom->z field is not duplicated.  If
61068** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
61069** and flags gets srcType (either MEM_Ephem or MEM_Static).
61070*/
61071SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
61072  assert( (pFrom->flags & MEM_RowSet)==0 );
61073  VdbeMemRelease(pTo);
61074  memcpy(pTo, pFrom, MEMCELLSIZE);
61075  pTo->xDel = 0;
61076  if( (pFrom->flags&MEM_Static)==0 ){
61077    pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
61078    assert( srcType==MEM_Ephem || srcType==MEM_Static );
61079    pTo->flags |= srcType;
61080  }
61081}
61082
61083/*
61084** Make a full copy of pFrom into pTo.  Prior contents of pTo are
61085** freed before the copy is made.
61086*/
61087SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
61088  int rc = SQLITE_OK;
61089
61090  assert( (pFrom->flags & MEM_RowSet)==0 );
61091  VdbeMemRelease(pTo);
61092  memcpy(pTo, pFrom, MEMCELLSIZE);
61093  pTo->flags &= ~MEM_Dyn;
61094  pTo->xDel = 0;
61095
61096  if( pTo->flags&(MEM_Str|MEM_Blob) ){
61097    if( 0==(pFrom->flags&MEM_Static) ){
61098      pTo->flags |= MEM_Ephem;
61099      rc = sqlite3VdbeMemMakeWriteable(pTo);
61100    }
61101  }
61102
61103  return rc;
61104}
61105
61106/*
61107** Transfer the contents of pFrom to pTo. Any existing value in pTo is
61108** freed. If pFrom contains ephemeral data, a copy is made.
61109**
61110** pFrom contains an SQL NULL when this routine returns.
61111*/
61112SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
61113  assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
61114  assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
61115  assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
61116
61117  sqlite3VdbeMemRelease(pTo);
61118  memcpy(pTo, pFrom, sizeof(Mem));
61119  pFrom->flags = MEM_Null;
61120  pFrom->xDel = 0;
61121  pFrom->zMalloc = 0;
61122}
61123
61124/*
61125** Change the value of a Mem to be a string or a BLOB.
61126**
61127** The memory management strategy depends on the value of the xDel
61128** parameter. If the value passed is SQLITE_TRANSIENT, then the
61129** string is copied into a (possibly existing) buffer managed by the
61130** Mem structure. Otherwise, any existing buffer is freed and the
61131** pointer copied.
61132**
61133** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
61134** size limit) then no memory allocation occurs.  If the string can be
61135** stored without allocating memory, then it is.  If a memory allocation
61136** is required to store the string, then value of pMem is unchanged.  In
61137** either case, SQLITE_TOOBIG is returned.
61138*/
61139SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
61140  Mem *pMem,          /* Memory cell to set to string value */
61141  const char *z,      /* String pointer */
61142  int n,              /* Bytes in string, or negative */
61143  u8 enc,             /* Encoding of z.  0 for BLOBs */
61144  void (*xDel)(void*) /* Destructor function */
61145){
61146  int nByte = n;      /* New value for pMem->n */
61147  int iLimit;         /* Maximum allowed string or blob size */
61148  u16 flags = 0;      /* New value for pMem->flags */
61149
61150  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
61151  assert( (pMem->flags & MEM_RowSet)==0 );
61152
61153  /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
61154  if( !z ){
61155    sqlite3VdbeMemSetNull(pMem);
61156    return SQLITE_OK;
61157  }
61158
61159  if( pMem->db ){
61160    iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
61161  }else{
61162    iLimit = SQLITE_MAX_LENGTH;
61163  }
61164  flags = (enc==0?MEM_Blob:MEM_Str);
61165  if( nByte<0 ){
61166    assert( enc!=0 );
61167    if( enc==SQLITE_UTF8 ){
61168      for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
61169    }else{
61170      for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
61171    }
61172    flags |= MEM_Term;
61173  }
61174
61175  /* The following block sets the new values of Mem.z and Mem.xDel. It
61176  ** also sets a flag in local variable "flags" to indicate the memory
61177  ** management (one of MEM_Dyn or MEM_Static).
61178  */
61179  if( xDel==SQLITE_TRANSIENT ){
61180    int nAlloc = nByte;
61181    if( flags&MEM_Term ){
61182      nAlloc += (enc==SQLITE_UTF8?1:2);
61183    }
61184    if( nByte>iLimit ){
61185      return SQLITE_TOOBIG;
61186    }
61187    if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
61188      return SQLITE_NOMEM;
61189    }
61190    memcpy(pMem->z, z, nAlloc);
61191  }else if( xDel==SQLITE_DYNAMIC ){
61192    sqlite3VdbeMemRelease(pMem);
61193    pMem->zMalloc = pMem->z = (char *)z;
61194    pMem->xDel = 0;
61195  }else{
61196    sqlite3VdbeMemRelease(pMem);
61197    pMem->z = (char *)z;
61198    pMem->xDel = xDel;
61199    flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
61200  }
61201
61202  pMem->n = nByte;
61203  pMem->flags = flags;
61204  pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
61205
61206#ifndef SQLITE_OMIT_UTF16
61207  if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
61208    return SQLITE_NOMEM;
61209  }
61210#endif
61211
61212  if( nByte>iLimit ){
61213    return SQLITE_TOOBIG;
61214  }
61215
61216  return SQLITE_OK;
61217}
61218
61219/*
61220** Move data out of a btree key or data field and into a Mem structure.
61221** The data or key is taken from the entry that pCur is currently pointing
61222** to.  offset and amt determine what portion of the data or key to retrieve.
61223** key is true to get the key or false to get data.  The result is written
61224** into the pMem element.
61225**
61226** The pMem structure is assumed to be uninitialized.  Any prior content
61227** is overwritten without being freed.
61228**
61229** If this routine fails for any reason (malloc returns NULL or unable
61230** to read from the disk) then the pMem is left in an inconsistent state.
61231*/
61232SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
61233  BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
61234  u32 offset,       /* Offset from the start of data to return bytes from. */
61235  u32 amt,          /* Number of bytes to return. */
61236  int key,          /* If true, retrieve from the btree key, not data. */
61237  Mem *pMem         /* OUT: Return data in this Mem structure. */
61238){
61239  char *zData;        /* Data from the btree layer */
61240  u32 available = 0;  /* Number of bytes available on the local btree page */
61241  int rc = SQLITE_OK; /* Return code */
61242
61243  assert( sqlite3BtreeCursorIsValid(pCur) );
61244
61245  /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
61246  ** that both the BtShared and database handle mutexes are held. */
61247  assert( (pMem->flags & MEM_RowSet)==0 );
61248  if( key ){
61249    zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
61250  }else{
61251    zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
61252  }
61253  assert( zData!=0 );
61254
61255  if( offset+amt<=available ){
61256    sqlite3VdbeMemRelease(pMem);
61257    pMem->z = &zData[offset];
61258    pMem->flags = MEM_Blob|MEM_Ephem;
61259    pMem->n = (int)amt;
61260  }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
61261    if( key ){
61262      rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
61263    }else{
61264      rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
61265    }
61266    if( rc==SQLITE_OK ){
61267      pMem->z[amt] = 0;
61268      pMem->z[amt+1] = 0;
61269      pMem->flags = MEM_Blob|MEM_Term;
61270      pMem->n = (int)amt;
61271    }else{
61272      sqlite3VdbeMemRelease(pMem);
61273    }
61274  }
61275
61276  return rc;
61277}
61278
61279/* This function is only available internally, it is not part of the
61280** external API. It works in a similar way to sqlite3_value_text(),
61281** except the data returned is in the encoding specified by the second
61282** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
61283** SQLITE_UTF8.
61284**
61285** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
61286** If that is the case, then the result must be aligned on an even byte
61287** boundary.
61288*/
61289SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
61290  if( !pVal ) return 0;
61291
61292  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
61293  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
61294  assert( (pVal->flags & MEM_RowSet)==0 );
61295
61296  if( pVal->flags&MEM_Null ){
61297    return 0;
61298  }
61299  assert( (MEM_Blob>>3) == MEM_Str );
61300  pVal->flags |= (pVal->flags & MEM_Blob)>>3;
61301  ExpandBlob(pVal);
61302  if( pVal->flags&MEM_Str ){
61303    sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
61304    if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
61305      assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
61306      if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
61307        return 0;
61308      }
61309    }
61310    sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
61311  }else{
61312    assert( (pVal->flags&MEM_Blob)==0 );
61313    sqlite3VdbeMemStringify(pVal, enc);
61314    assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
61315  }
61316  assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
61317              || pVal->db->mallocFailed );
61318  if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
61319    return pVal->z;
61320  }else{
61321    return 0;
61322  }
61323}
61324
61325/*
61326** Create a new sqlite3_value object.
61327*/
61328SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
61329  Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
61330  if( p ){
61331    p->flags = MEM_Null;
61332    p->db = db;
61333  }
61334  return p;
61335}
61336
61337/*
61338** Context object passed by sqlite3Stat4ProbeSetValue() through to
61339** valueNew(). See comments above valueNew() for details.
61340*/
61341struct ValueNewStat4Ctx {
61342  Parse *pParse;
61343  Index *pIdx;
61344  UnpackedRecord **ppRec;
61345  int iVal;
61346};
61347
61348/*
61349** Allocate and return a pointer to a new sqlite3_value object. If
61350** the second argument to this function is NULL, the object is allocated
61351** by calling sqlite3ValueNew().
61352**
61353** Otherwise, if the second argument is non-zero, then this function is
61354** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
61355** already been allocated, allocate the UnpackedRecord structure that
61356** that function will return to its caller here. Then return a pointer
61357** an sqlite3_value within the UnpackedRecord.a[] array.
61358*/
61359static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
61360#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
61361  if( p ){
61362    UnpackedRecord *pRec = p->ppRec[0];
61363
61364    if( pRec==0 ){
61365      Index *pIdx = p->pIdx;      /* Index being probed */
61366      int nByte;                  /* Bytes of space to allocate */
61367      int i;                      /* Counter variable */
61368      int nCol = pIdx->nColumn;   /* Number of index columns including rowid */
61369
61370      nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
61371      pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
61372      if( pRec ){
61373        pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
61374        if( pRec->pKeyInfo ){
61375          assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol );
61376          assert( pRec->pKeyInfo->enc==ENC(db) );
61377          pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
61378          for(i=0; i<nCol; i++){
61379            pRec->aMem[i].flags = MEM_Null;
61380            pRec->aMem[i].db = db;
61381          }
61382        }else{
61383          sqlite3DbFree(db, pRec);
61384          pRec = 0;
61385        }
61386      }
61387      if( pRec==0 ) return 0;
61388      p->ppRec[0] = pRec;
61389    }
61390
61391    pRec->nField = p->iVal+1;
61392    return &pRec->aMem[p->iVal];
61393  }
61394#else
61395  UNUSED_PARAMETER(p);
61396#endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
61397  return sqlite3ValueNew(db);
61398}
61399
61400/*
61401** Extract a value from the supplied expression in the manner described
61402** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
61403** using valueNew().
61404**
61405** If pCtx is NULL and an error occurs after the sqlite3_value object
61406** has been allocated, it is freed before returning. Or, if pCtx is not
61407** NULL, it is assumed that the caller will free any allocated object
61408** in all cases.
61409*/
61410static int valueFromExpr(
61411  sqlite3 *db,                    /* The database connection */
61412  Expr *pExpr,                    /* The expression to evaluate */
61413  u8 enc,                         /* Encoding to use */
61414  u8 affinity,                    /* Affinity to use */
61415  sqlite3_value **ppVal,          /* Write the new value here */
61416  struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
61417){
61418  int op;
61419  char *zVal = 0;
61420  sqlite3_value *pVal = 0;
61421  int negInt = 1;
61422  const char *zNeg = "";
61423  int rc = SQLITE_OK;
61424
61425  if( !pExpr ){
61426    *ppVal = 0;
61427    return SQLITE_OK;
61428  }
61429  op = pExpr->op;
61430  if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
61431
61432  /* Handle negative integers in a single step.  This is needed in the
61433  ** case when the value is -9223372036854775808.
61434  */
61435  if( op==TK_UMINUS
61436   && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
61437    pExpr = pExpr->pLeft;
61438    op = pExpr->op;
61439    negInt = -1;
61440    zNeg = "-";
61441  }
61442
61443  if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
61444    pVal = valueNew(db, pCtx);
61445    if( pVal==0 ) goto no_mem;
61446    if( ExprHasProperty(pExpr, EP_IntValue) ){
61447      sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
61448    }else{
61449      zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
61450      if( zVal==0 ) goto no_mem;
61451      sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
61452    }
61453    if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
61454      sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
61455    }else{
61456      sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
61457    }
61458    if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
61459    if( enc!=SQLITE_UTF8 ){
61460      rc = sqlite3VdbeChangeEncoding(pVal, enc);
61461    }
61462  }else if( op==TK_UMINUS ) {
61463    /* This branch happens for multiple negative signs.  Ex: -(-5) */
61464    if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal)
61465     && pVal!=0
61466    ){
61467      sqlite3VdbeMemNumerify(pVal);
61468      if( pVal->u.i==SMALLEST_INT64 ){
61469        pVal->flags &= ~MEM_Int;
61470        pVal->flags |= MEM_Real;
61471        pVal->r = (double)SMALLEST_INT64;
61472      }else{
61473        pVal->u.i = -pVal->u.i;
61474      }
61475      pVal->r = -pVal->r;
61476      sqlite3ValueApplyAffinity(pVal, affinity, enc);
61477    }
61478  }else if( op==TK_NULL ){
61479    pVal = valueNew(db, pCtx);
61480    if( pVal==0 ) goto no_mem;
61481  }
61482#ifndef SQLITE_OMIT_BLOB_LITERAL
61483  else if( op==TK_BLOB ){
61484    int nVal;
61485    assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
61486    assert( pExpr->u.zToken[1]=='\'' );
61487    pVal = valueNew(db, pCtx);
61488    if( !pVal ) goto no_mem;
61489    zVal = &pExpr->u.zToken[2];
61490    nVal = sqlite3Strlen30(zVal)-1;
61491    assert( zVal[nVal]=='\'' );
61492    sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
61493                         0, SQLITE_DYNAMIC);
61494  }
61495#endif
61496
61497  *ppVal = pVal;
61498  return rc;
61499
61500no_mem:
61501  db->mallocFailed = 1;
61502  sqlite3DbFree(db, zVal);
61503  assert( *ppVal==0 );
61504#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
61505  if( pCtx==0 ) sqlite3ValueFree(pVal);
61506#else
61507  assert( pCtx==0 ); sqlite3ValueFree(pVal);
61508#endif
61509  return SQLITE_NOMEM;
61510}
61511
61512/*
61513** Create a new sqlite3_value object, containing the value of pExpr.
61514**
61515** This only works for very simple expressions that consist of one constant
61516** token (i.e. "5", "5.1", "'a string'"). If the expression can
61517** be converted directly into a value, then the value is allocated and
61518** a pointer written to *ppVal. The caller is responsible for deallocating
61519** the value by passing it to sqlite3ValueFree() later on. If the expression
61520** cannot be converted to a value, then *ppVal is set to NULL.
61521*/
61522SQLITE_PRIVATE int sqlite3ValueFromExpr(
61523  sqlite3 *db,              /* The database connection */
61524  Expr *pExpr,              /* The expression to evaluate */
61525  u8 enc,                   /* Encoding to use */
61526  u8 affinity,              /* Affinity to use */
61527  sqlite3_value **ppVal     /* Write the new value here */
61528){
61529  return valueFromExpr(db, pExpr, enc, affinity, ppVal, 0);
61530}
61531
61532#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
61533/*
61534** The implementation of the sqlite_record() function. This function accepts
61535** a single argument of any type. The return value is a formatted database
61536** record (a blob) containing the argument value.
61537**
61538** This is used to convert the value stored in the 'sample' column of the
61539** sqlite_stat3 table to the record format SQLite uses internally.
61540*/
61541static void recordFunc(
61542  sqlite3_context *context,
61543  int argc,
61544  sqlite3_value **argv
61545){
61546  const int file_format = 1;
61547  int iSerial;                    /* Serial type */
61548  int nSerial;                    /* Bytes of space for iSerial as varint */
61549  int nVal;                       /* Bytes of space required for argv[0] */
61550  int nRet;
61551  sqlite3 *db;
61552  u8 *aRet;
61553
61554  UNUSED_PARAMETER( argc );
61555  iSerial = sqlite3VdbeSerialType(argv[0], file_format);
61556  nSerial = sqlite3VarintLen(iSerial);
61557  nVal = sqlite3VdbeSerialTypeLen(iSerial);
61558  db = sqlite3_context_db_handle(context);
61559
61560  nRet = 1 + nSerial + nVal;
61561  aRet = sqlite3DbMallocRaw(db, nRet);
61562  if( aRet==0 ){
61563    sqlite3_result_error_nomem(context);
61564  }else{
61565    aRet[0] = nSerial+1;
61566    sqlite3PutVarint(&aRet[1], iSerial);
61567    sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
61568    sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
61569    sqlite3DbFree(db, aRet);
61570  }
61571}
61572
61573/*
61574** Register built-in functions used to help read ANALYZE data.
61575*/
61576SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
61577  static SQLITE_WSD FuncDef aAnalyzeTableFuncs[] = {
61578    FUNCTION(sqlite_record,   1, 0, 0, recordFunc),
61579  };
61580  int i;
61581  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
61582  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAnalyzeTableFuncs);
61583  for(i=0; i<ArraySize(aAnalyzeTableFuncs); i++){
61584    sqlite3FuncDefInsert(pHash, &aFunc[i]);
61585  }
61586}
61587
61588/*
61589** This function is used to allocate and populate UnpackedRecord
61590** structures intended to be compared against sample index keys stored
61591** in the sqlite_stat4 table.
61592**
61593** A single call to this function attempts to populates field iVal (leftmost
61594** is 0 etc.) of the unpacked record with a value extracted from expression
61595** pExpr. Extraction of values is possible if:
61596**
61597**  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
61598**
61599**  * The expression is a bound variable, and this is a reprepare, or
61600**
61601**  * The sqlite3ValueFromExpr() function is able to extract a value
61602**    from the expression (i.e. the expression is a literal value).
61603**
61604** If a value can be extracted, the affinity passed as the 5th argument
61605** is applied to it before it is copied into the UnpackedRecord. Output
61606** parameter *pbOk is set to true if a value is extracted, or false
61607** otherwise.
61608**
61609** When this function is called, *ppRec must either point to an object
61610** allocated by an earlier call to this function, or must be NULL. If it
61611** is NULL and a value can be successfully extracted, a new UnpackedRecord
61612** is allocated (and *ppRec set to point to it) before returning.
61613**
61614** Unless an error is encountered, SQLITE_OK is returned. It is not an
61615** error if a value cannot be extracted from pExpr. If an error does
61616** occur, an SQLite error code is returned.
61617*/
61618SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
61619  Parse *pParse,                  /* Parse context */
61620  Index *pIdx,                    /* Index being probed */
61621  UnpackedRecord **ppRec,         /* IN/OUT: Probe record */
61622  Expr *pExpr,                    /* The expression to extract a value from */
61623  u8 affinity,                    /* Affinity to use */
61624  int iVal,                       /* Array element to populate */
61625  int *pbOk                       /* OUT: True if value was extracted */
61626){
61627  int rc = SQLITE_OK;
61628  sqlite3_value *pVal = 0;
61629  sqlite3 *db = pParse->db;
61630
61631
61632  struct ValueNewStat4Ctx alloc;
61633  alloc.pParse = pParse;
61634  alloc.pIdx = pIdx;
61635  alloc.ppRec = ppRec;
61636  alloc.iVal = iVal;
61637
61638  /* Skip over any TK_COLLATE nodes */
61639  pExpr = sqlite3ExprSkipCollate(pExpr);
61640
61641  if( !pExpr ){
61642    pVal = valueNew(db, &alloc);
61643    if( pVal ){
61644      sqlite3VdbeMemSetNull((Mem*)pVal);
61645    }
61646  }else if( pExpr->op==TK_VARIABLE
61647        || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
61648  ){
61649    Vdbe *v;
61650    int iBindVar = pExpr->iColumn;
61651    sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
61652    if( (v = pParse->pReprepare)!=0 ){
61653      pVal = valueNew(db, &alloc);
61654      if( pVal ){
61655        rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
61656        if( rc==SQLITE_OK ){
61657          sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
61658        }
61659        pVal->db = pParse->db;
61660      }
61661    }
61662  }else{
61663    rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, &alloc);
61664  }
61665  *pbOk = (pVal!=0);
61666
61667  assert( pVal==0 || pVal->db==db );
61668  return rc;
61669}
61670
61671/*
61672** Unless it is NULL, the argument must be an UnpackedRecord object returned
61673** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
61674** the object.
61675*/
61676SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
61677  if( pRec ){
61678    int i;
61679    int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField;
61680    Mem *aMem = pRec->aMem;
61681    sqlite3 *db = aMem[0].db;
61682    for(i=0; i<nCol; i++){
61683      sqlite3DbFree(db, aMem[i].zMalloc);
61684    }
61685    sqlite3KeyInfoUnref(pRec->pKeyInfo);
61686    sqlite3DbFree(db, pRec);
61687  }
61688}
61689#endif /* ifdef SQLITE_ENABLE_STAT4 */
61690
61691/*
61692** Change the string value of an sqlite3_value object
61693*/
61694SQLITE_PRIVATE void sqlite3ValueSetStr(
61695  sqlite3_value *v,     /* Value to be set */
61696  int n,                /* Length of string z */
61697  const void *z,        /* Text of the new string */
61698  u8 enc,               /* Encoding to use */
61699  void (*xDel)(void*)   /* Destructor for the string */
61700){
61701  if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
61702}
61703
61704/*
61705** Free an sqlite3_value object
61706*/
61707SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
61708  if( !v ) return;
61709  sqlite3VdbeMemRelease((Mem *)v);
61710  sqlite3DbFree(((Mem*)v)->db, v);
61711}
61712
61713/*
61714** Return the number of bytes in the sqlite3_value object assuming
61715** that it uses the encoding "enc"
61716*/
61717SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
61718  Mem *p = (Mem*)pVal;
61719  if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
61720    if( p->flags & MEM_Zero ){
61721      return p->n + p->u.nZero;
61722    }else{
61723      return p->n;
61724    }
61725  }
61726  return 0;
61727}
61728
61729/************** End of vdbemem.c *********************************************/
61730/************** Begin file vdbeaux.c *****************************************/
61731/*
61732** 2003 September 6
61733**
61734** The author disclaims copyright to this source code.  In place of
61735** a legal notice, here is a blessing:
61736**
61737**    May you do good and not evil.
61738**    May you find forgiveness for yourself and forgive others.
61739**    May you share freely, never taking more than you give.
61740**
61741*************************************************************************
61742** This file contains code used for creating, destroying, and populating
61743** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
61744** to version 2.8.7, all this code was combined into the vdbe.c source file.
61745** But that file was getting too big so this subroutines were split out.
61746*/
61747
61748/*
61749** Create a new virtual database engine.
61750*/
61751SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
61752  sqlite3 *db = pParse->db;
61753  Vdbe *p;
61754  p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
61755  if( p==0 ) return 0;
61756  p->db = db;
61757  if( db->pVdbe ){
61758    db->pVdbe->pPrev = p;
61759  }
61760  p->pNext = db->pVdbe;
61761  p->pPrev = 0;
61762  db->pVdbe = p;
61763  p->magic = VDBE_MAGIC_INIT;
61764  p->pParse = pParse;
61765  assert( pParse->aLabel==0 );
61766  assert( pParse->nLabel==0 );
61767  assert( pParse->nOpAlloc==0 );
61768  return p;
61769}
61770
61771/*
61772** Remember the SQL string for a prepared statement.
61773*/
61774SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
61775  assert( isPrepareV2==1 || isPrepareV2==0 );
61776  if( p==0 ) return;
61777#if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
61778  if( !isPrepareV2 ) return;
61779#endif
61780  assert( p->zSql==0 );
61781  p->zSql = sqlite3DbStrNDup(p->db, z, n);
61782  p->isPrepareV2 = (u8)isPrepareV2;
61783}
61784
61785/*
61786** Return the SQL associated with a prepared statement
61787*/
61788SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
61789  Vdbe *p = (Vdbe *)pStmt;
61790  return (p && p->isPrepareV2) ? p->zSql : 0;
61791}
61792
61793/*
61794** Swap all content between two VDBE structures.
61795*/
61796SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
61797  Vdbe tmp, *pTmp;
61798  char *zTmp;
61799  tmp = *pA;
61800  *pA = *pB;
61801  *pB = tmp;
61802  pTmp = pA->pNext;
61803  pA->pNext = pB->pNext;
61804  pB->pNext = pTmp;
61805  pTmp = pA->pPrev;
61806  pA->pPrev = pB->pPrev;
61807  pB->pPrev = pTmp;
61808  zTmp = pA->zSql;
61809  pA->zSql = pB->zSql;
61810  pB->zSql = zTmp;
61811  pB->isPrepareV2 = pA->isPrepareV2;
61812}
61813
61814/*
61815** Resize the Vdbe.aOp array so that it is at least one op larger than
61816** it was.
61817**
61818** If an out-of-memory error occurs while resizing the array, return
61819** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
61820** unchanged (this is so that any opcodes already allocated can be
61821** correctly deallocated along with the rest of the Vdbe).
61822*/
61823static int growOpArray(Vdbe *v){
61824  VdbeOp *pNew;
61825  Parse *p = v->pParse;
61826  int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
61827  pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
61828  if( pNew ){
61829    p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
61830    v->aOp = pNew;
61831  }
61832  return (pNew ? SQLITE_OK : SQLITE_NOMEM);
61833}
61834
61835#ifdef SQLITE_DEBUG
61836/* This routine is just a convenient place to set a breakpoint that will
61837** fire after each opcode is inserted and displayed using
61838** "PRAGMA vdbe_addoptrace=on".
61839*/
61840static void test_addop_breakpoint(void){
61841  static int n = 0;
61842  n++;
61843}
61844#endif
61845
61846/*
61847** Add a new instruction to the list of instructions current in the
61848** VDBE.  Return the address of the new instruction.
61849**
61850** Parameters:
61851**
61852**    p               Pointer to the VDBE
61853**
61854**    op              The opcode for this instruction
61855**
61856**    p1, p2, p3      Operands
61857**
61858** Use the sqlite3VdbeResolveLabel() function to fix an address and
61859** the sqlite3VdbeChangeP4() function to change the value of the P4
61860** operand.
61861*/
61862SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
61863  int i;
61864  VdbeOp *pOp;
61865
61866  i = p->nOp;
61867  assert( p->magic==VDBE_MAGIC_INIT );
61868  assert( op>0 && op<0xff );
61869  if( p->pParse->nOpAlloc<=i ){
61870    if( growOpArray(p) ){
61871      return 1;
61872    }
61873  }
61874  p->nOp++;
61875  pOp = &p->aOp[i];
61876  pOp->opcode = (u8)op;
61877  pOp->p5 = 0;
61878  pOp->p1 = p1;
61879  pOp->p2 = p2;
61880  pOp->p3 = p3;
61881  pOp->p4.p = 0;
61882  pOp->p4type = P4_NOTUSED;
61883#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
61884  pOp->zComment = 0;
61885#endif
61886#ifdef SQLITE_DEBUG
61887  if( p->db->flags & SQLITE_VdbeAddopTrace ){
61888    int jj, kk;
61889    Parse *pParse = p->pParse;
61890    for(jj=kk=0; jj<SQLITE_N_COLCACHE; jj++){
61891      struct yColCache *x = pParse->aColCache + jj;
61892      if( x->iLevel>pParse->iCacheLevel || x->iReg==0 ) continue;
61893      printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
61894      kk++;
61895    }
61896    if( kk ) printf("\n");
61897    sqlite3VdbePrintOp(0, i, &p->aOp[i]);
61898    test_addop_breakpoint();
61899  }
61900#endif
61901#ifdef VDBE_PROFILE
61902  pOp->cycles = 0;
61903  pOp->cnt = 0;
61904#endif
61905#ifdef SQLITE_VDBE_COVERAGE
61906  pOp->iSrcLine = 0;
61907#endif
61908  return i;
61909}
61910SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
61911  return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
61912}
61913SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
61914  return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
61915}
61916SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
61917  return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
61918}
61919
61920
61921/*
61922** Add an opcode that includes the p4 value as a pointer.
61923*/
61924SQLITE_PRIVATE int sqlite3VdbeAddOp4(
61925  Vdbe *p,            /* Add the opcode to this VM */
61926  int op,             /* The new opcode */
61927  int p1,             /* The P1 operand */
61928  int p2,             /* The P2 operand */
61929  int p3,             /* The P3 operand */
61930  const char *zP4,    /* The P4 operand */
61931  int p4type          /* P4 operand type */
61932){
61933  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
61934  sqlite3VdbeChangeP4(p, addr, zP4, p4type);
61935  return addr;
61936}
61937
61938/*
61939** Add an OP_ParseSchema opcode.  This routine is broken out from
61940** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
61941** as having been used.
61942**
61943** The zWhere string must have been obtained from sqlite3_malloc().
61944** This routine will take ownership of the allocated memory.
61945*/
61946SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
61947  int j;
61948  int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
61949  sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
61950  for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
61951}
61952
61953/*
61954** Add an opcode that includes the p4 value as an integer.
61955*/
61956SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
61957  Vdbe *p,            /* Add the opcode to this VM */
61958  int op,             /* The new opcode */
61959  int p1,             /* The P1 operand */
61960  int p2,             /* The P2 operand */
61961  int p3,             /* The P3 operand */
61962  int p4              /* The P4 operand as an integer */
61963){
61964  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
61965  sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
61966  return addr;
61967}
61968
61969/*
61970** Create a new symbolic label for an instruction that has yet to be
61971** coded.  The symbolic label is really just a negative number.  The
61972** label can be used as the P2 value of an operation.  Later, when
61973** the label is resolved to a specific address, the VDBE will scan
61974** through its operation list and change all values of P2 which match
61975** the label into the resolved address.
61976**
61977** The VDBE knows that a P2 value is a label because labels are
61978** always negative and P2 values are suppose to be non-negative.
61979** Hence, a negative P2 value is a label that has yet to be resolved.
61980**
61981** Zero is returned if a malloc() fails.
61982*/
61983SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
61984  Parse *p = v->pParse;
61985  int i = p->nLabel++;
61986  assert( v->magic==VDBE_MAGIC_INIT );
61987  if( (i & (i-1))==0 ){
61988    p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
61989                                       (i*2+1)*sizeof(p->aLabel[0]));
61990  }
61991  if( p->aLabel ){
61992    p->aLabel[i] = -1;
61993  }
61994  return -1-i;
61995}
61996
61997/*
61998** Resolve label "x" to be the address of the next instruction to
61999** be inserted.  The parameter "x" must have been obtained from
62000** a prior call to sqlite3VdbeMakeLabel().
62001*/
62002SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
62003  Parse *p = v->pParse;
62004  int j = -1-x;
62005  assert( v->magic==VDBE_MAGIC_INIT );
62006  assert( j<p->nLabel );
62007  if( ALWAYS(j>=0) && p->aLabel ){
62008    p->aLabel[j] = v->nOp;
62009  }
62010  p->iFixedOp = v->nOp - 1;
62011}
62012
62013/*
62014** Mark the VDBE as one that can only be run one time.
62015*/
62016SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
62017  p->runOnlyOnce = 1;
62018}
62019
62020#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
62021
62022/*
62023** The following type and function are used to iterate through all opcodes
62024** in a Vdbe main program and each of the sub-programs (triggers) it may
62025** invoke directly or indirectly. It should be used as follows:
62026**
62027**   Op *pOp;
62028**   VdbeOpIter sIter;
62029**
62030**   memset(&sIter, 0, sizeof(sIter));
62031**   sIter.v = v;                            // v is of type Vdbe*
62032**   while( (pOp = opIterNext(&sIter)) ){
62033**     // Do something with pOp
62034**   }
62035**   sqlite3DbFree(v->db, sIter.apSub);
62036**
62037*/
62038typedef struct VdbeOpIter VdbeOpIter;
62039struct VdbeOpIter {
62040  Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
62041  SubProgram **apSub;        /* Array of subprograms */
62042  int nSub;                  /* Number of entries in apSub */
62043  int iAddr;                 /* Address of next instruction to return */
62044  int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
62045};
62046static Op *opIterNext(VdbeOpIter *p){
62047  Vdbe *v = p->v;
62048  Op *pRet = 0;
62049  Op *aOp;
62050  int nOp;
62051
62052  if( p->iSub<=p->nSub ){
62053
62054    if( p->iSub==0 ){
62055      aOp = v->aOp;
62056      nOp = v->nOp;
62057    }else{
62058      aOp = p->apSub[p->iSub-1]->aOp;
62059      nOp = p->apSub[p->iSub-1]->nOp;
62060    }
62061    assert( p->iAddr<nOp );
62062
62063    pRet = &aOp[p->iAddr];
62064    p->iAddr++;
62065    if( p->iAddr==nOp ){
62066      p->iSub++;
62067      p->iAddr = 0;
62068    }
62069
62070    if( pRet->p4type==P4_SUBPROGRAM ){
62071      int nByte = (p->nSub+1)*sizeof(SubProgram*);
62072      int j;
62073      for(j=0; j<p->nSub; j++){
62074        if( p->apSub[j]==pRet->p4.pProgram ) break;
62075      }
62076      if( j==p->nSub ){
62077        p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
62078        if( !p->apSub ){
62079          pRet = 0;
62080        }else{
62081          p->apSub[p->nSub++] = pRet->p4.pProgram;
62082        }
62083      }
62084    }
62085  }
62086
62087  return pRet;
62088}
62089
62090/*
62091** Check if the program stored in the VM associated with pParse may
62092** throw an ABORT exception (causing the statement, but not entire transaction
62093** to be rolled back). This condition is true if the main program or any
62094** sub-programs contains any of the following:
62095**
62096**   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
62097**   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
62098**   *  OP_Destroy
62099**   *  OP_VUpdate
62100**   *  OP_VRename
62101**   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
62102**
62103** Then check that the value of Parse.mayAbort is true if an
62104** ABORT may be thrown, or false otherwise. Return true if it does
62105** match, or false otherwise. This function is intended to be used as
62106** part of an assert statement in the compiler. Similar to:
62107**
62108**   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
62109*/
62110SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
62111  int hasAbort = 0;
62112  Op *pOp;
62113  VdbeOpIter sIter;
62114  memset(&sIter, 0, sizeof(sIter));
62115  sIter.v = v;
62116
62117  while( (pOp = opIterNext(&sIter))!=0 ){
62118    int opcode = pOp->opcode;
62119    if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
62120#ifndef SQLITE_OMIT_FOREIGN_KEY
62121     || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
62122#endif
62123     || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
62124      && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
62125    ){
62126      hasAbort = 1;
62127      break;
62128    }
62129  }
62130  sqlite3DbFree(v->db, sIter.apSub);
62131
62132  /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
62133  ** If malloc failed, then the while() loop above may not have iterated
62134  ** through all opcodes and hasAbort may be set incorrectly. Return
62135  ** true for this case to prevent the assert() in the callers frame
62136  ** from failing.  */
62137  return ( v->db->mallocFailed || hasAbort==mayAbort );
62138}
62139#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
62140
62141/*
62142** Loop through the program looking for P2 values that are negative
62143** on jump instructions.  Each such value is a label.  Resolve the
62144** label by setting the P2 value to its correct non-zero value.
62145**
62146** This routine is called once after all opcodes have been inserted.
62147**
62148** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
62149** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
62150** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
62151**
62152** The Op.opflags field is set on all opcodes.
62153*/
62154static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
62155  int i;
62156  int nMaxArgs = *pMaxFuncArgs;
62157  Op *pOp;
62158  Parse *pParse = p->pParse;
62159  int *aLabel = pParse->aLabel;
62160  p->readOnly = 1;
62161  p->bIsReader = 0;
62162  for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
62163    u8 opcode = pOp->opcode;
62164
62165    /* NOTE: Be sure to update mkopcodeh.awk when adding or removing
62166    ** cases from this switch! */
62167    switch( opcode ){
62168      case OP_Function:
62169      case OP_AggStep: {
62170        if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
62171        break;
62172      }
62173      case OP_Transaction: {
62174        if( pOp->p2!=0 ) p->readOnly = 0;
62175        /* fall thru */
62176      }
62177      case OP_AutoCommit:
62178      case OP_Savepoint: {
62179        p->bIsReader = 1;
62180        break;
62181      }
62182#ifndef SQLITE_OMIT_WAL
62183      case OP_Checkpoint:
62184#endif
62185      case OP_Vacuum:
62186      case OP_JournalMode: {
62187        p->readOnly = 0;
62188        p->bIsReader = 1;
62189        break;
62190      }
62191#ifndef SQLITE_OMIT_VIRTUALTABLE
62192      case OP_VUpdate: {
62193        if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
62194        break;
62195      }
62196      case OP_VFilter: {
62197        int n;
62198        assert( p->nOp - i >= 3 );
62199        assert( pOp[-1].opcode==OP_Integer );
62200        n = pOp[-1].p1;
62201        if( n>nMaxArgs ) nMaxArgs = n;
62202        break;
62203      }
62204#endif
62205      case OP_Next:
62206      case OP_NextIfOpen:
62207      case OP_SorterNext: {
62208        pOp->p4.xAdvance = sqlite3BtreeNext;
62209        pOp->p4type = P4_ADVANCE;
62210        break;
62211      }
62212      case OP_Prev:
62213      case OP_PrevIfOpen: {
62214        pOp->p4.xAdvance = sqlite3BtreePrevious;
62215        pOp->p4type = P4_ADVANCE;
62216        break;
62217      }
62218    }
62219
62220    pOp->opflags = sqlite3OpcodeProperty[opcode];
62221    if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
62222      assert( -1-pOp->p2<pParse->nLabel );
62223      pOp->p2 = aLabel[-1-pOp->p2];
62224    }
62225  }
62226  sqlite3DbFree(p->db, pParse->aLabel);
62227  pParse->aLabel = 0;
62228  pParse->nLabel = 0;
62229  *pMaxFuncArgs = nMaxArgs;
62230  assert( p->bIsReader!=0 || p->btreeMask==0 );
62231}
62232
62233/*
62234** Return the address of the next instruction to be inserted.
62235*/
62236SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
62237  assert( p->magic==VDBE_MAGIC_INIT );
62238  return p->nOp;
62239}
62240
62241/*
62242** This function returns a pointer to the array of opcodes associated with
62243** the Vdbe passed as the first argument. It is the callers responsibility
62244** to arrange for the returned array to be eventually freed using the
62245** vdbeFreeOpArray() function.
62246**
62247** Before returning, *pnOp is set to the number of entries in the returned
62248** array. Also, *pnMaxArg is set to the larger of its current value and
62249** the number of entries in the Vdbe.apArg[] array required to execute the
62250** returned program.
62251*/
62252SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
62253  VdbeOp *aOp = p->aOp;
62254  assert( aOp && !p->db->mallocFailed );
62255
62256  /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
62257  assert( p->btreeMask==0 );
62258
62259  resolveP2Values(p, pnMaxArg);
62260  *pnOp = p->nOp;
62261  p->aOp = 0;
62262  return aOp;
62263}
62264
62265/*
62266** Add a whole list of operations to the operation stack.  Return the
62267** address of the first operation added.
62268*/
62269SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp, int iLineno){
62270  int addr;
62271  assert( p->magic==VDBE_MAGIC_INIT );
62272  if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p) ){
62273    return 0;
62274  }
62275  addr = p->nOp;
62276  if( ALWAYS(nOp>0) ){
62277    int i;
62278    VdbeOpList const *pIn = aOp;
62279    for(i=0; i<nOp; i++, pIn++){
62280      int p2 = pIn->p2;
62281      VdbeOp *pOut = &p->aOp[i+addr];
62282      pOut->opcode = pIn->opcode;
62283      pOut->p1 = pIn->p1;
62284      if( p2<0 ){
62285        assert( sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP );
62286        pOut->p2 = addr + ADDR(p2);
62287      }else{
62288        pOut->p2 = p2;
62289      }
62290      pOut->p3 = pIn->p3;
62291      pOut->p4type = P4_NOTUSED;
62292      pOut->p4.p = 0;
62293      pOut->p5 = 0;
62294#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
62295      pOut->zComment = 0;
62296#endif
62297#ifdef SQLITE_VDBE_COVERAGE
62298      pOut->iSrcLine = iLineno+i;
62299#else
62300      (void)iLineno;
62301#endif
62302#ifdef SQLITE_DEBUG
62303      if( p->db->flags & SQLITE_VdbeAddopTrace ){
62304        sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
62305      }
62306#endif
62307    }
62308    p->nOp += nOp;
62309  }
62310  return addr;
62311}
62312
62313/*
62314** Change the value of the P1 operand for a specific instruction.
62315** This routine is useful when a large program is loaded from a
62316** static array using sqlite3VdbeAddOpList but we want to make a
62317** few minor changes to the program.
62318*/
62319SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
62320  assert( p!=0 );
62321  if( ((u32)p->nOp)>addr ){
62322    p->aOp[addr].p1 = val;
62323  }
62324}
62325
62326/*
62327** Change the value of the P2 operand for a specific instruction.
62328** This routine is useful for setting a jump destination.
62329*/
62330SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
62331  assert( p!=0 );
62332  if( ((u32)p->nOp)>addr ){
62333    p->aOp[addr].p2 = val;
62334  }
62335}
62336
62337/*
62338** Change the value of the P3 operand for a specific instruction.
62339*/
62340SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
62341  assert( p!=0 );
62342  if( ((u32)p->nOp)>addr ){
62343    p->aOp[addr].p3 = val;
62344  }
62345}
62346
62347/*
62348** Change the value of the P5 operand for the most recently
62349** added operation.
62350*/
62351SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
62352  assert( p!=0 );
62353  if( p->aOp ){
62354    assert( p->nOp>0 );
62355    p->aOp[p->nOp-1].p5 = val;
62356  }
62357}
62358
62359/*
62360** Change the P2 operand of instruction addr so that it points to
62361** the address of the next instruction to be coded.
62362*/
62363SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
62364  sqlite3VdbeChangeP2(p, addr, p->nOp);
62365  p->pParse->iFixedOp = p->nOp - 1;
62366}
62367
62368
62369/*
62370** If the input FuncDef structure is ephemeral, then free it.  If
62371** the FuncDef is not ephermal, then do nothing.
62372*/
62373static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
62374  if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
62375    sqlite3DbFree(db, pDef);
62376  }
62377}
62378
62379static void vdbeFreeOpArray(sqlite3 *, Op *, int);
62380
62381/*
62382** Delete a P4 value if necessary.
62383*/
62384static void freeP4(sqlite3 *db, int p4type, void *p4){
62385  if( p4 ){
62386    assert( db );
62387    switch( p4type ){
62388      case P4_REAL:
62389      case P4_INT64:
62390      case P4_DYNAMIC:
62391      case P4_INTARRAY: {
62392        sqlite3DbFree(db, p4);
62393        break;
62394      }
62395      case P4_KEYINFO: {
62396        if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
62397        break;
62398      }
62399      case P4_MPRINTF: {
62400        if( db->pnBytesFreed==0 ) sqlite3_free(p4);
62401        break;
62402      }
62403      case P4_FUNCDEF: {
62404        freeEphemeralFunction(db, (FuncDef*)p4);
62405        break;
62406      }
62407      case P4_MEM: {
62408        if( db->pnBytesFreed==0 ){
62409          sqlite3ValueFree((sqlite3_value*)p4);
62410        }else{
62411          Mem *p = (Mem*)p4;
62412          sqlite3DbFree(db, p->zMalloc);
62413          sqlite3DbFree(db, p);
62414        }
62415        break;
62416      }
62417      case P4_VTAB : {
62418        if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
62419        break;
62420      }
62421    }
62422  }
62423}
62424
62425/*
62426** Free the space allocated for aOp and any p4 values allocated for the
62427** opcodes contained within. If aOp is not NULL it is assumed to contain
62428** nOp entries.
62429*/
62430static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
62431  if( aOp ){
62432    Op *pOp;
62433    for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
62434      freeP4(db, pOp->p4type, pOp->p4.p);
62435#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
62436      sqlite3DbFree(db, pOp->zComment);
62437#endif
62438    }
62439  }
62440  sqlite3DbFree(db, aOp);
62441}
62442
62443/*
62444** Link the SubProgram object passed as the second argument into the linked
62445** list at Vdbe.pSubProgram. This list is used to delete all sub-program
62446** objects when the VM is no longer required.
62447*/
62448SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
62449  p->pNext = pVdbe->pProgram;
62450  pVdbe->pProgram = p;
62451}
62452
62453/*
62454** Change the opcode at addr into OP_Noop
62455*/
62456SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
62457  if( p->aOp ){
62458    VdbeOp *pOp = &p->aOp[addr];
62459    sqlite3 *db = p->db;
62460    freeP4(db, pOp->p4type, pOp->p4.p);
62461    memset(pOp, 0, sizeof(pOp[0]));
62462    pOp->opcode = OP_Noop;
62463    if( addr==p->nOp-1 ) p->nOp--;
62464  }
62465}
62466
62467/*
62468** Remove the last opcode inserted
62469*/
62470SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
62471  if( (p->nOp-1)>(p->pParse->iFixedOp) && p->aOp[p->nOp-1].opcode==op ){
62472    sqlite3VdbeChangeToNoop(p, p->nOp-1);
62473    return 1;
62474  }else{
62475    return 0;
62476  }
62477}
62478
62479/*
62480** Change the value of the P4 operand for a specific instruction.
62481** This routine is useful when a large program is loaded from a
62482** static array using sqlite3VdbeAddOpList but we want to make a
62483** few minor changes to the program.
62484**
62485** If n>=0 then the P4 operand is dynamic, meaning that a copy of
62486** the string is made into memory obtained from sqlite3_malloc().
62487** A value of n==0 means copy bytes of zP4 up to and including the
62488** first null byte.  If n>0 then copy n+1 bytes of zP4.
62489**
62490** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
62491** to a string or structure that is guaranteed to exist for the lifetime of
62492** the Vdbe. In these cases we can just copy the pointer.
62493**
62494** If addr<0 then change P4 on the most recently inserted instruction.
62495*/
62496SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
62497  Op *pOp;
62498  sqlite3 *db;
62499  assert( p!=0 );
62500  db = p->db;
62501  assert( p->magic==VDBE_MAGIC_INIT );
62502  if( p->aOp==0 || db->mallocFailed ){
62503    if( n!=P4_VTAB ){
62504      freeP4(db, n, (void*)*(char**)&zP4);
62505    }
62506    return;
62507  }
62508  assert( p->nOp>0 );
62509  assert( addr<p->nOp );
62510  if( addr<0 ){
62511    addr = p->nOp - 1;
62512  }
62513  pOp = &p->aOp[addr];
62514  assert( pOp->p4type==P4_NOTUSED
62515       || pOp->p4type==P4_INT32
62516       || pOp->p4type==P4_KEYINFO );
62517  freeP4(db, pOp->p4type, pOp->p4.p);
62518  pOp->p4.p = 0;
62519  if( n==P4_INT32 ){
62520    /* Note: this cast is safe, because the origin data point was an int
62521    ** that was cast to a (const char *). */
62522    pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
62523    pOp->p4type = P4_INT32;
62524  }else if( zP4==0 ){
62525    pOp->p4.p = 0;
62526    pOp->p4type = P4_NOTUSED;
62527  }else if( n==P4_KEYINFO ){
62528    pOp->p4.p = (void*)zP4;
62529    pOp->p4type = P4_KEYINFO;
62530  }else if( n==P4_VTAB ){
62531    pOp->p4.p = (void*)zP4;
62532    pOp->p4type = P4_VTAB;
62533    sqlite3VtabLock((VTable *)zP4);
62534    assert( ((VTable *)zP4)->db==p->db );
62535  }else if( n<0 ){
62536    pOp->p4.p = (void*)zP4;
62537    pOp->p4type = (signed char)n;
62538  }else{
62539    if( n==0 ) n = sqlite3Strlen30(zP4);
62540    pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
62541    pOp->p4type = P4_DYNAMIC;
62542  }
62543}
62544
62545/*
62546** Set the P4 on the most recently added opcode to the KeyInfo for the
62547** index given.
62548*/
62549SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
62550  Vdbe *v = pParse->pVdbe;
62551  assert( v!=0 );
62552  assert( pIdx!=0 );
62553  sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx),
62554                      P4_KEYINFO);
62555}
62556
62557#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
62558/*
62559** Change the comment on the most recently coded instruction.  Or
62560** insert a No-op and add the comment to that new instruction.  This
62561** makes the code easier to read during debugging.  None of this happens
62562** in a production build.
62563*/
62564static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
62565  assert( p->nOp>0 || p->aOp==0 );
62566  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
62567  if( p->nOp ){
62568    assert( p->aOp );
62569    sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
62570    p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
62571  }
62572}
62573SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
62574  va_list ap;
62575  if( p ){
62576    va_start(ap, zFormat);
62577    vdbeVComment(p, zFormat, ap);
62578    va_end(ap);
62579  }
62580}
62581SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
62582  va_list ap;
62583  if( p ){
62584    sqlite3VdbeAddOp0(p, OP_Noop);
62585    va_start(ap, zFormat);
62586    vdbeVComment(p, zFormat, ap);
62587    va_end(ap);
62588  }
62589}
62590#endif  /* NDEBUG */
62591
62592#ifdef SQLITE_VDBE_COVERAGE
62593/*
62594** Set the value if the iSrcLine field for the previously coded instruction.
62595*/
62596SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
62597  sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
62598}
62599#endif /* SQLITE_VDBE_COVERAGE */
62600
62601/*
62602** Return the opcode for a given address.  If the address is -1, then
62603** return the most recently inserted opcode.
62604**
62605** If a memory allocation error has occurred prior to the calling of this
62606** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
62607** is readable but not writable, though it is cast to a writable value.
62608** The return of a dummy opcode allows the call to continue functioning
62609** after a OOM fault without having to check to see if the return from
62610** this routine is a valid pointer.  But because the dummy.opcode is 0,
62611** dummy will never be written to.  This is verified by code inspection and
62612** by running with Valgrind.
62613*/
62614SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
62615  /* C89 specifies that the constant "dummy" will be initialized to all
62616  ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
62617  static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
62618  assert( p->magic==VDBE_MAGIC_INIT );
62619  if( addr<0 ){
62620    addr = p->nOp - 1;
62621  }
62622  assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
62623  if( p->db->mallocFailed ){
62624    return (VdbeOp*)&dummy;
62625  }else{
62626    return &p->aOp[addr];
62627  }
62628}
62629
62630#if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
62631/*
62632** Return an integer value for one of the parameters to the opcode pOp
62633** determined by character c.
62634*/
62635static int translateP(char c, const Op *pOp){
62636  if( c=='1' ) return pOp->p1;
62637  if( c=='2' ) return pOp->p2;
62638  if( c=='3' ) return pOp->p3;
62639  if( c=='4' ) return pOp->p4.i;
62640  return pOp->p5;
62641}
62642
62643/*
62644** Compute a string for the "comment" field of a VDBE opcode listing.
62645**
62646** The Synopsis: field in comments in the vdbe.c source file gets converted
62647** to an extra string that is appended to the sqlite3OpcodeName().  In the
62648** absence of other comments, this synopsis becomes the comment on the opcode.
62649** Some translation occurs:
62650**
62651**       "PX"      ->  "r[X]"
62652**       "PX@PY"   ->  "r[X..X+Y-1]"  or "r[x]" if y is 0 or 1
62653**       "PX@PY+1" ->  "r[X..X+Y]"    or "r[x]" if y is 0
62654**       "PY..PY"  ->  "r[X..Y]"      or "r[x]" if y<=x
62655*/
62656static int displayComment(
62657  const Op *pOp,     /* The opcode to be commented */
62658  const char *zP4,   /* Previously obtained value for P4 */
62659  char *zTemp,       /* Write result here */
62660  int nTemp          /* Space available in zTemp[] */
62661){
62662  const char *zOpName;
62663  const char *zSynopsis;
62664  int nOpName;
62665  int ii, jj;
62666  zOpName = sqlite3OpcodeName(pOp->opcode);
62667  nOpName = sqlite3Strlen30(zOpName);
62668  if( zOpName[nOpName+1] ){
62669    int seenCom = 0;
62670    char c;
62671    zSynopsis = zOpName += nOpName + 1;
62672    for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
62673      if( c=='P' ){
62674        c = zSynopsis[++ii];
62675        if( c=='4' ){
62676          sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
62677        }else if( c=='X' ){
62678          sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
62679          seenCom = 1;
62680        }else{
62681          int v1 = translateP(c, pOp);
62682          int v2;
62683          sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
62684          if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
62685            ii += 3;
62686            jj += sqlite3Strlen30(zTemp+jj);
62687            v2 = translateP(zSynopsis[ii], pOp);
62688            if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
62689              ii += 2;
62690              v2++;
62691            }
62692            if( v2>1 ){
62693              sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
62694            }
62695          }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
62696            ii += 4;
62697          }
62698        }
62699        jj += sqlite3Strlen30(zTemp+jj);
62700      }else{
62701        zTemp[jj++] = c;
62702      }
62703    }
62704    if( !seenCom && jj<nTemp-5 && pOp->zComment ){
62705      sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
62706      jj += sqlite3Strlen30(zTemp+jj);
62707    }
62708    if( jj<nTemp ) zTemp[jj] = 0;
62709  }else if( pOp->zComment ){
62710    sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
62711    jj = sqlite3Strlen30(zTemp);
62712  }else{
62713    zTemp[0] = 0;
62714    jj = 0;
62715  }
62716  return jj;
62717}
62718#endif /* SQLITE_DEBUG */
62719
62720
62721#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
62722     || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
62723/*
62724** Compute a string that describes the P4 parameter for an opcode.
62725** Use zTemp for any required temporary buffer space.
62726*/
62727static char *displayP4(Op *pOp, char *zTemp, int nTemp){
62728  char *zP4 = zTemp;
62729  assert( nTemp>=20 );
62730  switch( pOp->p4type ){
62731    case P4_KEYINFO: {
62732      int i, j;
62733      KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
62734      assert( pKeyInfo->aSortOrder!=0 );
62735      sqlite3_snprintf(nTemp, zTemp, "k(%d", pKeyInfo->nField);
62736      i = sqlite3Strlen30(zTemp);
62737      for(j=0; j<pKeyInfo->nField; j++){
62738        CollSeq *pColl = pKeyInfo->aColl[j];
62739        const char *zColl = pColl ? pColl->zName : "nil";
62740        int n = sqlite3Strlen30(zColl);
62741        if( n==6 && memcmp(zColl,"BINARY",6)==0 ){
62742          zColl = "B";
62743          n = 1;
62744        }
62745        if( i+n>nTemp-6 ){
62746          memcpy(&zTemp[i],",...",4);
62747          break;
62748        }
62749        zTemp[i++] = ',';
62750        if( pKeyInfo->aSortOrder[j] ){
62751          zTemp[i++] = '-';
62752        }
62753        memcpy(&zTemp[i], zColl, n+1);
62754        i += n;
62755      }
62756      zTemp[i++] = ')';
62757      zTemp[i] = 0;
62758      assert( i<nTemp );
62759      break;
62760    }
62761    case P4_COLLSEQ: {
62762      CollSeq *pColl = pOp->p4.pColl;
62763      sqlite3_snprintf(nTemp, zTemp, "(%.20s)", pColl->zName);
62764      break;
62765    }
62766    case P4_FUNCDEF: {
62767      FuncDef *pDef = pOp->p4.pFunc;
62768      sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
62769      break;
62770    }
62771    case P4_INT64: {
62772      sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
62773      break;
62774    }
62775    case P4_INT32: {
62776      sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
62777      break;
62778    }
62779    case P4_REAL: {
62780      sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
62781      break;
62782    }
62783    case P4_MEM: {
62784      Mem *pMem = pOp->p4.pMem;
62785      if( pMem->flags & MEM_Str ){
62786        zP4 = pMem->z;
62787      }else if( pMem->flags & MEM_Int ){
62788        sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
62789      }else if( pMem->flags & MEM_Real ){
62790        sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
62791      }else if( pMem->flags & MEM_Null ){
62792        sqlite3_snprintf(nTemp, zTemp, "NULL");
62793      }else{
62794        assert( pMem->flags & MEM_Blob );
62795        zP4 = "(blob)";
62796      }
62797      break;
62798    }
62799#ifndef SQLITE_OMIT_VIRTUALTABLE
62800    case P4_VTAB: {
62801      sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
62802      sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
62803      break;
62804    }
62805#endif
62806    case P4_INTARRAY: {
62807      sqlite3_snprintf(nTemp, zTemp, "intarray");
62808      break;
62809    }
62810    case P4_SUBPROGRAM: {
62811      sqlite3_snprintf(nTemp, zTemp, "program");
62812      break;
62813    }
62814    case P4_ADVANCE: {
62815      zTemp[0] = 0;
62816      break;
62817    }
62818    default: {
62819      zP4 = pOp->p4.z;
62820      if( zP4==0 ){
62821        zP4 = zTemp;
62822        zTemp[0] = 0;
62823      }
62824    }
62825  }
62826  assert( zP4!=0 );
62827  return zP4;
62828}
62829#endif
62830
62831/*
62832** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
62833**
62834** The prepared statements need to know in advance the complete set of
62835** attached databases that will be use.  A mask of these databases
62836** is maintained in p->btreeMask.  The p->lockMask value is the subset of
62837** p->btreeMask of databases that will require a lock.
62838*/
62839SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
62840  assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
62841  assert( i<(int)sizeof(p->btreeMask)*8 );
62842  p->btreeMask |= ((yDbMask)1)<<i;
62843  if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
62844    p->lockMask |= ((yDbMask)1)<<i;
62845  }
62846}
62847
62848#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
62849/*
62850** If SQLite is compiled to support shared-cache mode and to be threadsafe,
62851** this routine obtains the mutex associated with each BtShared structure
62852** that may be accessed by the VM passed as an argument. In doing so it also
62853** sets the BtShared.db member of each of the BtShared structures, ensuring
62854** that the correct busy-handler callback is invoked if required.
62855**
62856** If SQLite is not threadsafe but does support shared-cache mode, then
62857** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
62858** of all of BtShared structures accessible via the database handle
62859** associated with the VM.
62860**
62861** If SQLite is not threadsafe and does not support shared-cache mode, this
62862** function is a no-op.
62863**
62864** The p->btreeMask field is a bitmask of all btrees that the prepared
62865** statement p will ever use.  Let N be the number of bits in p->btreeMask
62866** corresponding to btrees that use shared cache.  Then the runtime of
62867** this routine is N*N.  But as N is rarely more than 1, this should not
62868** be a problem.
62869*/
62870SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
62871  int i;
62872  yDbMask mask;
62873  sqlite3 *db;
62874  Db *aDb;
62875  int nDb;
62876  if( p->lockMask==0 ) return;  /* The common case */
62877  db = p->db;
62878  aDb = db->aDb;
62879  nDb = db->nDb;
62880  for(i=0, mask=1; i<nDb; i++, mask += mask){
62881    if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
62882      sqlite3BtreeEnter(aDb[i].pBt);
62883    }
62884  }
62885}
62886#endif
62887
62888#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
62889/*
62890** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
62891*/
62892SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
62893  int i;
62894  yDbMask mask;
62895  sqlite3 *db;
62896  Db *aDb;
62897  int nDb;
62898  if( p->lockMask==0 ) return;  /* The common case */
62899  db = p->db;
62900  aDb = db->aDb;
62901  nDb = db->nDb;
62902  for(i=0, mask=1; i<nDb; i++, mask += mask){
62903    if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
62904      sqlite3BtreeLeave(aDb[i].pBt);
62905    }
62906  }
62907}
62908#endif
62909
62910#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
62911/*
62912** Print a single opcode.  This routine is used for debugging only.
62913*/
62914SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
62915  char *zP4;
62916  char zPtr[50];
62917  char zCom[100];
62918  static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
62919  if( pOut==0 ) pOut = stdout;
62920  zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
62921#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
62922  displayComment(pOp, zP4, zCom, sizeof(zCom));
62923#else
62924  zCom[0] = 0;
62925#endif
62926  /* NB:  The sqlite3OpcodeName() function is implemented by code created
62927  ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
62928  ** information from the vdbe.c source text */
62929  fprintf(pOut, zFormat1, pc,
62930      sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
62931      zCom
62932  );
62933  fflush(pOut);
62934}
62935#endif
62936
62937/*
62938** Release an array of N Mem elements
62939*/
62940static void releaseMemArray(Mem *p, int N){
62941  if( p && N ){
62942    Mem *pEnd;
62943    sqlite3 *db = p->db;
62944    u8 malloc_failed = db->mallocFailed;
62945    if( db->pnBytesFreed ){
62946      for(pEnd=&p[N]; p<pEnd; p++){
62947        sqlite3DbFree(db, p->zMalloc);
62948      }
62949      return;
62950    }
62951    for(pEnd=&p[N]; p<pEnd; p++){
62952      assert( (&p[1])==pEnd || p[0].db==p[1].db );
62953      assert( sqlite3VdbeCheckMemInvariants(p) );
62954
62955      /* This block is really an inlined version of sqlite3VdbeMemRelease()
62956      ** that takes advantage of the fact that the memory cell value is
62957      ** being set to NULL after releasing any dynamic resources.
62958      **
62959      ** The justification for duplicating code is that according to
62960      ** callgrind, this causes a certain test case to hit the CPU 4.7
62961      ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
62962      ** sqlite3MemRelease() were called from here. With -O2, this jumps
62963      ** to 6.6 percent. The test case is inserting 1000 rows into a table
62964      ** with no indexes using a single prepared INSERT statement, bind()
62965      ** and reset(). Inserts are grouped into a transaction.
62966      */
62967      testcase( p->flags & MEM_Agg );
62968      testcase( p->flags & MEM_Dyn );
62969      testcase( p->flags & MEM_Frame );
62970      testcase( p->flags & MEM_RowSet );
62971      if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
62972        sqlite3VdbeMemRelease(p);
62973      }else if( p->zMalloc ){
62974        sqlite3DbFree(db, p->zMalloc);
62975        p->zMalloc = 0;
62976      }
62977
62978      p->flags = MEM_Undefined;
62979    }
62980    db->mallocFailed = malloc_failed;
62981  }
62982}
62983
62984/*
62985** Delete a VdbeFrame object and its contents. VdbeFrame objects are
62986** allocated by the OP_Program opcode in sqlite3VdbeExec().
62987*/
62988SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
62989  int i;
62990  Mem *aMem = VdbeFrameMem(p);
62991  VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
62992  for(i=0; i<p->nChildCsr; i++){
62993    sqlite3VdbeFreeCursor(p->v, apCsr[i]);
62994  }
62995  releaseMemArray(aMem, p->nChildMem);
62996  sqlite3DbFree(p->v->db, p);
62997}
62998
62999#ifndef SQLITE_OMIT_EXPLAIN
63000/*
63001** Give a listing of the program in the virtual machine.
63002**
63003** The interface is the same as sqlite3VdbeExec().  But instead of
63004** running the code, it invokes the callback once for each instruction.
63005** This feature is used to implement "EXPLAIN".
63006**
63007** When p->explain==1, each instruction is listed.  When
63008** p->explain==2, only OP_Explain instructions are listed and these
63009** are shown in a different format.  p->explain==2 is used to implement
63010** EXPLAIN QUERY PLAN.
63011**
63012** When p->explain==1, first the main program is listed, then each of
63013** the trigger subprograms are listed one by one.
63014*/
63015SQLITE_PRIVATE int sqlite3VdbeList(
63016  Vdbe *p                   /* The VDBE */
63017){
63018  int nRow;                            /* Stop when row count reaches this */
63019  int nSub = 0;                        /* Number of sub-vdbes seen so far */
63020  SubProgram **apSub = 0;              /* Array of sub-vdbes */
63021  Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
63022  sqlite3 *db = p->db;                 /* The database connection */
63023  int i;                               /* Loop counter */
63024  int rc = SQLITE_OK;                  /* Return code */
63025  Mem *pMem = &p->aMem[1];             /* First Mem of result set */
63026
63027  assert( p->explain );
63028  assert( p->magic==VDBE_MAGIC_RUN );
63029  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
63030
63031  /* Even though this opcode does not use dynamic strings for
63032  ** the result, result columns may become dynamic if the user calls
63033  ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
63034  */
63035  releaseMemArray(pMem, 8);
63036  p->pResultSet = 0;
63037
63038  if( p->rc==SQLITE_NOMEM ){
63039    /* This happens if a malloc() inside a call to sqlite3_column_text() or
63040    ** sqlite3_column_text16() failed.  */
63041    db->mallocFailed = 1;
63042    return SQLITE_ERROR;
63043  }
63044
63045  /* When the number of output rows reaches nRow, that means the
63046  ** listing has finished and sqlite3_step() should return SQLITE_DONE.
63047  ** nRow is the sum of the number of rows in the main program, plus
63048  ** the sum of the number of rows in all trigger subprograms encountered
63049  ** so far.  The nRow value will increase as new trigger subprograms are
63050  ** encountered, but p->pc will eventually catch up to nRow.
63051  */
63052  nRow = p->nOp;
63053  if( p->explain==1 ){
63054    /* The first 8 memory cells are used for the result set.  So we will
63055    ** commandeer the 9th cell to use as storage for an array of pointers
63056    ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
63057    ** cells.  */
63058    assert( p->nMem>9 );
63059    pSub = &p->aMem[9];
63060    if( pSub->flags&MEM_Blob ){
63061      /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
63062      ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
63063      nSub = pSub->n/sizeof(Vdbe*);
63064      apSub = (SubProgram **)pSub->z;
63065    }
63066    for(i=0; i<nSub; i++){
63067      nRow += apSub[i]->nOp;
63068    }
63069  }
63070
63071  do{
63072    i = p->pc++;
63073  }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
63074  if( i>=nRow ){
63075    p->rc = SQLITE_OK;
63076    rc = SQLITE_DONE;
63077  }else if( db->u1.isInterrupted ){
63078    p->rc = SQLITE_INTERRUPT;
63079    rc = SQLITE_ERROR;
63080    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
63081  }else{
63082    char *zP4;
63083    Op *pOp;
63084    if( i<p->nOp ){
63085      /* The output line number is small enough that we are still in the
63086      ** main program. */
63087      pOp = &p->aOp[i];
63088    }else{
63089      /* We are currently listing subprograms.  Figure out which one and
63090      ** pick up the appropriate opcode. */
63091      int j;
63092      i -= p->nOp;
63093      for(j=0; i>=apSub[j]->nOp; j++){
63094        i -= apSub[j]->nOp;
63095      }
63096      pOp = &apSub[j]->aOp[i];
63097    }
63098    if( p->explain==1 ){
63099      pMem->flags = MEM_Int;
63100      pMem->u.i = i;                                /* Program counter */
63101      pMem++;
63102
63103      pMem->flags = MEM_Static|MEM_Str|MEM_Term;
63104      pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
63105      assert( pMem->z!=0 );
63106      pMem->n = sqlite3Strlen30(pMem->z);
63107      pMem->enc = SQLITE_UTF8;
63108      pMem++;
63109
63110      /* When an OP_Program opcode is encounter (the only opcode that has
63111      ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
63112      ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
63113      ** has not already been seen.
63114      */
63115      if( pOp->p4type==P4_SUBPROGRAM ){
63116        int nByte = (nSub+1)*sizeof(SubProgram*);
63117        int j;
63118        for(j=0; j<nSub; j++){
63119          if( apSub[j]==pOp->p4.pProgram ) break;
63120        }
63121        if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
63122          apSub = (SubProgram **)pSub->z;
63123          apSub[nSub++] = pOp->p4.pProgram;
63124          pSub->flags |= MEM_Blob;
63125          pSub->n = nSub*sizeof(SubProgram*);
63126        }
63127      }
63128    }
63129
63130    pMem->flags = MEM_Int;
63131    pMem->u.i = pOp->p1;                          /* P1 */
63132    pMem++;
63133
63134    pMem->flags = MEM_Int;
63135    pMem->u.i = pOp->p2;                          /* P2 */
63136    pMem++;
63137
63138    pMem->flags = MEM_Int;
63139    pMem->u.i = pOp->p3;                          /* P3 */
63140    pMem++;
63141
63142    if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
63143      assert( p->db->mallocFailed );
63144      return SQLITE_ERROR;
63145    }
63146    pMem->flags = MEM_Str|MEM_Term;
63147    zP4 = displayP4(pOp, pMem->z, 32);
63148    if( zP4!=pMem->z ){
63149      sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
63150    }else{
63151      assert( pMem->z!=0 );
63152      pMem->n = sqlite3Strlen30(pMem->z);
63153      pMem->enc = SQLITE_UTF8;
63154    }
63155    pMem++;
63156
63157    if( p->explain==1 ){
63158      if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
63159        assert( p->db->mallocFailed );
63160        return SQLITE_ERROR;
63161      }
63162      pMem->flags = MEM_Str|MEM_Term;
63163      pMem->n = 2;
63164      sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
63165      pMem->enc = SQLITE_UTF8;
63166      pMem++;
63167
63168#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
63169      if( sqlite3VdbeMemGrow(pMem, 500, 0) ){
63170        assert( p->db->mallocFailed );
63171        return SQLITE_ERROR;
63172      }
63173      pMem->flags = MEM_Str|MEM_Term;
63174      pMem->n = displayComment(pOp, zP4, pMem->z, 500);
63175      pMem->enc = SQLITE_UTF8;
63176#else
63177      pMem->flags = MEM_Null;                       /* Comment */
63178#endif
63179    }
63180
63181    p->nResColumn = 8 - 4*(p->explain-1);
63182    p->pResultSet = &p->aMem[1];
63183    p->rc = SQLITE_OK;
63184    rc = SQLITE_ROW;
63185  }
63186  return rc;
63187}
63188#endif /* SQLITE_OMIT_EXPLAIN */
63189
63190#ifdef SQLITE_DEBUG
63191/*
63192** Print the SQL that was used to generate a VDBE program.
63193*/
63194SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
63195  const char *z = 0;
63196  if( p->zSql ){
63197    z = p->zSql;
63198  }else if( p->nOp>=1 ){
63199    const VdbeOp *pOp = &p->aOp[0];
63200    if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
63201      z = pOp->p4.z;
63202      while( sqlite3Isspace(*z) ) z++;
63203    }
63204  }
63205  if( z ) printf("SQL: [%s]\n", z);
63206}
63207#endif
63208
63209#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
63210/*
63211** Print an IOTRACE message showing SQL content.
63212*/
63213SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
63214  int nOp = p->nOp;
63215  VdbeOp *pOp;
63216  if( sqlite3IoTrace==0 ) return;
63217  if( nOp<1 ) return;
63218  pOp = &p->aOp[0];
63219  if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
63220    int i, j;
63221    char z[1000];
63222    sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
63223    for(i=0; sqlite3Isspace(z[i]); i++){}
63224    for(j=0; z[i]; i++){
63225      if( sqlite3Isspace(z[i]) ){
63226        if( z[i-1]!=' ' ){
63227          z[j++] = ' ';
63228        }
63229      }else{
63230        z[j++] = z[i];
63231      }
63232    }
63233    z[j] = 0;
63234    sqlite3IoTrace("SQL %s\n", z);
63235  }
63236}
63237#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
63238
63239/*
63240** Allocate space from a fixed size buffer and return a pointer to
63241** that space.  If insufficient space is available, return NULL.
63242**
63243** The pBuf parameter is the initial value of a pointer which will
63244** receive the new memory.  pBuf is normally NULL.  If pBuf is not
63245** NULL, it means that memory space has already been allocated and that
63246** this routine should not allocate any new memory.  When pBuf is not
63247** NULL simply return pBuf.  Only allocate new memory space when pBuf
63248** is NULL.
63249**
63250** nByte is the number of bytes of space needed.
63251**
63252** *ppFrom points to available space and pEnd points to the end of the
63253** available space.  When space is allocated, *ppFrom is advanced past
63254** the end of the allocated space.
63255**
63256** *pnByte is a counter of the number of bytes of space that have failed
63257** to allocate.  If there is insufficient space in *ppFrom to satisfy the
63258** request, then increment *pnByte by the amount of the request.
63259*/
63260static void *allocSpace(
63261  void *pBuf,          /* Where return pointer will be stored */
63262  int nByte,           /* Number of bytes to allocate */
63263  u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
63264  u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
63265  int *pnByte          /* If allocation cannot be made, increment *pnByte */
63266){
63267  assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
63268  if( pBuf ) return pBuf;
63269  nByte = ROUND8(nByte);
63270  if( &(*ppFrom)[nByte] <= pEnd ){
63271    pBuf = (void*)*ppFrom;
63272    *ppFrom += nByte;
63273  }else{
63274    *pnByte += nByte;
63275  }
63276  return pBuf;
63277}
63278
63279/*
63280** Rewind the VDBE back to the beginning in preparation for
63281** running it.
63282*/
63283SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
63284#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
63285  int i;
63286#endif
63287  assert( p!=0 );
63288  assert( p->magic==VDBE_MAGIC_INIT );
63289
63290  /* There should be at least one opcode.
63291  */
63292  assert( p->nOp>0 );
63293
63294  /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
63295  p->magic = VDBE_MAGIC_RUN;
63296
63297#ifdef SQLITE_DEBUG
63298  for(i=1; i<p->nMem; i++){
63299    assert( p->aMem[i].db==p->db );
63300  }
63301#endif
63302  p->pc = -1;
63303  p->rc = SQLITE_OK;
63304  p->errorAction = OE_Abort;
63305  p->magic = VDBE_MAGIC_RUN;
63306  p->nChange = 0;
63307  p->cacheCtr = 1;
63308  p->minWriteFileFormat = 255;
63309  p->iStatement = 0;
63310  p->nFkConstraint = 0;
63311#ifdef VDBE_PROFILE
63312  for(i=0; i<p->nOp; i++){
63313    p->aOp[i].cnt = 0;
63314    p->aOp[i].cycles = 0;
63315  }
63316#endif
63317}
63318
63319/*
63320** Prepare a virtual machine for execution for the first time after
63321** creating the virtual machine.  This involves things such
63322** as allocating stack space and initializing the program counter.
63323** After the VDBE has be prepped, it can be executed by one or more
63324** calls to sqlite3VdbeExec().
63325**
63326** This function may be called exact once on a each virtual machine.
63327** After this routine is called the VM has been "packaged" and is ready
63328** to run.  After this routine is called, futher calls to
63329** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
63330** the Vdbe from the Parse object that helped generate it so that the
63331** the Vdbe becomes an independent entity and the Parse object can be
63332** destroyed.
63333**
63334** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
63335** to its initial state after it has been run.
63336*/
63337SQLITE_PRIVATE void sqlite3VdbeMakeReady(
63338  Vdbe *p,                       /* The VDBE */
63339  Parse *pParse                  /* Parsing context */
63340){
63341  sqlite3 *db;                   /* The database connection */
63342  int nVar;                      /* Number of parameters */
63343  int nMem;                      /* Number of VM memory registers */
63344  int nCursor;                   /* Number of cursors required */
63345  int nArg;                      /* Number of arguments in subprograms */
63346  int nOnce;                     /* Number of OP_Once instructions */
63347  int n;                         /* Loop counter */
63348  u8 *zCsr;                      /* Memory available for allocation */
63349  u8 *zEnd;                      /* First byte past allocated memory */
63350  int nByte;                     /* How much extra memory is needed */
63351
63352  assert( p!=0 );
63353  assert( p->nOp>0 );
63354  assert( pParse!=0 );
63355  assert( p->magic==VDBE_MAGIC_INIT );
63356  assert( pParse==p->pParse );
63357  db = p->db;
63358  assert( db->mallocFailed==0 );
63359  nVar = pParse->nVar;
63360  nMem = pParse->nMem;
63361  nCursor = pParse->nTab;
63362  nArg = pParse->nMaxArg;
63363  nOnce = pParse->nOnce;
63364  if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
63365
63366  /* For each cursor required, also allocate a memory cell. Memory
63367  ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
63368  ** the vdbe program. Instead they are used to allocate space for
63369  ** VdbeCursor/BtCursor structures. The blob of memory associated with
63370  ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
63371  ** stores the blob of memory associated with cursor 1, etc.
63372  **
63373  ** See also: allocateCursor().
63374  */
63375  nMem += nCursor;
63376
63377  /* Allocate space for memory registers, SQL variables, VDBE cursors and
63378  ** an array to marshal SQL function arguments in.
63379  */
63380  zCsr = (u8*)&p->aOp[p->nOp];            /* Memory avaliable for allocation */
63381  zEnd = (u8*)&p->aOp[pParse->nOpAlloc];  /* First byte past end of zCsr[] */
63382
63383  resolveP2Values(p, &nArg);
63384  p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
63385  if( pParse->explain && nMem<10 ){
63386    nMem = 10;
63387  }
63388  memset(zCsr, 0, zEnd-zCsr);
63389  zCsr += (zCsr - (u8*)0)&7;
63390  assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
63391  p->expired = 0;
63392
63393  /* Memory for registers, parameters, cursor, etc, is allocated in two
63394  ** passes.  On the first pass, we try to reuse unused space at the
63395  ** end of the opcode array.  If we are unable to satisfy all memory
63396  ** requirements by reusing the opcode array tail, then the second
63397  ** pass will fill in the rest using a fresh allocation.
63398  **
63399  ** This two-pass approach that reuses as much memory as possible from
63400  ** the leftover space at the end of the opcode array can significantly
63401  ** reduce the amount of memory held by a prepared statement.
63402  */
63403  do {
63404    nByte = 0;
63405    p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
63406    p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
63407    p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
63408    p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
63409    p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
63410                          &zCsr, zEnd, &nByte);
63411    p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
63412    if( nByte ){
63413      p->pFree = sqlite3DbMallocZero(db, nByte);
63414    }
63415    zCsr = p->pFree;
63416    zEnd = &zCsr[nByte];
63417  }while( nByte && !db->mallocFailed );
63418
63419  p->nCursor = nCursor;
63420  p->nOnceFlag = nOnce;
63421  if( p->aVar ){
63422    p->nVar = (ynVar)nVar;
63423    for(n=0; n<nVar; n++){
63424      p->aVar[n].flags = MEM_Null;
63425      p->aVar[n].db = db;
63426    }
63427  }
63428  if( p->azVar ){
63429    p->nzVar = pParse->nzVar;
63430    memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
63431    memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
63432  }
63433  if( p->aMem ){
63434    p->aMem--;                      /* aMem[] goes from 1..nMem */
63435    p->nMem = nMem;                 /*       not from 0..nMem-1 */
63436    for(n=1; n<=nMem; n++){
63437      p->aMem[n].flags = MEM_Undefined;
63438      p->aMem[n].db = db;
63439    }
63440  }
63441  p->explain = pParse->explain;
63442  sqlite3VdbeRewind(p);
63443}
63444
63445/*
63446** Close a VDBE cursor and release all the resources that cursor
63447** happens to hold.
63448*/
63449SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
63450  if( pCx==0 ){
63451    return;
63452  }
63453  sqlite3VdbeSorterClose(p->db, pCx);
63454  if( pCx->pBt ){
63455    sqlite3BtreeClose(pCx->pBt);
63456    /* The pCx->pCursor will be close automatically, if it exists, by
63457    ** the call above. */
63458  }else if( pCx->pCursor ){
63459    sqlite3BtreeCloseCursor(pCx->pCursor);
63460  }
63461#ifndef SQLITE_OMIT_VIRTUALTABLE
63462  if( pCx->pVtabCursor ){
63463    sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
63464    const sqlite3_module *pModule = pVtabCursor->pVtab->pModule;
63465    p->inVtabMethod = 1;
63466    pModule->xClose(pVtabCursor);
63467    p->inVtabMethod = 0;
63468  }
63469#endif
63470}
63471
63472/*
63473** Copy the values stored in the VdbeFrame structure to its Vdbe. This
63474** is used, for example, when a trigger sub-program is halted to restore
63475** control to the main program.
63476*/
63477SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
63478  Vdbe *v = pFrame->v;
63479  v->aOnceFlag = pFrame->aOnceFlag;
63480  v->nOnceFlag = pFrame->nOnceFlag;
63481  v->aOp = pFrame->aOp;
63482  v->nOp = pFrame->nOp;
63483  v->aMem = pFrame->aMem;
63484  v->nMem = pFrame->nMem;
63485  v->apCsr = pFrame->apCsr;
63486  v->nCursor = pFrame->nCursor;
63487  v->db->lastRowid = pFrame->lastRowid;
63488  v->nChange = pFrame->nChange;
63489  return pFrame->pc;
63490}
63491
63492/*
63493** Close all cursors.
63494**
63495** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
63496** cell array. This is necessary as the memory cell array may contain
63497** pointers to VdbeFrame objects, which may in turn contain pointers to
63498** open cursors.
63499*/
63500static void closeAllCursors(Vdbe *p){
63501  if( p->pFrame ){
63502    VdbeFrame *pFrame;
63503    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
63504    sqlite3VdbeFrameRestore(pFrame);
63505  }
63506  p->pFrame = 0;
63507  p->nFrame = 0;
63508
63509  if( p->apCsr ){
63510    int i;
63511    for(i=0; i<p->nCursor; i++){
63512      VdbeCursor *pC = p->apCsr[i];
63513      if( pC ){
63514        sqlite3VdbeFreeCursor(p, pC);
63515        p->apCsr[i] = 0;
63516      }
63517    }
63518  }
63519  if( p->aMem ){
63520    releaseMemArray(&p->aMem[1], p->nMem);
63521  }
63522  while( p->pDelFrame ){
63523    VdbeFrame *pDel = p->pDelFrame;
63524    p->pDelFrame = pDel->pParent;
63525    sqlite3VdbeFrameDelete(pDel);
63526  }
63527
63528  /* Delete any auxdata allocations made by the VM */
63529  sqlite3VdbeDeleteAuxData(p, -1, 0);
63530  assert( p->pAuxData==0 );
63531}
63532
63533/*
63534** Clean up the VM after execution.
63535**
63536** This routine will automatically close any cursors, lists, and/or
63537** sorters that were left open.  It also deletes the values of
63538** variables in the aVar[] array.
63539*/
63540static void Cleanup(Vdbe *p){
63541  sqlite3 *db = p->db;
63542
63543#ifdef SQLITE_DEBUG
63544  /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
63545  ** Vdbe.aMem[] arrays have already been cleaned up.  */
63546  int i;
63547  if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
63548  if( p->aMem ){
63549    for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
63550  }
63551#endif
63552
63553  sqlite3DbFree(db, p->zErrMsg);
63554  p->zErrMsg = 0;
63555  p->pResultSet = 0;
63556}
63557
63558/*
63559** Set the number of result columns that will be returned by this SQL
63560** statement. This is now set at compile time, rather than during
63561** execution of the vdbe program so that sqlite3_column_count() can
63562** be called on an SQL statement before sqlite3_step().
63563*/
63564SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
63565  Mem *pColName;
63566  int n;
63567  sqlite3 *db = p->db;
63568
63569  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
63570  sqlite3DbFree(db, p->aColName);
63571  n = nResColumn*COLNAME_N;
63572  p->nResColumn = (u16)nResColumn;
63573  p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
63574  if( p->aColName==0 ) return;
63575  while( n-- > 0 ){
63576    pColName->flags = MEM_Null;
63577    pColName->db = p->db;
63578    pColName++;
63579  }
63580}
63581
63582/*
63583** Set the name of the idx'th column to be returned by the SQL statement.
63584** zName must be a pointer to a nul terminated string.
63585**
63586** This call must be made after a call to sqlite3VdbeSetNumCols().
63587**
63588** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
63589** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
63590** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
63591*/
63592SQLITE_PRIVATE int sqlite3VdbeSetColName(
63593  Vdbe *p,                         /* Vdbe being configured */
63594  int idx,                         /* Index of column zName applies to */
63595  int var,                         /* One of the COLNAME_* constants */
63596  const char *zName,               /* Pointer to buffer containing name */
63597  void (*xDel)(void*)              /* Memory management strategy for zName */
63598){
63599  int rc;
63600  Mem *pColName;
63601  assert( idx<p->nResColumn );
63602  assert( var<COLNAME_N );
63603  if( p->db->mallocFailed ){
63604    assert( !zName || xDel!=SQLITE_DYNAMIC );
63605    return SQLITE_NOMEM;
63606  }
63607  assert( p->aColName!=0 );
63608  pColName = &(p->aColName[idx+var*p->nResColumn]);
63609  rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
63610  assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
63611  return rc;
63612}
63613
63614/*
63615** A read or write transaction may or may not be active on database handle
63616** db. If a transaction is active, commit it. If there is a
63617** write-transaction spanning more than one database file, this routine
63618** takes care of the master journal trickery.
63619*/
63620static int vdbeCommit(sqlite3 *db, Vdbe *p){
63621  int i;
63622  int nTrans = 0;  /* Number of databases with an active write-transaction */
63623  int rc = SQLITE_OK;
63624  int needXcommit = 0;
63625
63626#ifdef SQLITE_OMIT_VIRTUALTABLE
63627  /* With this option, sqlite3VtabSync() is defined to be simply
63628  ** SQLITE_OK so p is not used.
63629  */
63630  UNUSED_PARAMETER(p);
63631#endif
63632
63633  /* Before doing anything else, call the xSync() callback for any
63634  ** virtual module tables written in this transaction. This has to
63635  ** be done before determining whether a master journal file is
63636  ** required, as an xSync() callback may add an attached database
63637  ** to the transaction.
63638  */
63639  rc = sqlite3VtabSync(db, p);
63640
63641  /* This loop determines (a) if the commit hook should be invoked and
63642  ** (b) how many database files have open write transactions, not
63643  ** including the temp database. (b) is important because if more than
63644  ** one database file has an open write transaction, a master journal
63645  ** file is required for an atomic commit.
63646  */
63647  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
63648    Btree *pBt = db->aDb[i].pBt;
63649    if( sqlite3BtreeIsInTrans(pBt) ){
63650      needXcommit = 1;
63651      if( i!=1 ) nTrans++;
63652      sqlite3BtreeEnter(pBt);
63653      rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
63654      sqlite3BtreeLeave(pBt);
63655    }
63656  }
63657  if( rc!=SQLITE_OK ){
63658    return rc;
63659  }
63660
63661  /* If there are any write-transactions at all, invoke the commit hook */
63662  if( needXcommit && db->xCommitCallback ){
63663    rc = db->xCommitCallback(db->pCommitArg);
63664    if( rc ){
63665      return SQLITE_CONSTRAINT_COMMITHOOK;
63666    }
63667  }
63668
63669  /* The simple case - no more than one database file (not counting the
63670  ** TEMP database) has a transaction active.   There is no need for the
63671  ** master-journal.
63672  **
63673  ** If the return value of sqlite3BtreeGetFilename() is a zero length
63674  ** string, it means the main database is :memory: or a temp file.  In
63675  ** that case we do not support atomic multi-file commits, so use the
63676  ** simple case then too.
63677  */
63678  if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
63679   || nTrans<=1
63680  ){
63681    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
63682      Btree *pBt = db->aDb[i].pBt;
63683      if( pBt ){
63684        rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
63685      }
63686    }
63687
63688    /* Do the commit only if all databases successfully complete phase 1.
63689    ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
63690    ** IO error while deleting or truncating a journal file. It is unlikely,
63691    ** but could happen. In this case abandon processing and return the error.
63692    */
63693    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
63694      Btree *pBt = db->aDb[i].pBt;
63695      if( pBt ){
63696        rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
63697      }
63698    }
63699    if( rc==SQLITE_OK ){
63700      sqlite3VtabCommit(db);
63701    }
63702  }
63703
63704  /* The complex case - There is a multi-file write-transaction active.
63705  ** This requires a master journal file to ensure the transaction is
63706  ** committed atomicly.
63707  */
63708#ifndef SQLITE_OMIT_DISKIO
63709  else{
63710    sqlite3_vfs *pVfs = db->pVfs;
63711    int needSync = 0;
63712    char *zMaster = 0;   /* File-name for the master journal */
63713    char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
63714    sqlite3_file *pMaster = 0;
63715    i64 offset = 0;
63716    int res;
63717    int retryCount = 0;
63718    int nMainFile;
63719
63720    /* Select a master journal file name */
63721    nMainFile = sqlite3Strlen30(zMainFile);
63722    zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
63723    if( zMaster==0 ) return SQLITE_NOMEM;
63724    do {
63725      u32 iRandom;
63726      if( retryCount ){
63727        if( retryCount>100 ){
63728          sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
63729          sqlite3OsDelete(pVfs, zMaster, 0);
63730          break;
63731        }else if( retryCount==1 ){
63732          sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
63733        }
63734      }
63735      retryCount++;
63736      sqlite3_randomness(sizeof(iRandom), &iRandom);
63737      sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
63738                               (iRandom>>8)&0xffffff, iRandom&0xff);
63739      /* The antipenultimate character of the master journal name must
63740      ** be "9" to avoid name collisions when using 8+3 filenames. */
63741      assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
63742      sqlite3FileSuffix3(zMainFile, zMaster);
63743      rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
63744    }while( rc==SQLITE_OK && res );
63745    if( rc==SQLITE_OK ){
63746      /* Open the master journal. */
63747      rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
63748          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
63749          SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
63750      );
63751    }
63752    if( rc!=SQLITE_OK ){
63753      sqlite3DbFree(db, zMaster);
63754      return rc;
63755    }
63756
63757    /* Write the name of each database file in the transaction into the new
63758    ** master journal file. If an error occurs at this point close
63759    ** and delete the master journal file. All the individual journal files
63760    ** still have 'null' as the master journal pointer, so they will roll
63761    ** back independently if a failure occurs.
63762    */
63763    for(i=0; i<db->nDb; i++){
63764      Btree *pBt = db->aDb[i].pBt;
63765      if( sqlite3BtreeIsInTrans(pBt) ){
63766        char const *zFile = sqlite3BtreeGetJournalname(pBt);
63767        if( zFile==0 ){
63768          continue;  /* Ignore TEMP and :memory: databases */
63769        }
63770        assert( zFile[0]!=0 );
63771        if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
63772          needSync = 1;
63773        }
63774        rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
63775        offset += sqlite3Strlen30(zFile)+1;
63776        if( rc!=SQLITE_OK ){
63777          sqlite3OsCloseFree(pMaster);
63778          sqlite3OsDelete(pVfs, zMaster, 0);
63779          sqlite3DbFree(db, zMaster);
63780          return rc;
63781        }
63782      }
63783    }
63784
63785    /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
63786    ** flag is set this is not required.
63787    */
63788    if( needSync
63789     && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
63790     && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
63791    ){
63792      sqlite3OsCloseFree(pMaster);
63793      sqlite3OsDelete(pVfs, zMaster, 0);
63794      sqlite3DbFree(db, zMaster);
63795      return rc;
63796    }
63797
63798    /* Sync all the db files involved in the transaction. The same call
63799    ** sets the master journal pointer in each individual journal. If
63800    ** an error occurs here, do not delete the master journal file.
63801    **
63802    ** If the error occurs during the first call to
63803    ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
63804    ** master journal file will be orphaned. But we cannot delete it,
63805    ** in case the master journal file name was written into the journal
63806    ** file before the failure occurred.
63807    */
63808    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
63809      Btree *pBt = db->aDb[i].pBt;
63810      if( pBt ){
63811        rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
63812      }
63813    }
63814    sqlite3OsCloseFree(pMaster);
63815    assert( rc!=SQLITE_BUSY );
63816    if( rc!=SQLITE_OK ){
63817      sqlite3DbFree(db, zMaster);
63818      return rc;
63819    }
63820
63821    /* Delete the master journal file. This commits the transaction. After
63822    ** doing this the directory is synced again before any individual
63823    ** transaction files are deleted.
63824    */
63825    rc = sqlite3OsDelete(pVfs, zMaster, 1);
63826    sqlite3DbFree(db, zMaster);
63827    zMaster = 0;
63828    if( rc ){
63829      return rc;
63830    }
63831
63832    /* All files and directories have already been synced, so the following
63833    ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
63834    ** deleting or truncating journals. If something goes wrong while
63835    ** this is happening we don't really care. The integrity of the
63836    ** transaction is already guaranteed, but some stray 'cold' journals
63837    ** may be lying around. Returning an error code won't help matters.
63838    */
63839    disable_simulated_io_errors();
63840    sqlite3BeginBenignMalloc();
63841    for(i=0; i<db->nDb; i++){
63842      Btree *pBt = db->aDb[i].pBt;
63843      if( pBt ){
63844        sqlite3BtreeCommitPhaseTwo(pBt, 1);
63845      }
63846    }
63847    sqlite3EndBenignMalloc();
63848    enable_simulated_io_errors();
63849
63850    sqlite3VtabCommit(db);
63851  }
63852#endif
63853
63854  return rc;
63855}
63856
63857/*
63858** This routine checks that the sqlite3.nVdbeActive count variable
63859** matches the number of vdbe's in the list sqlite3.pVdbe that are
63860** currently active. An assertion fails if the two counts do not match.
63861** This is an internal self-check only - it is not an essential processing
63862** step.
63863**
63864** This is a no-op if NDEBUG is defined.
63865*/
63866#ifndef NDEBUG
63867static void checkActiveVdbeCnt(sqlite3 *db){
63868  Vdbe *p;
63869  int cnt = 0;
63870  int nWrite = 0;
63871  int nRead = 0;
63872  p = db->pVdbe;
63873  while( p ){
63874    if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
63875      cnt++;
63876      if( p->readOnly==0 ) nWrite++;
63877      if( p->bIsReader ) nRead++;
63878    }
63879    p = p->pNext;
63880  }
63881  assert( cnt==db->nVdbeActive );
63882  assert( nWrite==db->nVdbeWrite );
63883  assert( nRead==db->nVdbeRead );
63884}
63885#else
63886#define checkActiveVdbeCnt(x)
63887#endif
63888
63889/*
63890** If the Vdbe passed as the first argument opened a statement-transaction,
63891** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
63892** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
63893** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
63894** statement transaction is committed.
63895**
63896** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
63897** Otherwise SQLITE_OK.
63898*/
63899SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
63900  sqlite3 *const db = p->db;
63901  int rc = SQLITE_OK;
63902
63903  /* If p->iStatement is greater than zero, then this Vdbe opened a
63904  ** statement transaction that should be closed here. The only exception
63905  ** is that an IO error may have occurred, causing an emergency rollback.
63906  ** In this case (db->nStatement==0), and there is nothing to do.
63907  */
63908  if( db->nStatement && p->iStatement ){
63909    int i;
63910    const int iSavepoint = p->iStatement-1;
63911
63912    assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
63913    assert( db->nStatement>0 );
63914    assert( p->iStatement==(db->nStatement+db->nSavepoint) );
63915
63916    for(i=0; i<db->nDb; i++){
63917      int rc2 = SQLITE_OK;
63918      Btree *pBt = db->aDb[i].pBt;
63919      if( pBt ){
63920        if( eOp==SAVEPOINT_ROLLBACK ){
63921          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
63922        }
63923        if( rc2==SQLITE_OK ){
63924          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
63925        }
63926        if( rc==SQLITE_OK ){
63927          rc = rc2;
63928        }
63929      }
63930    }
63931    db->nStatement--;
63932    p->iStatement = 0;
63933
63934    if( rc==SQLITE_OK ){
63935      if( eOp==SAVEPOINT_ROLLBACK ){
63936        rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
63937      }
63938      if( rc==SQLITE_OK ){
63939        rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
63940      }
63941    }
63942
63943    /* If the statement transaction is being rolled back, also restore the
63944    ** database handles deferred constraint counter to the value it had when
63945    ** the statement transaction was opened.  */
63946    if( eOp==SAVEPOINT_ROLLBACK ){
63947      db->nDeferredCons = p->nStmtDefCons;
63948      db->nDeferredImmCons = p->nStmtDefImmCons;
63949    }
63950  }
63951  return rc;
63952}
63953
63954/*
63955** This function is called when a transaction opened by the database
63956** handle associated with the VM passed as an argument is about to be
63957** committed. If there are outstanding deferred foreign key constraint
63958** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
63959**
63960** If there are outstanding FK violations and this function returns
63961** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
63962** and write an error message to it. Then return SQLITE_ERROR.
63963*/
63964#ifndef SQLITE_OMIT_FOREIGN_KEY
63965SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
63966  sqlite3 *db = p->db;
63967  if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
63968   || (!deferred && p->nFkConstraint>0)
63969  ){
63970    p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
63971    p->errorAction = OE_Abort;
63972    sqlite3SetString(&p->zErrMsg, db, "FOREIGN KEY constraint failed");
63973    return SQLITE_ERROR;
63974  }
63975  return SQLITE_OK;
63976}
63977#endif
63978
63979/*
63980** This routine is called the when a VDBE tries to halt.  If the VDBE
63981** has made changes and is in autocommit mode, then commit those
63982** changes.  If a rollback is needed, then do the rollback.
63983**
63984** This routine is the only way to move the state of a VM from
63985** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
63986** call this on a VM that is in the SQLITE_MAGIC_HALT state.
63987**
63988** Return an error code.  If the commit could not complete because of
63989** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
63990** means the close did not happen and needs to be repeated.
63991*/
63992SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
63993  int rc;                         /* Used to store transient return codes */
63994  sqlite3 *db = p->db;
63995
63996  /* This function contains the logic that determines if a statement or
63997  ** transaction will be committed or rolled back as a result of the
63998  ** execution of this virtual machine.
63999  **
64000  ** If any of the following errors occur:
64001  **
64002  **     SQLITE_NOMEM
64003  **     SQLITE_IOERR
64004  **     SQLITE_FULL
64005  **     SQLITE_INTERRUPT
64006  **
64007  ** Then the internal cache might have been left in an inconsistent
64008  ** state.  We need to rollback the statement transaction, if there is
64009  ** one, or the complete transaction if there is no statement transaction.
64010  */
64011
64012  if( p->db->mallocFailed ){
64013    p->rc = SQLITE_NOMEM;
64014  }
64015  if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
64016  closeAllCursors(p);
64017  if( p->magic!=VDBE_MAGIC_RUN ){
64018    return SQLITE_OK;
64019  }
64020  checkActiveVdbeCnt(db);
64021
64022  /* No commit or rollback needed if the program never started or if the
64023  ** SQL statement does not read or write a database file.  */
64024  if( p->pc>=0 && p->bIsReader ){
64025    int mrc;   /* Primary error code from p->rc */
64026    int eStatementOp = 0;
64027    int isSpecialError;            /* Set to true if a 'special' error */
64028
64029    /* Lock all btrees used by the statement */
64030    sqlite3VdbeEnter(p);
64031
64032    /* Check for one of the special errors */
64033    mrc = p->rc & 0xff;
64034    assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
64035    isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
64036                     || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
64037    if( isSpecialError ){
64038      /* If the query was read-only and the error code is SQLITE_INTERRUPT,
64039      ** no rollback is necessary. Otherwise, at least a savepoint
64040      ** transaction must be rolled back to restore the database to a
64041      ** consistent state.
64042      **
64043      ** Even if the statement is read-only, it is important to perform
64044      ** a statement or transaction rollback operation. If the error
64045      ** occurred while writing to the journal, sub-journal or database
64046      ** file as part of an effort to free up cache space (see function
64047      ** pagerStress() in pager.c), the rollback is required to restore
64048      ** the pager to a consistent state.
64049      */
64050      if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
64051        if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
64052          eStatementOp = SAVEPOINT_ROLLBACK;
64053        }else{
64054          /* We are forced to roll back the active transaction. Before doing
64055          ** so, abort any other statements this handle currently has active.
64056          */
64057          sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
64058          sqlite3CloseSavepoints(db);
64059          db->autoCommit = 1;
64060        }
64061      }
64062    }
64063
64064    /* Check for immediate foreign key violations. */
64065    if( p->rc==SQLITE_OK ){
64066      sqlite3VdbeCheckFk(p, 0);
64067    }
64068
64069    /* If the auto-commit flag is set and this is the only active writer
64070    ** VM, then we do either a commit or rollback of the current transaction.
64071    **
64072    ** Note: This block also runs if one of the special errors handled
64073    ** above has occurred.
64074    */
64075    if( !sqlite3VtabInSync(db)
64076     && db->autoCommit
64077     && db->nVdbeWrite==(p->readOnly==0)
64078    ){
64079      if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
64080        rc = sqlite3VdbeCheckFk(p, 1);
64081        if( rc!=SQLITE_OK ){
64082          if( NEVER(p->readOnly) ){
64083            sqlite3VdbeLeave(p);
64084            return SQLITE_ERROR;
64085          }
64086          rc = SQLITE_CONSTRAINT_FOREIGNKEY;
64087        }else{
64088          /* The auto-commit flag is true, the vdbe program was successful
64089          ** or hit an 'OR FAIL' constraint and there are no deferred foreign
64090          ** key constraints to hold up the transaction. This means a commit
64091          ** is required. */
64092          rc = vdbeCommit(db, p);
64093        }
64094        if( rc==SQLITE_BUSY && p->readOnly ){
64095          sqlite3VdbeLeave(p);
64096          return SQLITE_BUSY;
64097        }else if( rc!=SQLITE_OK ){
64098          p->rc = rc;
64099          sqlite3RollbackAll(db, SQLITE_OK);
64100        }else{
64101          db->nDeferredCons = 0;
64102          db->nDeferredImmCons = 0;
64103          db->flags &= ~SQLITE_DeferFKs;
64104          sqlite3CommitInternalChanges(db);
64105        }
64106      }else{
64107        sqlite3RollbackAll(db, SQLITE_OK);
64108      }
64109      db->nStatement = 0;
64110    }else if( eStatementOp==0 ){
64111      if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
64112        eStatementOp = SAVEPOINT_RELEASE;
64113      }else if( p->errorAction==OE_Abort ){
64114        eStatementOp = SAVEPOINT_ROLLBACK;
64115      }else{
64116        sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
64117        sqlite3CloseSavepoints(db);
64118        db->autoCommit = 1;
64119      }
64120    }
64121
64122    /* If eStatementOp is non-zero, then a statement transaction needs to
64123    ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
64124    ** do so. If this operation returns an error, and the current statement
64125    ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
64126    ** current statement error code.
64127    */
64128    if( eStatementOp ){
64129      rc = sqlite3VdbeCloseStatement(p, eStatementOp);
64130      if( rc ){
64131        if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
64132          p->rc = rc;
64133          sqlite3DbFree(db, p->zErrMsg);
64134          p->zErrMsg = 0;
64135        }
64136        sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
64137        sqlite3CloseSavepoints(db);
64138        db->autoCommit = 1;
64139      }
64140    }
64141
64142    /* If this was an INSERT, UPDATE or DELETE and no statement transaction
64143    ** has been rolled back, update the database connection change-counter.
64144    */
64145    if( p->changeCntOn ){
64146      if( eStatementOp!=SAVEPOINT_ROLLBACK ){
64147        sqlite3VdbeSetChanges(db, p->nChange);
64148      }else{
64149        sqlite3VdbeSetChanges(db, 0);
64150      }
64151      p->nChange = 0;
64152    }
64153
64154    /* Release the locks */
64155    sqlite3VdbeLeave(p);
64156  }
64157
64158  /* We have successfully halted and closed the VM.  Record this fact. */
64159  if( p->pc>=0 ){
64160    db->nVdbeActive--;
64161    if( !p->readOnly ) db->nVdbeWrite--;
64162    if( p->bIsReader ) db->nVdbeRead--;
64163    assert( db->nVdbeActive>=db->nVdbeRead );
64164    assert( db->nVdbeRead>=db->nVdbeWrite );
64165    assert( db->nVdbeWrite>=0 );
64166  }
64167  p->magic = VDBE_MAGIC_HALT;
64168  checkActiveVdbeCnt(db);
64169  if( p->db->mallocFailed ){
64170    p->rc = SQLITE_NOMEM;
64171  }
64172
64173  /* If the auto-commit flag is set to true, then any locks that were held
64174  ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
64175  ** to invoke any required unlock-notify callbacks.
64176  */
64177  if( db->autoCommit ){
64178    sqlite3ConnectionUnlocked(db);
64179  }
64180
64181  assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
64182  return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
64183}
64184
64185
64186/*
64187** Each VDBE holds the result of the most recent sqlite3_step() call
64188** in p->rc.  This routine sets that result back to SQLITE_OK.
64189*/
64190SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
64191  p->rc = SQLITE_OK;
64192}
64193
64194/*
64195** Copy the error code and error message belonging to the VDBE passed
64196** as the first argument to its database handle (so that they will be
64197** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
64198**
64199** This function does not clear the VDBE error code or message, just
64200** copies them to the database handle.
64201*/
64202SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
64203  sqlite3 *db = p->db;
64204  int rc = p->rc;
64205  if( p->zErrMsg ){
64206    u8 mallocFailed = db->mallocFailed;
64207    sqlite3BeginBenignMalloc();
64208    if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
64209    sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
64210    sqlite3EndBenignMalloc();
64211    db->mallocFailed = mallocFailed;
64212    db->errCode = rc;
64213  }else{
64214    sqlite3Error(db, rc, 0);
64215  }
64216  return rc;
64217}
64218
64219#ifdef SQLITE_ENABLE_SQLLOG
64220/*
64221** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
64222** invoke it.
64223*/
64224static void vdbeInvokeSqllog(Vdbe *v){
64225  if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
64226    char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
64227    assert( v->db->init.busy==0 );
64228    if( zExpanded ){
64229      sqlite3GlobalConfig.xSqllog(
64230          sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
64231      );
64232      sqlite3DbFree(v->db, zExpanded);
64233    }
64234  }
64235}
64236#else
64237# define vdbeInvokeSqllog(x)
64238#endif
64239
64240/*
64241** Clean up a VDBE after execution but do not delete the VDBE just yet.
64242** Write any error messages into *pzErrMsg.  Return the result code.
64243**
64244** After this routine is run, the VDBE should be ready to be executed
64245** again.
64246**
64247** To look at it another way, this routine resets the state of the
64248** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
64249** VDBE_MAGIC_INIT.
64250*/
64251SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
64252  sqlite3 *db;
64253  db = p->db;
64254
64255  /* If the VM did not run to completion or if it encountered an
64256  ** error, then it might not have been halted properly.  So halt
64257  ** it now.
64258  */
64259  sqlite3VdbeHalt(p);
64260
64261  /* If the VDBE has be run even partially, then transfer the error code
64262  ** and error message from the VDBE into the main database structure.  But
64263  ** if the VDBE has just been set to run but has not actually executed any
64264  ** instructions yet, leave the main database error information unchanged.
64265  */
64266  if( p->pc>=0 ){
64267    vdbeInvokeSqllog(p);
64268    sqlite3VdbeTransferError(p);
64269    sqlite3DbFree(db, p->zErrMsg);
64270    p->zErrMsg = 0;
64271    if( p->runOnlyOnce ) p->expired = 1;
64272  }else if( p->rc && p->expired ){
64273    /* The expired flag was set on the VDBE before the first call
64274    ** to sqlite3_step(). For consistency (since sqlite3_step() was
64275    ** called), set the database error in this case as well.
64276    */
64277    sqlite3Error(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
64278    sqlite3DbFree(db, p->zErrMsg);
64279    p->zErrMsg = 0;
64280  }
64281
64282  /* Reclaim all memory used by the VDBE
64283  */
64284  Cleanup(p);
64285
64286  /* Save profiling information from this VDBE run.
64287  */
64288#ifdef VDBE_PROFILE
64289  {
64290    FILE *out = fopen("vdbe_profile.out", "a");
64291    if( out ){
64292      int i;
64293      fprintf(out, "---- ");
64294      for(i=0; i<p->nOp; i++){
64295        fprintf(out, "%02x", p->aOp[i].opcode);
64296      }
64297      fprintf(out, "\n");
64298      if( p->zSql ){
64299        char c, pc = 0;
64300        fprintf(out, "-- ");
64301        for(i=0; (c = p->zSql[i])!=0; i++){
64302          if( pc=='\n' ) fprintf(out, "-- ");
64303          putc(c, out);
64304          pc = c;
64305        }
64306        if( pc!='\n' ) fprintf(out, "\n");
64307      }
64308      for(i=0; i<p->nOp; i++){
64309        char zHdr[100];
64310        sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
64311           p->aOp[i].cnt,
64312           p->aOp[i].cycles,
64313           p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
64314        );
64315        fprintf(out, "%s", zHdr);
64316        sqlite3VdbePrintOp(out, i, &p->aOp[i]);
64317      }
64318      fclose(out);
64319    }
64320  }
64321#endif
64322  p->iCurrentTime = 0;
64323  p->magic = VDBE_MAGIC_INIT;
64324  return p->rc & db->errMask;
64325}
64326
64327/*
64328** Clean up and delete a VDBE after execution.  Return an integer which is
64329** the result code.  Write any error message text into *pzErrMsg.
64330*/
64331SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
64332  int rc = SQLITE_OK;
64333  if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
64334    rc = sqlite3VdbeReset(p);
64335    assert( (rc & p->db->errMask)==rc );
64336  }
64337  sqlite3VdbeDelete(p);
64338  return rc;
64339}
64340
64341/*
64342** If parameter iOp is less than zero, then invoke the destructor for
64343** all auxiliary data pointers currently cached by the VM passed as
64344** the first argument.
64345**
64346** Or, if iOp is greater than or equal to zero, then the destructor is
64347** only invoked for those auxiliary data pointers created by the user
64348** function invoked by the OP_Function opcode at instruction iOp of
64349** VM pVdbe, and only then if:
64350**
64351**    * the associated function parameter is the 32nd or later (counting
64352**      from left to right), or
64353**
64354**    * the corresponding bit in argument mask is clear (where the first
64355**      function parameter corrsponds to bit 0 etc.).
64356*/
64357SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe *pVdbe, int iOp, int mask){
64358  AuxData **pp = &pVdbe->pAuxData;
64359  while( *pp ){
64360    AuxData *pAux = *pp;
64361    if( (iOp<0)
64362     || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
64363    ){
64364      testcase( pAux->iArg==31 );
64365      if( pAux->xDelete ){
64366        pAux->xDelete(pAux->pAux);
64367      }
64368      *pp = pAux->pNext;
64369      sqlite3DbFree(pVdbe->db, pAux);
64370    }else{
64371      pp= &pAux->pNext;
64372    }
64373  }
64374}
64375
64376/*
64377** Free all memory associated with the Vdbe passed as the second argument,
64378** except for object itself, which is preserved.
64379**
64380** The difference between this function and sqlite3VdbeDelete() is that
64381** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
64382** the database connection and frees the object itself.
64383*/
64384SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
64385  SubProgram *pSub, *pNext;
64386  int i;
64387  assert( p->db==0 || p->db==db );
64388  releaseMemArray(p->aVar, p->nVar);
64389  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
64390  for(pSub=p->pProgram; pSub; pSub=pNext){
64391    pNext = pSub->pNext;
64392    vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
64393    sqlite3DbFree(db, pSub);
64394  }
64395  for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
64396  vdbeFreeOpArray(db, p->aOp, p->nOp);
64397  sqlite3DbFree(db, p->aColName);
64398  sqlite3DbFree(db, p->zSql);
64399  sqlite3DbFree(db, p->pFree);
64400#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
64401  sqlite3DbFree(db, p->zExplain);
64402  sqlite3DbFree(db, p->pExplain);
64403#endif
64404}
64405
64406/*
64407** Delete an entire VDBE.
64408*/
64409SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
64410  sqlite3 *db;
64411
64412  if( NEVER(p==0) ) return;
64413  db = p->db;
64414  assert( sqlite3_mutex_held(db->mutex) );
64415  sqlite3VdbeClearObject(db, p);
64416  if( p->pPrev ){
64417    p->pPrev->pNext = p->pNext;
64418  }else{
64419    assert( db->pVdbe==p );
64420    db->pVdbe = p->pNext;
64421  }
64422  if( p->pNext ){
64423    p->pNext->pPrev = p->pPrev;
64424  }
64425  p->magic = VDBE_MAGIC_DEAD;
64426  p->db = 0;
64427  sqlite3DbFree(db, p);
64428}
64429
64430/*
64431** Make sure the cursor p is ready to read or write the row to which it
64432** was last positioned.  Return an error code if an OOM fault or I/O error
64433** prevents us from positioning the cursor to its correct position.
64434**
64435** If a MoveTo operation is pending on the given cursor, then do that
64436** MoveTo now.  If no move is pending, check to see if the row has been
64437** deleted out from under the cursor and if it has, mark the row as
64438** a NULL row.
64439**
64440** If the cursor is already pointing to the correct row and that row has
64441** not been deleted out from under the cursor, then this routine is a no-op.
64442*/
64443SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
64444  if( p->deferredMoveto ){
64445    int res, rc;
64446#ifdef SQLITE_TEST
64447    extern int sqlite3_search_count;
64448#endif
64449    assert( p->isTable );
64450    rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
64451    if( rc ) return rc;
64452    p->lastRowid = p->movetoTarget;
64453    if( res!=0 ) return SQLITE_CORRUPT_BKPT;
64454    p->rowidIsValid = 1;
64455#ifdef SQLITE_TEST
64456    sqlite3_search_count++;
64457#endif
64458    p->deferredMoveto = 0;
64459    p->cacheStatus = CACHE_STALE;
64460  }else if( p->pCursor ){
64461    int hasMoved;
64462    int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
64463    if( rc ) return rc;
64464    if( hasMoved ){
64465      p->cacheStatus = CACHE_STALE;
64466      if( hasMoved==2 ) p->nullRow = 1;
64467    }
64468  }
64469  return SQLITE_OK;
64470}
64471
64472/*
64473** The following functions:
64474**
64475** sqlite3VdbeSerialType()
64476** sqlite3VdbeSerialTypeLen()
64477** sqlite3VdbeSerialLen()
64478** sqlite3VdbeSerialPut()
64479** sqlite3VdbeSerialGet()
64480**
64481** encapsulate the code that serializes values for storage in SQLite
64482** data and index records. Each serialized value consists of a
64483** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
64484** integer, stored as a varint.
64485**
64486** In an SQLite index record, the serial type is stored directly before
64487** the blob of data that it corresponds to. In a table record, all serial
64488** types are stored at the start of the record, and the blobs of data at
64489** the end. Hence these functions allow the caller to handle the
64490** serial-type and data blob separately.
64491**
64492** The following table describes the various storage classes for data:
64493**
64494**   serial type        bytes of data      type
64495**   --------------     ---------------    ---------------
64496**      0                     0            NULL
64497**      1                     1            signed integer
64498**      2                     2            signed integer
64499**      3                     3            signed integer
64500**      4                     4            signed integer
64501**      5                     6            signed integer
64502**      6                     8            signed integer
64503**      7                     8            IEEE float
64504**      8                     0            Integer constant 0
64505**      9                     0            Integer constant 1
64506**     10,11                               reserved for expansion
64507**    N>=12 and even       (N-12)/2        BLOB
64508**    N>=13 and odd        (N-13)/2        text
64509**
64510** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
64511** of SQLite will not understand those serial types.
64512*/
64513
64514/*
64515** Return the serial-type for the value stored in pMem.
64516*/
64517SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
64518  int flags = pMem->flags;
64519  int n;
64520
64521  if( flags&MEM_Null ){
64522    return 0;
64523  }
64524  if( flags&MEM_Int ){
64525    /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
64526#   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
64527    i64 i = pMem->u.i;
64528    u64 u;
64529    if( i<0 ){
64530      if( i<(-MAX_6BYTE) ) return 6;
64531      /* Previous test prevents:  u = -(-9223372036854775808) */
64532      u = -i;
64533    }else{
64534      u = i;
64535    }
64536    if( u<=127 ){
64537      return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
64538    }
64539    if( u<=32767 ) return 2;
64540    if( u<=8388607 ) return 3;
64541    if( u<=2147483647 ) return 4;
64542    if( u<=MAX_6BYTE ) return 5;
64543    return 6;
64544  }
64545  if( flags&MEM_Real ){
64546    return 7;
64547  }
64548  assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
64549  n = pMem->n;
64550  if( flags & MEM_Zero ){
64551    n += pMem->u.nZero;
64552  }
64553  assert( n>=0 );
64554  return ((n*2) + 12 + ((flags&MEM_Str)!=0));
64555}
64556
64557/*
64558** Return the length of the data corresponding to the supplied serial-type.
64559*/
64560SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
64561  if( serial_type>=12 ){
64562    return (serial_type-12)/2;
64563  }else{
64564    static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
64565    return aSize[serial_type];
64566  }
64567}
64568
64569/*
64570** If we are on an architecture with mixed-endian floating
64571** points (ex: ARM7) then swap the lower 4 bytes with the
64572** upper 4 bytes.  Return the result.
64573**
64574** For most architectures, this is a no-op.
64575**
64576** (later):  It is reported to me that the mixed-endian problem
64577** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
64578** that early versions of GCC stored the two words of a 64-bit
64579** float in the wrong order.  And that error has been propagated
64580** ever since.  The blame is not necessarily with GCC, though.
64581** GCC might have just copying the problem from a prior compiler.
64582** I am also told that newer versions of GCC that follow a different
64583** ABI get the byte order right.
64584**
64585** Developers using SQLite on an ARM7 should compile and run their
64586** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
64587** enabled, some asserts below will ensure that the byte order of
64588** floating point values is correct.
64589**
64590** (2007-08-30)  Frank van Vugt has studied this problem closely
64591** and has send his findings to the SQLite developers.  Frank
64592** writes that some Linux kernels offer floating point hardware
64593** emulation that uses only 32-bit mantissas instead of a full
64594** 48-bits as required by the IEEE standard.  (This is the
64595** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
64596** byte swapping becomes very complicated.  To avoid problems,
64597** the necessary byte swapping is carried out using a 64-bit integer
64598** rather than a 64-bit float.  Frank assures us that the code here
64599** works for him.  We, the developers, have no way to independently
64600** verify this, but Frank seems to know what he is talking about
64601** so we trust him.
64602*/
64603#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
64604static u64 floatSwap(u64 in){
64605  union {
64606    u64 r;
64607    u32 i[2];
64608  } u;
64609  u32 t;
64610
64611  u.r = in;
64612  t = u.i[0];
64613  u.i[0] = u.i[1];
64614  u.i[1] = t;
64615  return u.r;
64616}
64617# define swapMixedEndianFloat(X)  X = floatSwap(X)
64618#else
64619# define swapMixedEndianFloat(X)
64620#endif
64621
64622/*
64623** Write the serialized data blob for the value stored in pMem into
64624** buf. It is assumed that the caller has allocated sufficient space.
64625** Return the number of bytes written.
64626**
64627** nBuf is the amount of space left in buf[].  The caller is responsible
64628** for allocating enough space to buf[] to hold the entire field, exclusive
64629** of the pMem->u.nZero bytes for a MEM_Zero value.
64630**
64631** Return the number of bytes actually written into buf[].  The number
64632** of bytes in the zero-filled tail is included in the return value only
64633** if those bytes were zeroed in buf[].
64634*/
64635SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
64636  u32 len;
64637
64638  /* Integer and Real */
64639  if( serial_type<=7 && serial_type>0 ){
64640    u64 v;
64641    u32 i;
64642    if( serial_type==7 ){
64643      assert( sizeof(v)==sizeof(pMem->r) );
64644      memcpy(&v, &pMem->r, sizeof(v));
64645      swapMixedEndianFloat(v);
64646    }else{
64647      v = pMem->u.i;
64648    }
64649    len = i = sqlite3VdbeSerialTypeLen(serial_type);
64650    while( i-- ){
64651      buf[i] = (u8)(v&0xFF);
64652      v >>= 8;
64653    }
64654    return len;
64655  }
64656
64657  /* String or blob */
64658  if( serial_type>=12 ){
64659    assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
64660             == (int)sqlite3VdbeSerialTypeLen(serial_type) );
64661    len = pMem->n;
64662    memcpy(buf, pMem->z, len);
64663    return len;
64664  }
64665
64666  /* NULL or constants 0 or 1 */
64667  return 0;
64668}
64669
64670/* Input "x" is a sequence of unsigned characters that represent a
64671** big-endian integer.  Return the equivalent native integer
64672*/
64673#define ONE_BYTE_INT(x)    ((i8)(x)[0])
64674#define TWO_BYTE_INT(x)    (256*(i8)((x)[0])|(x)[1])
64675#define THREE_BYTE_INT(x)  (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
64676#define FOUR_BYTE_UINT(x)  (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
64677
64678/*
64679** Deserialize the data blob pointed to by buf as serial type serial_type
64680** and store the result in pMem.  Return the number of bytes read.
64681*/
64682SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
64683  const unsigned char *buf,     /* Buffer to deserialize from */
64684  u32 serial_type,              /* Serial type to deserialize */
64685  Mem *pMem                     /* Memory cell to write value into */
64686){
64687  u64 x;
64688  u32 y;
64689  switch( serial_type ){
64690    case 10:   /* Reserved for future use */
64691    case 11:   /* Reserved for future use */
64692    case 0: {  /* NULL */
64693      pMem->flags = MEM_Null;
64694      break;
64695    }
64696    case 1: { /* 1-byte signed integer */
64697      pMem->u.i = ONE_BYTE_INT(buf);
64698      pMem->flags = MEM_Int;
64699      testcase( pMem->u.i<0 );
64700      return 1;
64701    }
64702    case 2: { /* 2-byte signed integer */
64703      pMem->u.i = TWO_BYTE_INT(buf);
64704      pMem->flags = MEM_Int;
64705      testcase( pMem->u.i<0 );
64706      return 2;
64707    }
64708    case 3: { /* 3-byte signed integer */
64709      pMem->u.i = THREE_BYTE_INT(buf);
64710      pMem->flags = MEM_Int;
64711      testcase( pMem->u.i<0 );
64712      return 3;
64713    }
64714    case 4: { /* 4-byte signed integer */
64715      y = FOUR_BYTE_UINT(buf);
64716      pMem->u.i = (i64)*(int*)&y;
64717      pMem->flags = MEM_Int;
64718      testcase( pMem->u.i<0 );
64719      return 4;
64720    }
64721    case 5: { /* 6-byte signed integer */
64722      pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
64723      pMem->flags = MEM_Int;
64724      testcase( pMem->u.i<0 );
64725      return 6;
64726    }
64727    case 6:   /* 8-byte signed integer */
64728    case 7: { /* IEEE floating point */
64729#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
64730      /* Verify that integers and floating point values use the same
64731      ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
64732      ** defined that 64-bit floating point values really are mixed
64733      ** endian.
64734      */
64735      static const u64 t1 = ((u64)0x3ff00000)<<32;
64736      static const double r1 = 1.0;
64737      u64 t2 = t1;
64738      swapMixedEndianFloat(t2);
64739      assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
64740#endif
64741      x = FOUR_BYTE_UINT(buf);
64742      y = FOUR_BYTE_UINT(buf+4);
64743      x = (x<<32) | y;
64744      if( serial_type==6 ){
64745        pMem->u.i = *(i64*)&x;
64746        pMem->flags = MEM_Int;
64747        testcase( pMem->u.i<0 );
64748      }else{
64749        assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
64750        swapMixedEndianFloat(x);
64751        memcpy(&pMem->r, &x, sizeof(x));
64752        pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
64753      }
64754      return 8;
64755    }
64756    case 8:    /* Integer 0 */
64757    case 9: {  /* Integer 1 */
64758      pMem->u.i = serial_type-8;
64759      pMem->flags = MEM_Int;
64760      return 0;
64761    }
64762    default: {
64763      static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
64764      u32 len = (serial_type-12)/2;
64765      pMem->z = (char *)buf;
64766      pMem->n = len;
64767      pMem->xDel = 0;
64768      pMem->flags = aFlag[serial_type&1];
64769      return len;
64770    }
64771  }
64772  return 0;
64773}
64774
64775/*
64776** This routine is used to allocate sufficient space for an UnpackedRecord
64777** structure large enough to be used with sqlite3VdbeRecordUnpack() if
64778** the first argument is a pointer to KeyInfo structure pKeyInfo.
64779**
64780** The space is either allocated using sqlite3DbMallocRaw() or from within
64781** the unaligned buffer passed via the second and third arguments (presumably
64782** stack space). If the former, then *ppFree is set to a pointer that should
64783** be eventually freed by the caller using sqlite3DbFree(). Or, if the
64784** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
64785** before returning.
64786**
64787** If an OOM error occurs, NULL is returned.
64788*/
64789SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
64790  KeyInfo *pKeyInfo,              /* Description of the record */
64791  char *pSpace,                   /* Unaligned space available */
64792  int szSpace,                    /* Size of pSpace[] in bytes */
64793  char **ppFree                   /* OUT: Caller should free this pointer */
64794){
64795  UnpackedRecord *p;              /* Unpacked record to return */
64796  int nOff;                       /* Increment pSpace by nOff to align it */
64797  int nByte;                      /* Number of bytes required for *p */
64798
64799  /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
64800  ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
64801  ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
64802  */
64803  nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
64804  nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
64805  if( nByte>szSpace+nOff ){
64806    p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
64807    *ppFree = (char *)p;
64808    if( !p ) return 0;
64809  }else{
64810    p = (UnpackedRecord*)&pSpace[nOff];
64811    *ppFree = 0;
64812  }
64813
64814  p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
64815  assert( pKeyInfo->aSortOrder!=0 );
64816  p->pKeyInfo = pKeyInfo;
64817  p->nField = pKeyInfo->nField + 1;
64818  return p;
64819}
64820
64821/*
64822** Given the nKey-byte encoding of a record in pKey[], populate the
64823** UnpackedRecord structure indicated by the fourth argument with the
64824** contents of the decoded record.
64825*/
64826SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
64827  KeyInfo *pKeyInfo,     /* Information about the record format */
64828  int nKey,              /* Size of the binary record */
64829  const void *pKey,      /* The binary record */
64830  UnpackedRecord *p      /* Populate this structure before returning. */
64831){
64832  const unsigned char *aKey = (const unsigned char *)pKey;
64833  int d;
64834  u32 idx;                        /* Offset in aKey[] to read from */
64835  u16 u;                          /* Unsigned loop counter */
64836  u32 szHdr;
64837  Mem *pMem = p->aMem;
64838
64839  p->default_rc = 0;
64840  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
64841  idx = getVarint32(aKey, szHdr);
64842  d = szHdr;
64843  u = 0;
64844  while( idx<szHdr && u<p->nField && d<=nKey ){
64845    u32 serial_type;
64846
64847    idx += getVarint32(&aKey[idx], serial_type);
64848    pMem->enc = pKeyInfo->enc;
64849    pMem->db = pKeyInfo->db;
64850    /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
64851    pMem->zMalloc = 0;
64852    d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
64853    pMem++;
64854    u++;
64855  }
64856  assert( u<=pKeyInfo->nField + 1 );
64857  p->nField = u;
64858}
64859
64860#if SQLITE_DEBUG
64861/*
64862** This function compares two index or table record keys in the same way
64863** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
64864** this function deserializes and compares values using the
64865** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
64866** in assert() statements to ensure that the optimized code in
64867** sqlite3VdbeRecordCompare() returns results with these two primitives.
64868*/
64869static int vdbeRecordCompareDebug(
64870  int nKey1, const void *pKey1, /* Left key */
64871  const UnpackedRecord *pPKey2  /* Right key */
64872){
64873  u32 d1;            /* Offset into aKey[] of next data element */
64874  u32 idx1;          /* Offset into aKey[] of next header element */
64875  u32 szHdr1;        /* Number of bytes in header */
64876  int i = 0;
64877  int rc = 0;
64878  const unsigned char *aKey1 = (const unsigned char *)pKey1;
64879  KeyInfo *pKeyInfo;
64880  Mem mem1;
64881
64882  pKeyInfo = pPKey2->pKeyInfo;
64883  mem1.enc = pKeyInfo->enc;
64884  mem1.db = pKeyInfo->db;
64885  /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
64886  VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
64887
64888  /* Compilers may complain that mem1.u.i is potentially uninitialized.
64889  ** We could initialize it, as shown here, to silence those complaints.
64890  ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
64891  ** the unnecessary initialization has a measurable negative performance
64892  ** impact, since this routine is a very high runner.  And so, we choose
64893  ** to ignore the compiler warnings and leave this variable uninitialized.
64894  */
64895  /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
64896
64897  idx1 = getVarint32(aKey1, szHdr1);
64898  d1 = szHdr1;
64899  assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
64900  assert( pKeyInfo->aSortOrder!=0 );
64901  assert( pKeyInfo->nField>0 );
64902  assert( idx1<=szHdr1 || CORRUPT_DB );
64903  do{
64904    u32 serial_type1;
64905
64906    /* Read the serial types for the next element in each key. */
64907    idx1 += getVarint32( aKey1+idx1, serial_type1 );
64908
64909    /* Verify that there is enough key space remaining to avoid
64910    ** a buffer overread.  The "d1+serial_type1+2" subexpression will
64911    ** always be greater than or equal to the amount of required key space.
64912    ** Use that approximation to avoid the more expensive call to
64913    ** sqlite3VdbeSerialTypeLen() in the common case.
64914    */
64915    if( d1+serial_type1+2>(u32)nKey1
64916     && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
64917    ){
64918      break;
64919    }
64920
64921    /* Extract the values to be compared.
64922    */
64923    d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
64924
64925    /* Do the comparison
64926    */
64927    rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
64928    if( rc!=0 ){
64929      assert( mem1.zMalloc==0 );  /* See comment below */
64930      if( pKeyInfo->aSortOrder[i] ){
64931        rc = -rc;  /* Invert the result for DESC sort order. */
64932      }
64933      return rc;
64934    }
64935    i++;
64936  }while( idx1<szHdr1 && i<pPKey2->nField );
64937
64938  /* No memory allocation is ever used on mem1.  Prove this using
64939  ** the following assert().  If the assert() fails, it indicates a
64940  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
64941  */
64942  assert( mem1.zMalloc==0 );
64943
64944  /* rc==0 here means that one of the keys ran out of fields and
64945  ** all the fields up to that point were equal. Return the the default_rc
64946  ** value.  */
64947  return pPKey2->default_rc;
64948}
64949#endif
64950
64951/*
64952** Both *pMem1 and *pMem2 contain string values. Compare the two values
64953** using the collation sequence pColl. As usual, return a negative , zero
64954** or positive value if *pMem1 is less than, equal to or greater than
64955** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
64956*/
64957static int vdbeCompareMemString(
64958  const Mem *pMem1,
64959  const Mem *pMem2,
64960  const CollSeq *pColl
64961){
64962  if( pMem1->enc==pColl->enc ){
64963    /* The strings are already in the correct encoding.  Call the
64964     ** comparison function directly */
64965    return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
64966  }else{
64967    int rc;
64968    const void *v1, *v2;
64969    int n1, n2;
64970    Mem c1;
64971    Mem c2;
64972    memset(&c1, 0, sizeof(c1));
64973    memset(&c2, 0, sizeof(c2));
64974    sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
64975    sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
64976    v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
64977    n1 = v1==0 ? 0 : c1.n;
64978    v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
64979    n2 = v2==0 ? 0 : c2.n;
64980    rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
64981    sqlite3VdbeMemRelease(&c1);
64982    sqlite3VdbeMemRelease(&c2);
64983    return rc;
64984  }
64985}
64986
64987/*
64988** Compare the values contained by the two memory cells, returning
64989** negative, zero or positive if pMem1 is less than, equal to, or greater
64990** than pMem2. Sorting order is NULL's first, followed by numbers (integers
64991** and reals) sorted numerically, followed by text ordered by the collating
64992** sequence pColl and finally blob's ordered by memcmp().
64993**
64994** Two NULL values are considered equal by this function.
64995*/
64996SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
64997  int rc;
64998  int f1, f2;
64999  int combined_flags;
65000
65001  f1 = pMem1->flags;
65002  f2 = pMem2->flags;
65003  combined_flags = f1|f2;
65004  assert( (combined_flags & MEM_RowSet)==0 );
65005
65006  /* If one value is NULL, it is less than the other. If both values
65007  ** are NULL, return 0.
65008  */
65009  if( combined_flags&MEM_Null ){
65010    return (f2&MEM_Null) - (f1&MEM_Null);
65011  }
65012
65013  /* If one value is a number and the other is not, the number is less.
65014  ** If both are numbers, compare as reals if one is a real, or as integers
65015  ** if both values are integers.
65016  */
65017  if( combined_flags&(MEM_Int|MEM_Real) ){
65018    double r1, r2;
65019    if( (f1 & f2 & MEM_Int)!=0 ){
65020      if( pMem1->u.i < pMem2->u.i ) return -1;
65021      if( pMem1->u.i > pMem2->u.i ) return 1;
65022      return 0;
65023    }
65024    if( (f1&MEM_Real)!=0 ){
65025      r1 = pMem1->r;
65026    }else if( (f1&MEM_Int)!=0 ){
65027      r1 = (double)pMem1->u.i;
65028    }else{
65029      return 1;
65030    }
65031    if( (f2&MEM_Real)!=0 ){
65032      r2 = pMem2->r;
65033    }else if( (f2&MEM_Int)!=0 ){
65034      r2 = (double)pMem2->u.i;
65035    }else{
65036      return -1;
65037    }
65038    if( r1<r2 ) return -1;
65039    if( r1>r2 ) return 1;
65040    return 0;
65041  }
65042
65043  /* If one value is a string and the other is a blob, the string is less.
65044  ** If both are strings, compare using the collating functions.
65045  */
65046  if( combined_flags&MEM_Str ){
65047    if( (f1 & MEM_Str)==0 ){
65048      return 1;
65049    }
65050    if( (f2 & MEM_Str)==0 ){
65051      return -1;
65052    }
65053
65054    assert( pMem1->enc==pMem2->enc );
65055    assert( pMem1->enc==SQLITE_UTF8 ||
65056            pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
65057
65058    /* The collation sequence must be defined at this point, even if
65059    ** the user deletes the collation sequence after the vdbe program is
65060    ** compiled (this was not always the case).
65061    */
65062    assert( !pColl || pColl->xCmp );
65063
65064    if( pColl ){
65065      return vdbeCompareMemString(pMem1, pMem2, pColl);
65066    }
65067    /* If a NULL pointer was passed as the collate function, fall through
65068    ** to the blob case and use memcmp().  */
65069  }
65070
65071  /* Both values must be blobs.  Compare using memcmp().  */
65072  rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
65073  if( rc==0 ){
65074    rc = pMem1->n - pMem2->n;
65075  }
65076  return rc;
65077}
65078
65079
65080/*
65081** The first argument passed to this function is a serial-type that
65082** corresponds to an integer - all values between 1 and 9 inclusive
65083** except 7. The second points to a buffer containing an integer value
65084** serialized according to serial_type. This function deserializes
65085** and returns the value.
65086*/
65087static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
65088  u32 y;
65089  assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
65090  switch( serial_type ){
65091    case 0:
65092    case 1:
65093      testcase( aKey[0]&0x80 );
65094      return ONE_BYTE_INT(aKey);
65095    case 2:
65096      testcase( aKey[0]&0x80 );
65097      return TWO_BYTE_INT(aKey);
65098    case 3:
65099      testcase( aKey[0]&0x80 );
65100      return THREE_BYTE_INT(aKey);
65101    case 4: {
65102      testcase( aKey[0]&0x80 );
65103      y = FOUR_BYTE_UINT(aKey);
65104      return (i64)*(int*)&y;
65105    }
65106    case 5: {
65107      testcase( aKey[0]&0x80 );
65108      return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
65109    }
65110    case 6: {
65111      u64 x = FOUR_BYTE_UINT(aKey);
65112      testcase( aKey[0]&0x80 );
65113      x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
65114      return (i64)*(i64*)&x;
65115    }
65116  }
65117
65118  return (serial_type - 8);
65119}
65120
65121/*
65122** This function compares the two table rows or index records
65123** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
65124** or positive integer if key1 is less than, equal to or
65125** greater than key2.  The {nKey1, pKey1} key must be a blob
65126** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
65127** key must be a parsed key such as obtained from
65128** sqlite3VdbeParseRecord.
65129**
65130** If argument bSkip is non-zero, it is assumed that the caller has already
65131** determined that the first fields of the keys are equal.
65132**
65133** Key1 and Key2 do not have to contain the same number of fields. If all
65134** fields that appear in both keys are equal, then pPKey2->default_rc is
65135** returned.
65136**
65137** If database corruption is discovered, set pPKey2->isCorrupt to non-zero
65138** and return 0.
65139*/
65140SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
65141  int nKey1, const void *pKey1,   /* Left key */
65142  UnpackedRecord *pPKey2,         /* Right key */
65143  int bSkip                       /* If true, skip the first field */
65144){
65145  u32 d1;                         /* Offset into aKey[] of next data element */
65146  int i;                          /* Index of next field to compare */
65147  u32 szHdr1;                     /* Size of record header in bytes */
65148  u32 idx1;                       /* Offset of first type in header */
65149  int rc = 0;                     /* Return value */
65150  Mem *pRhs = pPKey2->aMem;       /* Next field of pPKey2 to compare */
65151  KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
65152  const unsigned char *aKey1 = (const unsigned char *)pKey1;
65153  Mem mem1;
65154
65155  /* If bSkip is true, then the caller has already determined that the first
65156  ** two elements in the keys are equal. Fix the various stack variables so
65157  ** that this routine begins comparing at the second field. */
65158  if( bSkip ){
65159    u32 s1;
65160    idx1 = 1 + getVarint32(&aKey1[1], s1);
65161    szHdr1 = aKey1[0];
65162    d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
65163    i = 1;
65164    pRhs++;
65165  }else{
65166    idx1 = getVarint32(aKey1, szHdr1);
65167    d1 = szHdr1;
65168    if( d1>(unsigned)nKey1 ){
65169      pPKey2->isCorrupt = (u8)SQLITE_CORRUPT_BKPT;
65170      return 0;  /* Corruption */
65171    }
65172    i = 0;
65173  }
65174
65175  VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
65176  assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField
65177       || CORRUPT_DB );
65178  assert( pPKey2->pKeyInfo->aSortOrder!=0 );
65179  assert( pPKey2->pKeyInfo->nField>0 );
65180  assert( idx1<=szHdr1 || CORRUPT_DB );
65181  do{
65182    u32 serial_type;
65183
65184    /* RHS is an integer */
65185    if( pRhs->flags & MEM_Int ){
65186      serial_type = aKey1[idx1];
65187      testcase( serial_type==12 );
65188      if( serial_type>=12 ){
65189        rc = +1;
65190      }else if( serial_type==0 ){
65191        rc = -1;
65192      }else if( serial_type==7 ){
65193        double rhs = (double)pRhs->u.i;
65194        sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
65195        if( mem1.r<rhs ){
65196          rc = -1;
65197        }else if( mem1.r>rhs ){
65198          rc = +1;
65199        }
65200      }else{
65201        i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
65202        i64 rhs = pRhs->u.i;
65203        if( lhs<rhs ){
65204          rc = -1;
65205        }else if( lhs>rhs ){
65206          rc = +1;
65207        }
65208      }
65209    }
65210
65211    /* RHS is real */
65212    else if( pRhs->flags & MEM_Real ){
65213      serial_type = aKey1[idx1];
65214      if( serial_type>=12 ){
65215        rc = +1;
65216      }else if( serial_type==0 ){
65217        rc = -1;
65218      }else{
65219        double rhs = pRhs->r;
65220        double lhs;
65221        sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
65222        if( serial_type==7 ){
65223          lhs = mem1.r;
65224        }else{
65225          lhs = (double)mem1.u.i;
65226        }
65227        if( lhs<rhs ){
65228          rc = -1;
65229        }else if( lhs>rhs ){
65230          rc = +1;
65231        }
65232      }
65233    }
65234
65235    /* RHS is a string */
65236    else if( pRhs->flags & MEM_Str ){
65237      getVarint32(&aKey1[idx1], serial_type);
65238      testcase( serial_type==12 );
65239      if( serial_type<12 ){
65240        rc = -1;
65241      }else if( !(serial_type & 0x01) ){
65242        rc = +1;
65243      }else{
65244        mem1.n = (serial_type - 12) / 2;
65245        testcase( (d1+mem1.n)==(unsigned)nKey1 );
65246        testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
65247        if( (d1+mem1.n) > (unsigned)nKey1 ){
65248          pPKey2->isCorrupt = (u8)SQLITE_CORRUPT_BKPT;
65249          return 0;                /* Corruption */
65250        }else if( pKeyInfo->aColl[i] ){
65251          mem1.enc = pKeyInfo->enc;
65252          mem1.db = pKeyInfo->db;
65253          mem1.flags = MEM_Str;
65254          mem1.z = (char*)&aKey1[d1];
65255          rc = vdbeCompareMemString(&mem1, pRhs, pKeyInfo->aColl[i]);
65256        }else{
65257          int nCmp = MIN(mem1.n, pRhs->n);
65258          rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
65259          if( rc==0 ) rc = mem1.n - pRhs->n;
65260        }
65261      }
65262    }
65263
65264    /* RHS is a blob */
65265    else if( pRhs->flags & MEM_Blob ){
65266      getVarint32(&aKey1[idx1], serial_type);
65267      testcase( serial_type==12 );
65268      if( serial_type<12 || (serial_type & 0x01) ){
65269        rc = -1;
65270      }else{
65271        int nStr = (serial_type - 12) / 2;
65272        testcase( (d1+nStr)==(unsigned)nKey1 );
65273        testcase( (d1+nStr+1)==(unsigned)nKey1 );
65274        if( (d1+nStr) > (unsigned)nKey1 ){
65275          pPKey2->isCorrupt = (u8)SQLITE_CORRUPT_BKPT;
65276          return 0;                /* Corruption */
65277        }else{
65278          int nCmp = MIN(nStr, pRhs->n);
65279          rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
65280          if( rc==0 ) rc = nStr - pRhs->n;
65281        }
65282      }
65283    }
65284
65285    /* RHS is null */
65286    else{
65287      serial_type = aKey1[idx1];
65288      rc = (serial_type!=0);
65289    }
65290
65291    if( rc!=0 ){
65292      if( pKeyInfo->aSortOrder[i] ){
65293        rc = -rc;
65294      }
65295      assert( CORRUPT_DB
65296          || (rc<0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)<0)
65297          || (rc>0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)>0)
65298          || pKeyInfo->db->mallocFailed
65299      );
65300      assert( mem1.zMalloc==0 );  /* See comment below */
65301      return rc;
65302    }
65303
65304    i++;
65305    pRhs++;
65306    d1 += sqlite3VdbeSerialTypeLen(serial_type);
65307    idx1 += sqlite3VarintLen(serial_type);
65308  }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
65309
65310  /* No memory allocation is ever used on mem1.  Prove this using
65311  ** the following assert().  If the assert() fails, it indicates a
65312  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).  */
65313  assert( mem1.zMalloc==0 );
65314
65315  /* rc==0 here means that one or both of the keys ran out of fields and
65316  ** all the fields up to that point were equal. Return the the default_rc
65317  ** value.  */
65318  assert( CORRUPT_DB
65319       || pPKey2->default_rc==vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)
65320  );
65321  return pPKey2->default_rc;
65322}
65323
65324/*
65325** This function is an optimized version of sqlite3VdbeRecordCompare()
65326** that (a) the first field of pPKey2 is an integer, and (b) the
65327** size-of-header varint at the start of (pKey1/nKey1) fits in a single
65328** byte (i.e. is less than 128).
65329**
65330** To avoid concerns about buffer overreads, this routine is only used
65331** on schemas where the maximum valid header size is 63 bytes or less.
65332*/
65333static int vdbeRecordCompareInt(
65334  int nKey1, const void *pKey1, /* Left key */
65335  UnpackedRecord *pPKey2,       /* Right key */
65336  int bSkip                     /* Ignored */
65337){
65338  const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
65339  int serial_type = ((const u8*)pKey1)[1];
65340  int res;
65341  u32 y;
65342  u64 x;
65343  i64 v = pPKey2->aMem[0].u.i;
65344  i64 lhs;
65345  UNUSED_PARAMETER(bSkip);
65346
65347  assert( bSkip==0 );
65348  assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
65349  switch( serial_type ){
65350    case 1: { /* 1-byte signed integer */
65351      lhs = ONE_BYTE_INT(aKey);
65352      testcase( lhs<0 );
65353      break;
65354    }
65355    case 2: { /* 2-byte signed integer */
65356      lhs = TWO_BYTE_INT(aKey);
65357      testcase( lhs<0 );
65358      break;
65359    }
65360    case 3: { /* 3-byte signed integer */
65361      lhs = THREE_BYTE_INT(aKey);
65362      testcase( lhs<0 );
65363      break;
65364    }
65365    case 4: { /* 4-byte signed integer */
65366      y = FOUR_BYTE_UINT(aKey);
65367      lhs = (i64)*(int*)&y;
65368      testcase( lhs<0 );
65369      break;
65370    }
65371    case 5: { /* 6-byte signed integer */
65372      lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
65373      testcase( lhs<0 );
65374      break;
65375    }
65376    case 6: { /* 8-byte signed integer */
65377      x = FOUR_BYTE_UINT(aKey);
65378      x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
65379      lhs = *(i64*)&x;
65380      testcase( lhs<0 );
65381      break;
65382    }
65383    case 8:
65384      lhs = 0;
65385      break;
65386    case 9:
65387      lhs = 1;
65388      break;
65389
65390    /* This case could be removed without changing the results of running
65391    ** this code. Including it causes gcc to generate a faster switch
65392    ** statement (since the range of switch targets now starts at zero and
65393    ** is contiguous) but does not cause any duplicate code to be generated
65394    ** (as gcc is clever enough to combine the two like cases). Other
65395    ** compilers might be similar.  */
65396    case 0: case 7:
65397      return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2, 0);
65398
65399    default:
65400      return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2, 0);
65401  }
65402
65403  if( v>lhs ){
65404    res = pPKey2->r1;
65405  }else if( v<lhs ){
65406    res = pPKey2->r2;
65407  }else if( pPKey2->nField>1 ){
65408    /* The first fields of the two keys are equal. Compare the trailing
65409    ** fields.  */
65410    res = sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2, 1);
65411  }else{
65412    /* The first fields of the two keys are equal and there are no trailing
65413    ** fields. Return pPKey2->default_rc in this case. */
65414    res = pPKey2->default_rc;
65415  }
65416
65417  assert( (res==0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)==0)
65418       || (res<0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)<0)
65419       || (res>0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)>0)
65420       || CORRUPT_DB
65421  );
65422  return res;
65423}
65424
65425/*
65426** This function is an optimized version of sqlite3VdbeRecordCompare()
65427** that (a) the first field of pPKey2 is a string, that (b) the first field
65428** uses the collation sequence BINARY and (c) that the size-of-header varint
65429** at the start of (pKey1/nKey1) fits in a single byte.
65430*/
65431static int vdbeRecordCompareString(
65432  int nKey1, const void *pKey1, /* Left key */
65433  UnpackedRecord *pPKey2,       /* Right key */
65434  int bSkip
65435){
65436  const u8 *aKey1 = (const u8*)pKey1;
65437  int serial_type;
65438  int res;
65439  UNUSED_PARAMETER(bSkip);
65440
65441  assert( bSkip==0 );
65442  getVarint32(&aKey1[1], serial_type);
65443
65444  if( serial_type<12 ){
65445    res = pPKey2->r1;      /* (pKey1/nKey1) is a number or a null */
65446  }else if( !(serial_type & 0x01) ){
65447    res = pPKey2->r2;      /* (pKey1/nKey1) is a blob */
65448  }else{
65449    int nCmp;
65450    int nStr;
65451    int szHdr = aKey1[0];
65452
65453    nStr = (serial_type-12) / 2;
65454    if( (szHdr + nStr) > nKey1 ){
65455      pPKey2->isCorrupt = (u8)SQLITE_CORRUPT_BKPT;
65456      return 0;    /* Corruption */
65457    }
65458    nCmp = MIN( pPKey2->aMem[0].n, nStr );
65459    res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
65460
65461    if( res==0 ){
65462      res = nStr - pPKey2->aMem[0].n;
65463      if( res==0 ){
65464        if( pPKey2->nField>1 ){
65465          res = sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2, 1);
65466        }else{
65467          res = pPKey2->default_rc;
65468        }
65469      }else if( res>0 ){
65470        res = pPKey2->r2;
65471      }else{
65472        res = pPKey2->r1;
65473      }
65474    }else if( res>0 ){
65475      res = pPKey2->r2;
65476    }else{
65477      res = pPKey2->r1;
65478    }
65479  }
65480
65481  assert( (res==0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)==0)
65482       || (res<0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)<0)
65483       || (res>0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)>0)
65484       || CORRUPT_DB
65485  );
65486  return res;
65487}
65488
65489/*
65490** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
65491** suitable for comparing serialized records to the unpacked record passed
65492** as the only argument.
65493*/
65494SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
65495  /* varintRecordCompareInt() and varintRecordCompareString() both assume
65496  ** that the size-of-header varint that occurs at the start of each record
65497  ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
65498  ** also assumes that it is safe to overread a buffer by at least the
65499  ** maximum possible legal header size plus 8 bytes. Because there is
65500  ** guaranteed to be at least 74 (but not 136) bytes of padding following each
65501  ** buffer passed to varintRecordCompareInt() this makes it convenient to
65502  ** limit the size of the header to 64 bytes in cases where the first field
65503  ** is an integer.
65504  **
65505  ** The easiest way to enforce this limit is to consider only records with
65506  ** 13 fields or less. If the first field is an integer, the maximum legal
65507  ** header size is (12*5 + 1 + 1) bytes.  */
65508  if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
65509    int flags = p->aMem[0].flags;
65510    if( p->pKeyInfo->aSortOrder[0] ){
65511      p->r1 = 1;
65512      p->r2 = -1;
65513    }else{
65514      p->r1 = -1;
65515      p->r2 = 1;
65516    }
65517    if( (flags & MEM_Int) ){
65518      return vdbeRecordCompareInt;
65519    }
65520    testcase( flags & MEM_Real );
65521    testcase( flags & MEM_Null );
65522    testcase( flags & MEM_Blob );
65523    if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
65524      assert( flags & MEM_Str );
65525      return vdbeRecordCompareString;
65526    }
65527  }
65528
65529  return sqlite3VdbeRecordCompare;
65530}
65531
65532/*
65533** pCur points at an index entry created using the OP_MakeRecord opcode.
65534** Read the rowid (the last field in the record) and store it in *rowid.
65535** Return SQLITE_OK if everything works, or an error code otherwise.
65536**
65537** pCur might be pointing to text obtained from a corrupt database file.
65538** So the content cannot be trusted.  Do appropriate checks on the content.
65539*/
65540SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
65541  i64 nCellKey = 0;
65542  int rc;
65543  u32 szHdr;        /* Size of the header */
65544  u32 typeRowid;    /* Serial type of the rowid */
65545  u32 lenRowid;     /* Size of the rowid */
65546  Mem m, v;
65547
65548  UNUSED_PARAMETER(db);
65549
65550  /* Get the size of the index entry.  Only indices entries of less
65551  ** than 2GiB are support - anything large must be database corruption.
65552  ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
65553  ** this code can safely assume that nCellKey is 32-bits
65554  */
65555  assert( sqlite3BtreeCursorIsValid(pCur) );
65556  VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
65557  assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
65558  assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
65559
65560  /* Read in the complete content of the index entry */
65561  memset(&m, 0, sizeof(m));
65562  rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
65563  if( rc ){
65564    return rc;
65565  }
65566
65567  /* The index entry must begin with a header size */
65568  (void)getVarint32((u8*)m.z, szHdr);
65569  testcase( szHdr==3 );
65570  testcase( szHdr==m.n );
65571  if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
65572    goto idx_rowid_corruption;
65573  }
65574
65575  /* The last field of the index should be an integer - the ROWID.
65576  ** Verify that the last entry really is an integer. */
65577  (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
65578  testcase( typeRowid==1 );
65579  testcase( typeRowid==2 );
65580  testcase( typeRowid==3 );
65581  testcase( typeRowid==4 );
65582  testcase( typeRowid==5 );
65583  testcase( typeRowid==6 );
65584  testcase( typeRowid==8 );
65585  testcase( typeRowid==9 );
65586  if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
65587    goto idx_rowid_corruption;
65588  }
65589  lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
65590  testcase( (u32)m.n==szHdr+lenRowid );
65591  if( unlikely((u32)m.n<szHdr+lenRowid) ){
65592    goto idx_rowid_corruption;
65593  }
65594
65595  /* Fetch the integer off the end of the index record */
65596  sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
65597  *rowid = v.u.i;
65598  sqlite3VdbeMemRelease(&m);
65599  return SQLITE_OK;
65600
65601  /* Jump here if database corruption is detected after m has been
65602  ** allocated.  Free the m object and return SQLITE_CORRUPT. */
65603idx_rowid_corruption:
65604  testcase( m.zMalloc!=0 );
65605  sqlite3VdbeMemRelease(&m);
65606  return SQLITE_CORRUPT_BKPT;
65607}
65608
65609/*
65610** Compare the key of the index entry that cursor pC is pointing to against
65611** the key string in pUnpacked.  Write into *pRes a number
65612** that is negative, zero, or positive if pC is less than, equal to,
65613** or greater than pUnpacked.  Return SQLITE_OK on success.
65614**
65615** pUnpacked is either created without a rowid or is truncated so that it
65616** omits the rowid at the end.  The rowid at the end of the index entry
65617** is ignored as well.  Hence, this routine only compares the prefixes
65618** of the keys prior to the final rowid, not the entire key.
65619*/
65620SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
65621  VdbeCursor *pC,                  /* The cursor to compare against */
65622  UnpackedRecord *pUnpacked,       /* Unpacked version of key */
65623  int *res                         /* Write the comparison result here */
65624){
65625  i64 nCellKey = 0;
65626  int rc;
65627  BtCursor *pCur = pC->pCursor;
65628  Mem m;
65629
65630  assert( sqlite3BtreeCursorIsValid(pCur) );
65631  VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
65632  assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
65633  /* nCellKey will always be between 0 and 0xffffffff because of the way
65634  ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
65635  if( nCellKey<=0 || nCellKey>0x7fffffff ){
65636    *res = 0;
65637    return SQLITE_CORRUPT_BKPT;
65638  }
65639  memset(&m, 0, sizeof(m));
65640  rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (u32)nCellKey, 1, &m);
65641  if( rc ){
65642    return rc;
65643  }
65644  *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked, 0);
65645  sqlite3VdbeMemRelease(&m);
65646  return SQLITE_OK;
65647}
65648
65649/*
65650** This routine sets the value to be returned by subsequent calls to
65651** sqlite3_changes() on the database handle 'db'.
65652*/
65653SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
65654  assert( sqlite3_mutex_held(db->mutex) );
65655  db->nChange = nChange;
65656  db->nTotalChange += nChange;
65657}
65658
65659/*
65660** Set a flag in the vdbe to update the change counter when it is finalised
65661** or reset.
65662*/
65663SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
65664  v->changeCntOn = 1;
65665}
65666
65667/*
65668** Mark every prepared statement associated with a database connection
65669** as expired.
65670**
65671** An expired statement means that recompilation of the statement is
65672** recommend.  Statements expire when things happen that make their
65673** programs obsolete.  Removing user-defined functions or collating
65674** sequences, or changing an authorization function are the types of
65675** things that make prepared statements obsolete.
65676*/
65677SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
65678  Vdbe *p;
65679  for(p = db->pVdbe; p; p=p->pNext){
65680    p->expired = 1;
65681  }
65682}
65683
65684/*
65685** Return the database associated with the Vdbe.
65686*/
65687SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
65688  return v->db;
65689}
65690
65691/*
65692** Return a pointer to an sqlite3_value structure containing the value bound
65693** parameter iVar of VM v. Except, if the value is an SQL NULL, return
65694** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
65695** constants) to the value before returning it.
65696**
65697** The returned value must be freed by the caller using sqlite3ValueFree().
65698*/
65699SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
65700  assert( iVar>0 );
65701  if( v ){
65702    Mem *pMem = &v->aVar[iVar-1];
65703    if( 0==(pMem->flags & MEM_Null) ){
65704      sqlite3_value *pRet = sqlite3ValueNew(v->db);
65705      if( pRet ){
65706        sqlite3VdbeMemCopy((Mem *)pRet, pMem);
65707        sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
65708      }
65709      return pRet;
65710    }
65711  }
65712  return 0;
65713}
65714
65715/*
65716** Configure SQL variable iVar so that binding a new value to it signals
65717** to sqlite3_reoptimize() that re-preparing the statement may result
65718** in a better query plan.
65719*/
65720SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
65721  assert( iVar>0 );
65722  if( iVar>32 ){
65723    v->expmask = 0xffffffff;
65724  }else{
65725    v->expmask |= ((u32)1 << (iVar-1));
65726  }
65727}
65728
65729#ifndef SQLITE_OMIT_VIRTUALTABLE
65730/*
65731** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
65732** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
65733** in memory obtained from sqlite3DbMalloc).
65734*/
65735SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
65736  sqlite3 *db = p->db;
65737  sqlite3DbFree(db, p->zErrMsg);
65738  p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
65739  sqlite3_free(pVtab->zErrMsg);
65740  pVtab->zErrMsg = 0;
65741}
65742#endif /* SQLITE_OMIT_VIRTUALTABLE */
65743
65744/************** End of vdbeaux.c *********************************************/
65745/************** Begin file vdbeapi.c *****************************************/
65746/*
65747** 2004 May 26
65748**
65749** The author disclaims copyright to this source code.  In place of
65750** a legal notice, here is a blessing:
65751**
65752**    May you do good and not evil.
65753**    May you find forgiveness for yourself and forgive others.
65754**    May you share freely, never taking more than you give.
65755**
65756*************************************************************************
65757**
65758** This file contains code use to implement APIs that are part of the
65759** VDBE.
65760*/
65761
65762#ifndef SQLITE_OMIT_DEPRECATED
65763/*
65764** Return TRUE (non-zero) of the statement supplied as an argument needs
65765** to be recompiled.  A statement needs to be recompiled whenever the
65766** execution environment changes in a way that would alter the program
65767** that sqlite3_prepare() generates.  For example, if new functions or
65768** collating sequences are registered or if an authorizer function is
65769** added or changed.
65770*/
65771SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
65772  Vdbe *p = (Vdbe*)pStmt;
65773  return p==0 || p->expired;
65774}
65775#endif
65776
65777/*
65778** Check on a Vdbe to make sure it has not been finalized.  Log
65779** an error and return true if it has been finalized (or is otherwise
65780** invalid).  Return false if it is ok.
65781*/
65782static int vdbeSafety(Vdbe *p){
65783  if( p->db==0 ){
65784    sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
65785    return 1;
65786  }else{
65787    return 0;
65788  }
65789}
65790static int vdbeSafetyNotNull(Vdbe *p){
65791  if( p==0 ){
65792    sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
65793    return 1;
65794  }else{
65795    return vdbeSafety(p);
65796  }
65797}
65798
65799/*
65800** The following routine destroys a virtual machine that is created by
65801** the sqlite3_compile() routine. The integer returned is an SQLITE_
65802** success/failure code that describes the result of executing the virtual
65803** machine.
65804**
65805** This routine sets the error code and string returned by
65806** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
65807*/
65808SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
65809  int rc;
65810  if( pStmt==0 ){
65811    /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
65812    ** pointer is a harmless no-op. */
65813    rc = SQLITE_OK;
65814  }else{
65815    Vdbe *v = (Vdbe*)pStmt;
65816    sqlite3 *db = v->db;
65817    if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
65818    sqlite3_mutex_enter(db->mutex);
65819    rc = sqlite3VdbeFinalize(v);
65820    rc = sqlite3ApiExit(db, rc);
65821    sqlite3LeaveMutexAndCloseZombie(db);
65822  }
65823  return rc;
65824}
65825
65826/*
65827** Terminate the current execution of an SQL statement and reset it
65828** back to its starting state so that it can be reused. A success code from
65829** the prior execution is returned.
65830**
65831** This routine sets the error code and string returned by
65832** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
65833*/
65834SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
65835  int rc;
65836  if( pStmt==0 ){
65837    rc = SQLITE_OK;
65838  }else{
65839    Vdbe *v = (Vdbe*)pStmt;
65840    sqlite3_mutex_enter(v->db->mutex);
65841    rc = sqlite3VdbeReset(v);
65842    sqlite3VdbeRewind(v);
65843    assert( (rc & (v->db->errMask))==rc );
65844    rc = sqlite3ApiExit(v->db, rc);
65845    sqlite3_mutex_leave(v->db->mutex);
65846  }
65847  return rc;
65848}
65849
65850/*
65851** Set all the parameters in the compiled SQL statement to NULL.
65852*/
65853SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
65854  int i;
65855  int rc = SQLITE_OK;
65856  Vdbe *p = (Vdbe*)pStmt;
65857#if SQLITE_THREADSAFE
65858  sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
65859#endif
65860  sqlite3_mutex_enter(mutex);
65861  for(i=0; i<p->nVar; i++){
65862    sqlite3VdbeMemRelease(&p->aVar[i]);
65863    p->aVar[i].flags = MEM_Null;
65864  }
65865  if( p->isPrepareV2 && p->expmask ){
65866    p->expired = 1;
65867  }
65868  sqlite3_mutex_leave(mutex);
65869  return rc;
65870}
65871
65872
65873/**************************** sqlite3_value_  *******************************
65874** The following routines extract information from a Mem or sqlite3_value
65875** structure.
65876*/
65877SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
65878  Mem *p = (Mem*)pVal;
65879  if( p->flags & (MEM_Blob|MEM_Str) ){
65880    sqlite3VdbeMemExpandBlob(p);
65881    p->flags |= MEM_Blob;
65882    return p->n ? p->z : 0;
65883  }else{
65884    return sqlite3_value_text(pVal);
65885  }
65886}
65887SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
65888  return sqlite3ValueBytes(pVal, SQLITE_UTF8);
65889}
65890SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
65891  return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
65892}
65893SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
65894  return sqlite3VdbeRealValue((Mem*)pVal);
65895}
65896SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
65897  return (int)sqlite3VdbeIntValue((Mem*)pVal);
65898}
65899SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
65900  return sqlite3VdbeIntValue((Mem*)pVal);
65901}
65902SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
65903  return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
65904}
65905#ifndef SQLITE_OMIT_UTF16
65906SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
65907  return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
65908}
65909SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
65910  return sqlite3ValueText(pVal, SQLITE_UTF16BE);
65911}
65912SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
65913  return sqlite3ValueText(pVal, SQLITE_UTF16LE);
65914}
65915#endif /* SQLITE_OMIT_UTF16 */
65916SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
65917  static const u8 aType[] = {
65918     SQLITE_BLOB,     /* 0x00 */
65919     SQLITE_NULL,     /* 0x01 */
65920     SQLITE_TEXT,     /* 0x02 */
65921     SQLITE_NULL,     /* 0x03 */
65922     SQLITE_INTEGER,  /* 0x04 */
65923     SQLITE_NULL,     /* 0x05 */
65924     SQLITE_INTEGER,  /* 0x06 */
65925     SQLITE_NULL,     /* 0x07 */
65926     SQLITE_FLOAT,    /* 0x08 */
65927     SQLITE_NULL,     /* 0x09 */
65928     SQLITE_FLOAT,    /* 0x0a */
65929     SQLITE_NULL,     /* 0x0b */
65930     SQLITE_INTEGER,  /* 0x0c */
65931     SQLITE_NULL,     /* 0x0d */
65932     SQLITE_INTEGER,  /* 0x0e */
65933     SQLITE_NULL,     /* 0x0f */
65934     SQLITE_BLOB,     /* 0x10 */
65935     SQLITE_NULL,     /* 0x11 */
65936     SQLITE_TEXT,     /* 0x12 */
65937     SQLITE_NULL,     /* 0x13 */
65938     SQLITE_INTEGER,  /* 0x14 */
65939     SQLITE_NULL,     /* 0x15 */
65940     SQLITE_INTEGER,  /* 0x16 */
65941     SQLITE_NULL,     /* 0x17 */
65942     SQLITE_FLOAT,    /* 0x18 */
65943     SQLITE_NULL,     /* 0x19 */
65944     SQLITE_FLOAT,    /* 0x1a */
65945     SQLITE_NULL,     /* 0x1b */
65946     SQLITE_INTEGER,  /* 0x1c */
65947     SQLITE_NULL,     /* 0x1d */
65948     SQLITE_INTEGER,  /* 0x1e */
65949     SQLITE_NULL,     /* 0x1f */
65950  };
65951  return aType[pVal->flags&MEM_AffMask];
65952}
65953
65954/**************************** sqlite3_result_  *******************************
65955** The following routines are used by user-defined functions to specify
65956** the function result.
65957**
65958** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
65959** result as a string or blob but if the string or blob is too large, it
65960** then sets the error code to SQLITE_TOOBIG
65961*/
65962static void setResultStrOrError(
65963  sqlite3_context *pCtx,  /* Function context */
65964  const char *z,          /* String pointer */
65965  int n,                  /* Bytes in string, or negative */
65966  u8 enc,                 /* Encoding of z.  0 for BLOBs */
65967  void (*xDel)(void*)     /* Destructor function */
65968){
65969  if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
65970    sqlite3_result_error_toobig(pCtx);
65971  }
65972}
65973SQLITE_API void sqlite3_result_blob(
65974  sqlite3_context *pCtx,
65975  const void *z,
65976  int n,
65977  void (*xDel)(void *)
65978){
65979  assert( n>=0 );
65980  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
65981  setResultStrOrError(pCtx, z, n, 0, xDel);
65982}
65983SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
65984  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
65985  sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
65986}
65987SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
65988  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
65989  pCtx->isError = SQLITE_ERROR;
65990  pCtx->fErrorOrAux = 1;
65991  sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
65992}
65993#ifndef SQLITE_OMIT_UTF16
65994SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
65995  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
65996  pCtx->isError = SQLITE_ERROR;
65997  pCtx->fErrorOrAux = 1;
65998  sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
65999}
66000#endif
66001SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
66002  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
66003  sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
66004}
66005SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
66006  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
66007  sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
66008}
66009SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
66010  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
66011  sqlite3VdbeMemSetNull(&pCtx->s);
66012}
66013SQLITE_API void sqlite3_result_text(
66014  sqlite3_context *pCtx,
66015  const char *z,
66016  int n,
66017  void (*xDel)(void *)
66018){
66019  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
66020  setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
66021}
66022#ifndef SQLITE_OMIT_UTF16
66023SQLITE_API void sqlite3_result_text16(
66024  sqlite3_context *pCtx,
66025  const void *z,
66026  int n,
66027  void (*xDel)(void *)
66028){
66029  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
66030  setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
66031}
66032SQLITE_API void sqlite3_result_text16be(
66033  sqlite3_context *pCtx,
66034  const void *z,
66035  int n,
66036  void (*xDel)(void *)
66037){
66038  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
66039  setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
66040}
66041SQLITE_API void sqlite3_result_text16le(
66042  sqlite3_context *pCtx,
66043  const void *z,
66044  int n,
66045  void (*xDel)(void *)
66046){
66047  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
66048  setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
66049}
66050#endif /* SQLITE_OMIT_UTF16 */
66051SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
66052  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
66053  sqlite3VdbeMemCopy(&pCtx->s, pValue);
66054}
66055SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
66056  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
66057  sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
66058}
66059SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
66060  pCtx->isError = errCode;
66061  pCtx->fErrorOrAux = 1;
66062  if( pCtx->s.flags & MEM_Null ){
66063    sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
66064                         SQLITE_UTF8, SQLITE_STATIC);
66065  }
66066}
66067
66068/* Force an SQLITE_TOOBIG error. */
66069SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
66070  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
66071  pCtx->isError = SQLITE_TOOBIG;
66072  pCtx->fErrorOrAux = 1;
66073  sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
66074                       SQLITE_UTF8, SQLITE_STATIC);
66075}
66076
66077/* An SQLITE_NOMEM error. */
66078SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
66079  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
66080  sqlite3VdbeMemSetNull(&pCtx->s);
66081  pCtx->isError = SQLITE_NOMEM;
66082  pCtx->fErrorOrAux = 1;
66083  pCtx->s.db->mallocFailed = 1;
66084}
66085
66086/*
66087** This function is called after a transaction has been committed. It
66088** invokes callbacks registered with sqlite3_wal_hook() as required.
66089*/
66090static int doWalCallbacks(sqlite3 *db){
66091  int rc = SQLITE_OK;
66092#ifndef SQLITE_OMIT_WAL
66093  int i;
66094  for(i=0; i<db->nDb; i++){
66095    Btree *pBt = db->aDb[i].pBt;
66096    if( pBt ){
66097      int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
66098      if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
66099        rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
66100      }
66101    }
66102  }
66103#endif
66104  return rc;
66105}
66106
66107/*
66108** Execute the statement pStmt, either until a row of data is ready, the
66109** statement is completely executed or an error occurs.
66110**
66111** This routine implements the bulk of the logic behind the sqlite_step()
66112** API.  The only thing omitted is the automatic recompile if a
66113** schema change has occurred.  That detail is handled by the
66114** outer sqlite3_step() wrapper procedure.
66115*/
66116static int sqlite3Step(Vdbe *p){
66117  sqlite3 *db;
66118  int rc;
66119
66120  assert(p);
66121  if( p->magic!=VDBE_MAGIC_RUN ){
66122    /* We used to require that sqlite3_reset() be called before retrying
66123    ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
66124    ** with version 3.7.0, we changed this so that sqlite3_reset() would
66125    ** be called automatically instead of throwing the SQLITE_MISUSE error.
66126    ** This "automatic-reset" change is not technically an incompatibility,
66127    ** since any application that receives an SQLITE_MISUSE is broken by
66128    ** definition.
66129    **
66130    ** Nevertheless, some published applications that were originally written
66131    ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
66132    ** returns, and those were broken by the automatic-reset change.  As a
66133    ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
66134    ** legacy behavior of returning SQLITE_MISUSE for cases where the
66135    ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
66136    ** or SQLITE_BUSY error.
66137    */
66138#ifdef SQLITE_OMIT_AUTORESET
66139    if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
66140      sqlite3_reset((sqlite3_stmt*)p);
66141    }else{
66142      return SQLITE_MISUSE_BKPT;
66143    }
66144#else
66145    sqlite3_reset((sqlite3_stmt*)p);
66146#endif
66147  }
66148
66149  /* Check that malloc() has not failed. If it has, return early. */
66150  db = p->db;
66151  if( db->mallocFailed ){
66152    p->rc = SQLITE_NOMEM;
66153    return SQLITE_NOMEM;
66154  }
66155
66156  if( p->pc<=0 && p->expired ){
66157    p->rc = SQLITE_SCHEMA;
66158    rc = SQLITE_ERROR;
66159    goto end_of_step;
66160  }
66161  if( p->pc<0 ){
66162    /* If there are no other statements currently running, then
66163    ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
66164    ** from interrupting a statement that has not yet started.
66165    */
66166    if( db->nVdbeActive==0 ){
66167      db->u1.isInterrupted = 0;
66168    }
66169
66170    assert( db->nVdbeWrite>0 || db->autoCommit==0
66171        || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
66172    );
66173
66174#ifndef SQLITE_OMIT_TRACE
66175    if( db->xProfile && !db->init.busy ){
66176      sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
66177    }
66178#endif
66179
66180    db->nVdbeActive++;
66181    if( p->readOnly==0 ) db->nVdbeWrite++;
66182    if( p->bIsReader ) db->nVdbeRead++;
66183    p->pc = 0;
66184  }
66185#ifndef SQLITE_OMIT_EXPLAIN
66186  if( p->explain ){
66187    rc = sqlite3VdbeList(p);
66188  }else
66189#endif /* SQLITE_OMIT_EXPLAIN */
66190  {
66191    db->nVdbeExec++;
66192    rc = sqlite3VdbeExec(p);
66193    db->nVdbeExec--;
66194  }
66195
66196#ifndef SQLITE_OMIT_TRACE
66197  /* Invoke the profile callback if there is one
66198  */
66199  if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
66200    sqlite3_int64 iNow;
66201    sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
66202    db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
66203  }
66204#endif
66205
66206  if( rc==SQLITE_DONE ){
66207    assert( p->rc==SQLITE_OK );
66208    p->rc = doWalCallbacks(db);
66209    if( p->rc!=SQLITE_OK ){
66210      rc = SQLITE_ERROR;
66211    }
66212  }
66213
66214  db->errCode = rc;
66215  if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
66216    p->rc = SQLITE_NOMEM;
66217  }
66218end_of_step:
66219  /* At this point local variable rc holds the value that should be
66220  ** returned if this statement was compiled using the legacy
66221  ** sqlite3_prepare() interface. According to the docs, this can only
66222  ** be one of the values in the first assert() below. Variable p->rc
66223  ** contains the value that would be returned if sqlite3_finalize()
66224  ** were called on statement p.
66225  */
66226  assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
66227       || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
66228  );
66229  assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
66230  if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
66231    /* If this statement was prepared using sqlite3_prepare_v2(), and an
66232    ** error has occurred, then return the error code in p->rc to the
66233    ** caller. Set the error code in the database handle to the same value.
66234    */
66235    rc = sqlite3VdbeTransferError(p);
66236  }
66237  return (rc&db->errMask);
66238}
66239
66240/*
66241** This is the top-level implementation of sqlite3_step().  Call
66242** sqlite3Step() to do most of the work.  If a schema error occurs,
66243** call sqlite3Reprepare() and try again.
66244*/
66245SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
66246  int rc = SQLITE_OK;      /* Result from sqlite3Step() */
66247  int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
66248  Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
66249  int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
66250  sqlite3 *db;             /* The database connection */
66251
66252  if( vdbeSafetyNotNull(v) ){
66253    return SQLITE_MISUSE_BKPT;
66254  }
66255  db = v->db;
66256  sqlite3_mutex_enter(db->mutex);
66257  v->doingRerun = 0;
66258  while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
66259         && cnt++ < SQLITE_MAX_SCHEMA_RETRY
66260         && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
66261    sqlite3_reset(pStmt);
66262    v->doingRerun = 1;
66263    assert( v->expired==0 );
66264  }
66265  if( rc2!=SQLITE_OK ){
66266    /* This case occurs after failing to recompile an sql statement.
66267    ** The error message from the SQL compiler has already been loaded
66268    ** into the database handle. This block copies the error message
66269    ** from the database handle into the statement and sets the statement
66270    ** program counter to 0 to ensure that when the statement is
66271    ** finalized or reset the parser error message is available via
66272    ** sqlite3_errmsg() and sqlite3_errcode().
66273    */
66274    const char *zErr = (const char *)sqlite3_value_text(db->pErr);
66275    assert( zErr!=0 || db->mallocFailed );
66276    sqlite3DbFree(db, v->zErrMsg);
66277    if( !db->mallocFailed ){
66278      v->zErrMsg = sqlite3DbStrDup(db, zErr);
66279      v->rc = rc2;
66280    } else {
66281      v->zErrMsg = 0;
66282      v->rc = rc = SQLITE_NOMEM;
66283    }
66284  }
66285  rc = sqlite3ApiExit(db, rc);
66286  sqlite3_mutex_leave(db->mutex);
66287  return rc;
66288}
66289
66290
66291/*
66292** Extract the user data from a sqlite3_context structure and return a
66293** pointer to it.
66294*/
66295SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
66296  assert( p && p->pFunc );
66297  return p->pFunc->pUserData;
66298}
66299
66300/*
66301** Extract the user data from a sqlite3_context structure and return a
66302** pointer to it.
66303**
66304** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
66305** returns a copy of the pointer to the database connection (the 1st
66306** parameter) of the sqlite3_create_function() and
66307** sqlite3_create_function16() routines that originally registered the
66308** application defined function.
66309*/
66310SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
66311  assert( p && p->pFunc );
66312  return p->s.db;
66313}
66314
66315/*
66316** Return the current time for a statement
66317*/
66318SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
66319  Vdbe *v = p->pVdbe;
66320  int rc;
66321  if( v->iCurrentTime==0 ){
66322    rc = sqlite3OsCurrentTimeInt64(p->s.db->pVfs, &v->iCurrentTime);
66323    if( rc ) v->iCurrentTime = 0;
66324  }
66325  return v->iCurrentTime;
66326}
66327
66328/*
66329** The following is the implementation of an SQL function that always
66330** fails with an error message stating that the function is used in the
66331** wrong context.  The sqlite3_overload_function() API might construct
66332** SQL function that use this routine so that the functions will exist
66333** for name resolution but are actually overloaded by the xFindFunction
66334** method of virtual tables.
66335*/
66336SQLITE_PRIVATE void sqlite3InvalidFunction(
66337  sqlite3_context *context,  /* The function calling context */
66338  int NotUsed,               /* Number of arguments to the function */
66339  sqlite3_value **NotUsed2   /* Value of each argument */
66340){
66341  const char *zName = context->pFunc->zName;
66342  char *zErr;
66343  UNUSED_PARAMETER2(NotUsed, NotUsed2);
66344  zErr = sqlite3_mprintf(
66345      "unable to use function %s in the requested context", zName);
66346  sqlite3_result_error(context, zErr, -1);
66347  sqlite3_free(zErr);
66348}
66349
66350/*
66351** Allocate or return the aggregate context for a user function.  A new
66352** context is allocated on the first call.  Subsequent calls return the
66353** same context that was returned on prior calls.
66354*/
66355SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
66356  Mem *pMem;
66357  assert( p && p->pFunc && p->pFunc->xStep );
66358  assert( sqlite3_mutex_held(p->s.db->mutex) );
66359  pMem = p->pMem;
66360  testcase( nByte<0 );
66361  if( (pMem->flags & MEM_Agg)==0 ){
66362    if( nByte<=0 ){
66363      sqlite3VdbeMemReleaseExternal(pMem);
66364      pMem->flags = MEM_Null;
66365      pMem->z = 0;
66366    }else{
66367      sqlite3VdbeMemGrow(pMem, nByte, 0);
66368      pMem->flags = MEM_Agg;
66369      pMem->u.pDef = p->pFunc;
66370      if( pMem->z ){
66371        memset(pMem->z, 0, nByte);
66372      }
66373    }
66374  }
66375  return (void*)pMem->z;
66376}
66377
66378/*
66379** Return the auxilary data pointer, if any, for the iArg'th argument to
66380** the user-function defined by pCtx.
66381*/
66382SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
66383  AuxData *pAuxData;
66384
66385  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
66386  for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
66387    if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
66388  }
66389
66390  return (pAuxData ? pAuxData->pAux : 0);
66391}
66392
66393/*
66394** Set the auxilary data pointer and delete function, for the iArg'th
66395** argument to the user-function defined by pCtx. Any previous value is
66396** deleted by calling the delete function specified when it was set.
66397*/
66398SQLITE_API void sqlite3_set_auxdata(
66399  sqlite3_context *pCtx,
66400  int iArg,
66401  void *pAux,
66402  void (*xDelete)(void*)
66403){
66404  AuxData *pAuxData;
66405  Vdbe *pVdbe = pCtx->pVdbe;
66406
66407  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
66408  if( iArg<0 ) goto failed;
66409
66410  for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
66411    if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
66412  }
66413  if( pAuxData==0 ){
66414    pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
66415    if( !pAuxData ) goto failed;
66416    pAuxData->iOp = pCtx->iOp;
66417    pAuxData->iArg = iArg;
66418    pAuxData->pNext = pVdbe->pAuxData;
66419    pVdbe->pAuxData = pAuxData;
66420    if( pCtx->fErrorOrAux==0 ){
66421      pCtx->isError = 0;
66422      pCtx->fErrorOrAux = 1;
66423    }
66424  }else if( pAuxData->xDelete ){
66425    pAuxData->xDelete(pAuxData->pAux);
66426  }
66427
66428  pAuxData->pAux = pAux;
66429  pAuxData->xDelete = xDelete;
66430  return;
66431
66432failed:
66433  if( xDelete ){
66434    xDelete(pAux);
66435  }
66436}
66437
66438#ifndef SQLITE_OMIT_DEPRECATED
66439/*
66440** Return the number of times the Step function of a aggregate has been
66441** called.
66442**
66443** This function is deprecated.  Do not use it for new code.  It is
66444** provide only to avoid breaking legacy code.  New aggregate function
66445** implementations should keep their own counts within their aggregate
66446** context.
66447*/
66448SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
66449  assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
66450  return p->pMem->n;
66451}
66452#endif
66453
66454/*
66455** Return the number of columns in the result set for the statement pStmt.
66456*/
66457SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
66458  Vdbe *pVm = (Vdbe *)pStmt;
66459  return pVm ? pVm->nResColumn : 0;
66460}
66461
66462/*
66463** Return the number of values available from the current row of the
66464** currently executing statement pStmt.
66465*/
66466SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
66467  Vdbe *pVm = (Vdbe *)pStmt;
66468  if( pVm==0 || pVm->pResultSet==0 ) return 0;
66469  return pVm->nResColumn;
66470}
66471
66472/*
66473** Return a pointer to static memory containing an SQL NULL value.
66474*/
66475static const Mem *columnNullValue(void){
66476  /* Even though the Mem structure contains an element
66477  ** of type i64, on certain architectures (x86) with certain compiler
66478  ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
66479  ** instead of an 8-byte one. This all works fine, except that when
66480  ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
66481  ** that a Mem structure is located on an 8-byte boundary. To prevent
66482  ** these assert()s from failing, when building with SQLITE_DEBUG defined
66483  ** using gcc, we force nullMem to be 8-byte aligned using the magical
66484  ** __attribute__((aligned(8))) macro.  */
66485  static const Mem nullMem
66486#if defined(SQLITE_DEBUG) && defined(__GNUC__)
66487    __attribute__((aligned(8)))
66488#endif
66489    = {0, "", (double)0, {0}, 0, MEM_Null, 0,
66490#ifdef SQLITE_DEBUG
66491       0, 0,  /* pScopyFrom, pFiller */
66492#endif
66493       0, 0 };
66494  return &nullMem;
66495}
66496
66497/*
66498** Check to see if column iCol of the given statement is valid.  If
66499** it is, return a pointer to the Mem for the value of that column.
66500** If iCol is not valid, return a pointer to a Mem which has a value
66501** of NULL.
66502*/
66503static Mem *columnMem(sqlite3_stmt *pStmt, int i){
66504  Vdbe *pVm;
66505  Mem *pOut;
66506
66507  pVm = (Vdbe *)pStmt;
66508  if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
66509    sqlite3_mutex_enter(pVm->db->mutex);
66510    pOut = &pVm->pResultSet[i];
66511  }else{
66512    if( pVm && ALWAYS(pVm->db) ){
66513      sqlite3_mutex_enter(pVm->db->mutex);
66514      sqlite3Error(pVm->db, SQLITE_RANGE, 0);
66515    }
66516    pOut = (Mem*)columnNullValue();
66517  }
66518  return pOut;
66519}
66520
66521/*
66522** This function is called after invoking an sqlite3_value_XXX function on a
66523** column value (i.e. a value returned by evaluating an SQL expression in the
66524** select list of a SELECT statement) that may cause a malloc() failure. If
66525** malloc() has failed, the threads mallocFailed flag is cleared and the result
66526** code of statement pStmt set to SQLITE_NOMEM.
66527**
66528** Specifically, this is called from within:
66529**
66530**     sqlite3_column_int()
66531**     sqlite3_column_int64()
66532**     sqlite3_column_text()
66533**     sqlite3_column_text16()
66534**     sqlite3_column_real()
66535**     sqlite3_column_bytes()
66536**     sqlite3_column_bytes16()
66537**     sqiite3_column_blob()
66538*/
66539static void columnMallocFailure(sqlite3_stmt *pStmt)
66540{
66541  /* If malloc() failed during an encoding conversion within an
66542  ** sqlite3_column_XXX API, then set the return code of the statement to
66543  ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
66544  ** and _finalize() will return NOMEM.
66545  */
66546  Vdbe *p = (Vdbe *)pStmt;
66547  if( p ){
66548    p->rc = sqlite3ApiExit(p->db, p->rc);
66549    sqlite3_mutex_leave(p->db->mutex);
66550  }
66551}
66552
66553/**************************** sqlite3_column_  *******************************
66554** The following routines are used to access elements of the current row
66555** in the result set.
66556*/
66557SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
66558  const void *val;
66559  val = sqlite3_value_blob( columnMem(pStmt,i) );
66560  /* Even though there is no encoding conversion, value_blob() might
66561  ** need to call malloc() to expand the result of a zeroblob()
66562  ** expression.
66563  */
66564  columnMallocFailure(pStmt);
66565  return val;
66566}
66567SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
66568  int val = sqlite3_value_bytes( columnMem(pStmt,i) );
66569  columnMallocFailure(pStmt);
66570  return val;
66571}
66572SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
66573  int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
66574  columnMallocFailure(pStmt);
66575  return val;
66576}
66577SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
66578  double val = sqlite3_value_double( columnMem(pStmt,i) );
66579  columnMallocFailure(pStmt);
66580  return val;
66581}
66582SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
66583  int val = sqlite3_value_int( columnMem(pStmt,i) );
66584  columnMallocFailure(pStmt);
66585  return val;
66586}
66587SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
66588  sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
66589  columnMallocFailure(pStmt);
66590  return val;
66591}
66592SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
66593  const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
66594  columnMallocFailure(pStmt);
66595  return val;
66596}
66597SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
66598  Mem *pOut = columnMem(pStmt, i);
66599  if( pOut->flags&MEM_Static ){
66600    pOut->flags &= ~MEM_Static;
66601    pOut->flags |= MEM_Ephem;
66602  }
66603  columnMallocFailure(pStmt);
66604  return (sqlite3_value *)pOut;
66605}
66606#ifndef SQLITE_OMIT_UTF16
66607SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
66608  const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
66609  columnMallocFailure(pStmt);
66610  return val;
66611}
66612#endif /* SQLITE_OMIT_UTF16 */
66613SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
66614  int iType = sqlite3_value_type( columnMem(pStmt,i) );
66615  columnMallocFailure(pStmt);
66616  return iType;
66617}
66618
66619/*
66620** Convert the N-th element of pStmt->pColName[] into a string using
66621** xFunc() then return that string.  If N is out of range, return 0.
66622**
66623** There are up to 5 names for each column.  useType determines which
66624** name is returned.  Here are the names:
66625**
66626**    0      The column name as it should be displayed for output
66627**    1      The datatype name for the column
66628**    2      The name of the database that the column derives from
66629**    3      The name of the table that the column derives from
66630**    4      The name of the table column that the result column derives from
66631**
66632** If the result is not a simple column reference (if it is an expression
66633** or a constant) then useTypes 2, 3, and 4 return NULL.
66634*/
66635static const void *columnName(
66636  sqlite3_stmt *pStmt,
66637  int N,
66638  const void *(*xFunc)(Mem*),
66639  int useType
66640){
66641  const void *ret = 0;
66642  Vdbe *p = (Vdbe *)pStmt;
66643  int n;
66644  sqlite3 *db = p->db;
66645
66646  assert( db!=0 );
66647  n = sqlite3_column_count(pStmt);
66648  if( N<n && N>=0 ){
66649    N += useType*n;
66650    sqlite3_mutex_enter(db->mutex);
66651    assert( db->mallocFailed==0 );
66652    ret = xFunc(&p->aColName[N]);
66653     /* A malloc may have failed inside of the xFunc() call. If this
66654    ** is the case, clear the mallocFailed flag and return NULL.
66655    */
66656    if( db->mallocFailed ){
66657      db->mallocFailed = 0;
66658      ret = 0;
66659    }
66660    sqlite3_mutex_leave(db->mutex);
66661  }
66662  return ret;
66663}
66664
66665/*
66666** Return the name of the Nth column of the result set returned by SQL
66667** statement pStmt.
66668*/
66669SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
66670  return columnName(
66671      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
66672}
66673#ifndef SQLITE_OMIT_UTF16
66674SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
66675  return columnName(
66676      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
66677}
66678#endif
66679
66680/*
66681** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
66682** not define OMIT_DECLTYPE.
66683*/
66684#if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
66685# error "Must not define both SQLITE_OMIT_DECLTYPE \
66686         and SQLITE_ENABLE_COLUMN_METADATA"
66687#endif
66688
66689#ifndef SQLITE_OMIT_DECLTYPE
66690/*
66691** Return the column declaration type (if applicable) of the 'i'th column
66692** of the result set of SQL statement pStmt.
66693*/
66694SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
66695  return columnName(
66696      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
66697}
66698#ifndef SQLITE_OMIT_UTF16
66699SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
66700  return columnName(
66701      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
66702}
66703#endif /* SQLITE_OMIT_UTF16 */
66704#endif /* SQLITE_OMIT_DECLTYPE */
66705
66706#ifdef SQLITE_ENABLE_COLUMN_METADATA
66707/*
66708** Return the name of the database from which a result column derives.
66709** NULL is returned if the result column is an expression or constant or
66710** anything else which is not an unabiguous reference to a database column.
66711*/
66712SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
66713  return columnName(
66714      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
66715}
66716#ifndef SQLITE_OMIT_UTF16
66717SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
66718  return columnName(
66719      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
66720}
66721#endif /* SQLITE_OMIT_UTF16 */
66722
66723/*
66724** Return the name of the table from which a result column derives.
66725** NULL is returned if the result column is an expression or constant or
66726** anything else which is not an unabiguous reference to a database column.
66727*/
66728SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
66729  return columnName(
66730      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
66731}
66732#ifndef SQLITE_OMIT_UTF16
66733SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
66734  return columnName(
66735      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
66736}
66737#endif /* SQLITE_OMIT_UTF16 */
66738
66739/*
66740** Return the name of the table column from which a result column derives.
66741** NULL is returned if the result column is an expression or constant or
66742** anything else which is not an unabiguous reference to a database column.
66743*/
66744SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
66745  return columnName(
66746      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
66747}
66748#ifndef SQLITE_OMIT_UTF16
66749SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
66750  return columnName(
66751      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
66752}
66753#endif /* SQLITE_OMIT_UTF16 */
66754#endif /* SQLITE_ENABLE_COLUMN_METADATA */
66755
66756
66757/******************************* sqlite3_bind_  ***************************
66758**
66759** Routines used to attach values to wildcards in a compiled SQL statement.
66760*/
66761/*
66762** Unbind the value bound to variable i in virtual machine p. This is the
66763** the same as binding a NULL value to the column. If the "i" parameter is
66764** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
66765**
66766** A successful evaluation of this routine acquires the mutex on p.
66767** the mutex is released if any kind of error occurs.
66768**
66769** The error code stored in database p->db is overwritten with the return
66770** value in any case.
66771*/
66772static int vdbeUnbind(Vdbe *p, int i){
66773  Mem *pVar;
66774  if( vdbeSafetyNotNull(p) ){
66775    return SQLITE_MISUSE_BKPT;
66776  }
66777  sqlite3_mutex_enter(p->db->mutex);
66778  if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
66779    sqlite3Error(p->db, SQLITE_MISUSE, 0);
66780    sqlite3_mutex_leave(p->db->mutex);
66781    sqlite3_log(SQLITE_MISUSE,
66782        "bind on a busy prepared statement: [%s]", p->zSql);
66783    return SQLITE_MISUSE_BKPT;
66784  }
66785  if( i<1 || i>p->nVar ){
66786    sqlite3Error(p->db, SQLITE_RANGE, 0);
66787    sqlite3_mutex_leave(p->db->mutex);
66788    return SQLITE_RANGE;
66789  }
66790  i--;
66791  pVar = &p->aVar[i];
66792  sqlite3VdbeMemRelease(pVar);
66793  pVar->flags = MEM_Null;
66794  sqlite3Error(p->db, SQLITE_OK, 0);
66795
66796  /* If the bit corresponding to this variable in Vdbe.expmask is set, then
66797  ** binding a new value to this variable invalidates the current query plan.
66798  **
66799  ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
66800  ** parameter in the WHERE clause might influence the choice of query plan
66801  ** for a statement, then the statement will be automatically recompiled,
66802  ** as if there had been a schema change, on the first sqlite3_step() call
66803  ** following any change to the bindings of that parameter.
66804  */
66805  if( p->isPrepareV2 &&
66806     ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
66807  ){
66808    p->expired = 1;
66809  }
66810  return SQLITE_OK;
66811}
66812
66813/*
66814** Bind a text or BLOB value.
66815*/
66816static int bindText(
66817  sqlite3_stmt *pStmt,   /* The statement to bind against */
66818  int i,                 /* Index of the parameter to bind */
66819  const void *zData,     /* Pointer to the data to be bound */
66820  int nData,             /* Number of bytes of data to be bound */
66821  void (*xDel)(void*),   /* Destructor for the data */
66822  u8 encoding            /* Encoding for the data */
66823){
66824  Vdbe *p = (Vdbe *)pStmt;
66825  Mem *pVar;
66826  int rc;
66827
66828  rc = vdbeUnbind(p, i);
66829  if( rc==SQLITE_OK ){
66830    if( zData!=0 ){
66831      pVar = &p->aVar[i-1];
66832      rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
66833      if( rc==SQLITE_OK && encoding!=0 ){
66834        rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
66835      }
66836      sqlite3Error(p->db, rc, 0);
66837      rc = sqlite3ApiExit(p->db, rc);
66838    }
66839    sqlite3_mutex_leave(p->db->mutex);
66840  }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
66841    xDel((void*)zData);
66842  }
66843  return rc;
66844}
66845
66846
66847/*
66848** Bind a blob value to an SQL statement variable.
66849*/
66850SQLITE_API int sqlite3_bind_blob(
66851  sqlite3_stmt *pStmt,
66852  int i,
66853  const void *zData,
66854  int nData,
66855  void (*xDel)(void*)
66856){
66857  return bindText(pStmt, i, zData, nData, xDel, 0);
66858}
66859SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
66860  int rc;
66861  Vdbe *p = (Vdbe *)pStmt;
66862  rc = vdbeUnbind(p, i);
66863  if( rc==SQLITE_OK ){
66864    sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
66865    sqlite3_mutex_leave(p->db->mutex);
66866  }
66867  return rc;
66868}
66869SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
66870  return sqlite3_bind_int64(p, i, (i64)iValue);
66871}
66872SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
66873  int rc;
66874  Vdbe *p = (Vdbe *)pStmt;
66875  rc = vdbeUnbind(p, i);
66876  if( rc==SQLITE_OK ){
66877    sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
66878    sqlite3_mutex_leave(p->db->mutex);
66879  }
66880  return rc;
66881}
66882SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
66883  int rc;
66884  Vdbe *p = (Vdbe*)pStmt;
66885  rc = vdbeUnbind(p, i);
66886  if( rc==SQLITE_OK ){
66887    sqlite3_mutex_leave(p->db->mutex);
66888  }
66889  return rc;
66890}
66891SQLITE_API int sqlite3_bind_text(
66892  sqlite3_stmt *pStmt,
66893  int i,
66894  const char *zData,
66895  int nData,
66896  void (*xDel)(void*)
66897){
66898  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
66899}
66900#ifndef SQLITE_OMIT_UTF16
66901SQLITE_API int sqlite3_bind_text16(
66902  sqlite3_stmt *pStmt,
66903  int i,
66904  const void *zData,
66905  int nData,
66906  void (*xDel)(void*)
66907){
66908  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
66909}
66910#endif /* SQLITE_OMIT_UTF16 */
66911SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
66912  int rc;
66913  switch( sqlite3_value_type((sqlite3_value*)pValue) ){
66914    case SQLITE_INTEGER: {
66915      rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
66916      break;
66917    }
66918    case SQLITE_FLOAT: {
66919      rc = sqlite3_bind_double(pStmt, i, pValue->r);
66920      break;
66921    }
66922    case SQLITE_BLOB: {
66923      if( pValue->flags & MEM_Zero ){
66924        rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
66925      }else{
66926        rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
66927      }
66928      break;
66929    }
66930    case SQLITE_TEXT: {
66931      rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
66932                              pValue->enc);
66933      break;
66934    }
66935    default: {
66936      rc = sqlite3_bind_null(pStmt, i);
66937      break;
66938    }
66939  }
66940  return rc;
66941}
66942SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
66943  int rc;
66944  Vdbe *p = (Vdbe *)pStmt;
66945  rc = vdbeUnbind(p, i);
66946  if( rc==SQLITE_OK ){
66947    sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
66948    sqlite3_mutex_leave(p->db->mutex);
66949  }
66950  return rc;
66951}
66952
66953/*
66954** Return the number of wildcards that can be potentially bound to.
66955** This routine is added to support DBD::SQLite.
66956*/
66957SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
66958  Vdbe *p = (Vdbe*)pStmt;
66959  return p ? p->nVar : 0;
66960}
66961
66962/*
66963** Return the name of a wildcard parameter.  Return NULL if the index
66964** is out of range or if the wildcard is unnamed.
66965**
66966** The result is always UTF-8.
66967*/
66968SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
66969  Vdbe *p = (Vdbe*)pStmt;
66970  if( p==0 || i<1 || i>p->nzVar ){
66971    return 0;
66972  }
66973  return p->azVar[i-1];
66974}
66975
66976/*
66977** Given a wildcard parameter name, return the index of the variable
66978** with that name.  If there is no variable with the given name,
66979** return 0.
66980*/
66981SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
66982  int i;
66983  if( p==0 ){
66984    return 0;
66985  }
66986  if( zName ){
66987    for(i=0; i<p->nzVar; i++){
66988      const char *z = p->azVar[i];
66989      if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
66990        return i+1;
66991      }
66992    }
66993  }
66994  return 0;
66995}
66996SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
66997  return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
66998}
66999
67000/*
67001** Transfer all bindings from the first statement over to the second.
67002*/
67003SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
67004  Vdbe *pFrom = (Vdbe*)pFromStmt;
67005  Vdbe *pTo = (Vdbe*)pToStmt;
67006  int i;
67007  assert( pTo->db==pFrom->db );
67008  assert( pTo->nVar==pFrom->nVar );
67009  sqlite3_mutex_enter(pTo->db->mutex);
67010  for(i=0; i<pFrom->nVar; i++){
67011    sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
67012  }
67013  sqlite3_mutex_leave(pTo->db->mutex);
67014  return SQLITE_OK;
67015}
67016
67017#ifndef SQLITE_OMIT_DEPRECATED
67018/*
67019** Deprecated external interface.  Internal/core SQLite code
67020** should call sqlite3TransferBindings.
67021**
67022** Is is misuse to call this routine with statements from different
67023** database connections.  But as this is a deprecated interface, we
67024** will not bother to check for that condition.
67025**
67026** If the two statements contain a different number of bindings, then
67027** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
67028** SQLITE_OK is returned.
67029*/
67030SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
67031  Vdbe *pFrom = (Vdbe*)pFromStmt;
67032  Vdbe *pTo = (Vdbe*)pToStmt;
67033  if( pFrom->nVar!=pTo->nVar ){
67034    return SQLITE_ERROR;
67035  }
67036  if( pTo->isPrepareV2 && pTo->expmask ){
67037    pTo->expired = 1;
67038  }
67039  if( pFrom->isPrepareV2 && pFrom->expmask ){
67040    pFrom->expired = 1;
67041  }
67042  return sqlite3TransferBindings(pFromStmt, pToStmt);
67043}
67044#endif
67045
67046/*
67047** Return the sqlite3* database handle to which the prepared statement given
67048** in the argument belongs.  This is the same database handle that was
67049** the first argument to the sqlite3_prepare() that was used to create
67050** the statement in the first place.
67051*/
67052SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
67053  return pStmt ? ((Vdbe*)pStmt)->db : 0;
67054}
67055
67056/*
67057** Return true if the prepared statement is guaranteed to not modify the
67058** database.
67059*/
67060SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
67061  return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
67062}
67063
67064/*
67065** Return true if the prepared statement is in need of being reset.
67066*/
67067SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
67068  Vdbe *v = (Vdbe*)pStmt;
67069  return v!=0 && v->pc>0 && v->magic==VDBE_MAGIC_RUN;
67070}
67071
67072/*
67073** Return a pointer to the next prepared statement after pStmt associated
67074** with database connection pDb.  If pStmt is NULL, return the first
67075** prepared statement for the database connection.  Return NULL if there
67076** are no more.
67077*/
67078SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
67079  sqlite3_stmt *pNext;
67080  sqlite3_mutex_enter(pDb->mutex);
67081  if( pStmt==0 ){
67082    pNext = (sqlite3_stmt*)pDb->pVdbe;
67083  }else{
67084    pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
67085  }
67086  sqlite3_mutex_leave(pDb->mutex);
67087  return pNext;
67088}
67089
67090/*
67091** Return the value of a status counter for a prepared statement
67092*/
67093SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
67094  Vdbe *pVdbe = (Vdbe*)pStmt;
67095  u32 v = pVdbe->aCounter[op];
67096  if( resetFlag ) pVdbe->aCounter[op] = 0;
67097  return (int)v;
67098}
67099
67100/************** End of vdbeapi.c *********************************************/
67101/************** Begin file vdbetrace.c ***************************************/
67102/*
67103** 2009 November 25
67104**
67105** The author disclaims copyright to this source code.  In place of
67106** a legal notice, here is a blessing:
67107**
67108**    May you do good and not evil.
67109**    May you find forgiveness for yourself and forgive others.
67110**    May you share freely, never taking more than you give.
67111**
67112*************************************************************************
67113**
67114** This file contains code used to insert the values of host parameters
67115** (aka "wildcards") into the SQL text output by sqlite3_trace().
67116**
67117** The Vdbe parse-tree explainer is also found here.
67118*/
67119
67120#ifndef SQLITE_OMIT_TRACE
67121
67122/*
67123** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
67124** bytes in this text up to but excluding the first character in
67125** a host parameter.  If the text contains no host parameters, return
67126** the total number of bytes in the text.
67127*/
67128static int findNextHostParameter(const char *zSql, int *pnToken){
67129  int tokenType;
67130  int nTotal = 0;
67131  int n;
67132
67133  *pnToken = 0;
67134  while( zSql[0] ){
67135    n = sqlite3GetToken((u8*)zSql, &tokenType);
67136    assert( n>0 && tokenType!=TK_ILLEGAL );
67137    if( tokenType==TK_VARIABLE ){
67138      *pnToken = n;
67139      break;
67140    }
67141    nTotal += n;
67142    zSql += n;
67143  }
67144  return nTotal;
67145}
67146
67147/*
67148** This function returns a pointer to a nul-terminated string in memory
67149** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
67150** string contains a copy of zRawSql but with host parameters expanded to
67151** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
67152** then the returned string holds a copy of zRawSql with "-- " prepended
67153** to each line of text.
67154**
67155** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
67156** then long strings and blobs are truncated to that many bytes.  This
67157** can be used to prevent unreasonably large trace strings when dealing
67158** with large (multi-megabyte) strings and blobs.
67159**
67160** The calling function is responsible for making sure the memory returned
67161** is eventually freed.
67162**
67163** ALGORITHM:  Scan the input string looking for host parameters in any of
67164** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
67165** string literals, quoted identifier names, and comments.  For text forms,
67166** the host parameter index is found by scanning the perpared
67167** statement for the corresponding OP_Variable opcode.  Once the host
67168** parameter index is known, locate the value in p->aVar[].  Then render
67169** the value as a literal in place of the host parameter name.
67170*/
67171SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
67172  Vdbe *p,                 /* The prepared statement being evaluated */
67173  const char *zRawSql      /* Raw text of the SQL statement */
67174){
67175  sqlite3 *db;             /* The database connection */
67176  int idx = 0;             /* Index of a host parameter */
67177  int nextIndex = 1;       /* Index of next ? host parameter */
67178  int n;                   /* Length of a token prefix */
67179  int nToken;              /* Length of the parameter token */
67180  int i;                   /* Loop counter */
67181  Mem *pVar;               /* Value of a host parameter */
67182  StrAccum out;            /* Accumulate the output here */
67183  char zBase[100];         /* Initial working space */
67184
67185  db = p->db;
67186  sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
67187                      db->aLimit[SQLITE_LIMIT_LENGTH]);
67188  out.db = db;
67189  if( db->nVdbeExec>1 ){
67190    while( *zRawSql ){
67191      const char *zStart = zRawSql;
67192      while( *(zRawSql++)!='\n' && *zRawSql );
67193      sqlite3StrAccumAppend(&out, "-- ", 3);
67194      assert( (zRawSql - zStart) > 0 );
67195      sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
67196    }
67197  }else{
67198    while( zRawSql[0] ){
67199      n = findNextHostParameter(zRawSql, &nToken);
67200      assert( n>0 );
67201      sqlite3StrAccumAppend(&out, zRawSql, n);
67202      zRawSql += n;
67203      assert( zRawSql[0] || nToken==0 );
67204      if( nToken==0 ) break;
67205      if( zRawSql[0]=='?' ){
67206        if( nToken>1 ){
67207          assert( sqlite3Isdigit(zRawSql[1]) );
67208          sqlite3GetInt32(&zRawSql[1], &idx);
67209        }else{
67210          idx = nextIndex;
67211        }
67212      }else{
67213        assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
67214        testcase( zRawSql[0]==':' );
67215        testcase( zRawSql[0]=='$' );
67216        testcase( zRawSql[0]=='@' );
67217        idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
67218        assert( idx>0 );
67219      }
67220      zRawSql += nToken;
67221      nextIndex = idx + 1;
67222      assert( idx>0 && idx<=p->nVar );
67223      pVar = &p->aVar[idx-1];
67224      if( pVar->flags & MEM_Null ){
67225        sqlite3StrAccumAppend(&out, "NULL", 4);
67226      }else if( pVar->flags & MEM_Int ){
67227        sqlite3XPrintf(&out, 0, "%lld", pVar->u.i);
67228      }else if( pVar->flags & MEM_Real ){
67229        sqlite3XPrintf(&out, 0, "%!.15g", pVar->r);
67230      }else if( pVar->flags & MEM_Str ){
67231        int nOut;  /* Number of bytes of the string text to include in output */
67232#ifndef SQLITE_OMIT_UTF16
67233        u8 enc = ENC(db);
67234        Mem utf8;
67235        if( enc!=SQLITE_UTF8 ){
67236          memset(&utf8, 0, sizeof(utf8));
67237          utf8.db = db;
67238          sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
67239          sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
67240          pVar = &utf8;
67241        }
67242#endif
67243        nOut = pVar->n;
67244#ifdef SQLITE_TRACE_SIZE_LIMIT
67245        if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
67246          nOut = SQLITE_TRACE_SIZE_LIMIT;
67247          while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
67248        }
67249#endif
67250        sqlite3XPrintf(&out, 0, "'%.*q'", nOut, pVar->z);
67251#ifdef SQLITE_TRACE_SIZE_LIMIT
67252        if( nOut<pVar->n ){
67253          sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
67254        }
67255#endif
67256#ifndef SQLITE_OMIT_UTF16
67257        if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
67258#endif
67259      }else if( pVar->flags & MEM_Zero ){
67260        sqlite3XPrintf(&out, 0, "zeroblob(%d)", pVar->u.nZero);
67261      }else{
67262        int nOut;  /* Number of bytes of the blob to include in output */
67263        assert( pVar->flags & MEM_Blob );
67264        sqlite3StrAccumAppend(&out, "x'", 2);
67265        nOut = pVar->n;
67266#ifdef SQLITE_TRACE_SIZE_LIMIT
67267        if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
67268#endif
67269        for(i=0; i<nOut; i++){
67270          sqlite3XPrintf(&out, 0, "%02x", pVar->z[i]&0xff);
67271        }
67272        sqlite3StrAccumAppend(&out, "'", 1);
67273#ifdef SQLITE_TRACE_SIZE_LIMIT
67274        if( nOut<pVar->n ){
67275          sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
67276        }
67277#endif
67278      }
67279    }
67280  }
67281  return sqlite3StrAccumFinish(&out);
67282}
67283
67284#endif /* #ifndef SQLITE_OMIT_TRACE */
67285
67286/*****************************************************************************
67287** The following code implements the data-structure explaining logic
67288** for the Vdbe.
67289*/
67290
67291#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
67292
67293/*
67294** Allocate a new Explain object
67295*/
67296SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe *pVdbe){
67297  if( pVdbe ){
67298    Explain *p;
67299    sqlite3BeginBenignMalloc();
67300    p = (Explain *)sqlite3MallocZero( sizeof(Explain) );
67301    if( p ){
67302      p->pVdbe = pVdbe;
67303      sqlite3_free(pVdbe->pExplain);
67304      pVdbe->pExplain = p;
67305      sqlite3StrAccumInit(&p->str, p->zBase, sizeof(p->zBase),
67306                          SQLITE_MAX_LENGTH);
67307      p->str.useMalloc = 2;
67308    }else{
67309      sqlite3EndBenignMalloc();
67310    }
67311  }
67312}
67313
67314/*
67315** Return true if the Explain ends with a new-line.
67316*/
67317static int endsWithNL(Explain *p){
67318  return p && p->str.zText && p->str.nChar
67319           && p->str.zText[p->str.nChar-1]=='\n';
67320}
67321
67322/*
67323** Append text to the indentation
67324*/
67325SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe *pVdbe, const char *zFormat, ...){
67326  Explain *p;
67327  if( pVdbe && (p = pVdbe->pExplain)!=0 ){
67328    va_list ap;
67329    if( p->nIndent && endsWithNL(p) ){
67330      int n = p->nIndent;
67331      if( n>ArraySize(p->aIndent) ) n = ArraySize(p->aIndent);
67332      sqlite3AppendSpace(&p->str, p->aIndent[n-1]);
67333    }
67334    va_start(ap, zFormat);
67335    sqlite3VXPrintf(&p->str, SQLITE_PRINTF_INTERNAL, zFormat, ap);
67336    va_end(ap);
67337  }
67338}
67339
67340/*
67341** Append a '\n' if there is not already one.
67342*/
67343SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe *pVdbe){
67344  Explain *p;
67345  if( pVdbe && (p = pVdbe->pExplain)!=0 && !endsWithNL(p) ){
67346    sqlite3StrAccumAppend(&p->str, "\n", 1);
67347  }
67348}
67349
67350/*
67351** Push a new indentation level.  Subsequent lines will be indented
67352** so that they begin at the current cursor position.
67353*/
67354SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe *pVdbe){
67355  Explain *p;
67356  if( pVdbe && (p = pVdbe->pExplain)!=0 ){
67357    if( p->str.zText && p->nIndent<ArraySize(p->aIndent) ){
67358      const char *z = p->str.zText;
67359      int i = p->str.nChar-1;
67360      int x;
67361      while( i>=0 && z[i]!='\n' ){ i--; }
67362      x = (p->str.nChar - 1) - i;
67363      if( p->nIndent && x<p->aIndent[p->nIndent-1] ){
67364        x = p->aIndent[p->nIndent-1];
67365      }
67366      p->aIndent[p->nIndent] = x;
67367    }
67368    p->nIndent++;
67369  }
67370}
67371
67372/*
67373** Pop the indentation stack by one level.
67374*/
67375SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe *p){
67376  if( p && p->pExplain ) p->pExplain->nIndent--;
67377}
67378
67379/*
67380** Free the indentation structure
67381*/
67382SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe *pVdbe){
67383  if( pVdbe && pVdbe->pExplain ){
67384    sqlite3_free(pVdbe->zExplain);
67385    sqlite3ExplainNL(pVdbe);
67386    pVdbe->zExplain = sqlite3StrAccumFinish(&pVdbe->pExplain->str);
67387    sqlite3_free(pVdbe->pExplain);
67388    pVdbe->pExplain = 0;
67389    sqlite3EndBenignMalloc();
67390  }
67391}
67392
67393/*
67394** Return the explanation of a virtual machine.
67395*/
67396SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe *pVdbe){
67397  return (pVdbe && pVdbe->zExplain) ? pVdbe->zExplain : 0;
67398}
67399#endif /* defined(SQLITE_DEBUG) */
67400
67401/************** End of vdbetrace.c *******************************************/
67402/************** Begin file vdbe.c ********************************************/
67403/*
67404** 2001 September 15
67405**
67406** The author disclaims copyright to this source code.  In place of
67407** a legal notice, here is a blessing:
67408**
67409**    May you do good and not evil.
67410**    May you find forgiveness for yourself and forgive others.
67411**    May you share freely, never taking more than you give.
67412**
67413*************************************************************************
67414** The code in this file implements the function that runs the
67415** bytecode of a prepared statement.
67416**
67417** Various scripts scan this source file in order to generate HTML
67418** documentation, headers files, or other derived files.  The formatting
67419** of the code in this file is, therefore, important.  See other comments
67420** in this file for details.  If in doubt, do not deviate from existing
67421** commenting and indentation practices when changing or adding code.
67422*/
67423
67424/*
67425** Invoke this macro on memory cells just prior to changing the
67426** value of the cell.  This macro verifies that shallow copies are
67427** not misused.  A shallow copy of a string or blob just copies a
67428** pointer to the string or blob, not the content.  If the original
67429** is changed while the copy is still in use, the string or blob might
67430** be changed out from under the copy.  This macro verifies that nothing
67431** like that ever happens.
67432*/
67433#ifdef SQLITE_DEBUG
67434# define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
67435#else
67436# define memAboutToChange(P,M)
67437#endif
67438
67439/*
67440** The following global variable is incremented every time a cursor
67441** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
67442** procedures use this information to make sure that indices are
67443** working correctly.  This variable has no function other than to
67444** help verify the correct operation of the library.
67445*/
67446#ifdef SQLITE_TEST
67447SQLITE_API int sqlite3_search_count = 0;
67448#endif
67449
67450/*
67451** When this global variable is positive, it gets decremented once before
67452** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
67453** field of the sqlite3 structure is set in order to simulate an interrupt.
67454**
67455** This facility is used for testing purposes only.  It does not function
67456** in an ordinary build.
67457*/
67458#ifdef SQLITE_TEST
67459SQLITE_API int sqlite3_interrupt_count = 0;
67460#endif
67461
67462/*
67463** The next global variable is incremented each type the OP_Sort opcode
67464** is executed.  The test procedures use this information to make sure that
67465** sorting is occurring or not occurring at appropriate times.   This variable
67466** has no function other than to help verify the correct operation of the
67467** library.
67468*/
67469#ifdef SQLITE_TEST
67470SQLITE_API int sqlite3_sort_count = 0;
67471#endif
67472
67473/*
67474** The next global variable records the size of the largest MEM_Blob
67475** or MEM_Str that has been used by a VDBE opcode.  The test procedures
67476** use this information to make sure that the zero-blob functionality
67477** is working correctly.   This variable has no function other than to
67478** help verify the correct operation of the library.
67479*/
67480#ifdef SQLITE_TEST
67481SQLITE_API int sqlite3_max_blobsize = 0;
67482static void updateMaxBlobsize(Mem *p){
67483  if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
67484    sqlite3_max_blobsize = p->n;
67485  }
67486}
67487#endif
67488
67489/*
67490** The next global variable is incremented each time the OP_Found opcode
67491** is executed. This is used to test whether or not the foreign key
67492** operation implemented using OP_FkIsZero is working. This variable
67493** has no function other than to help verify the correct operation of the
67494** library.
67495*/
67496#ifdef SQLITE_TEST
67497SQLITE_API int sqlite3_found_count = 0;
67498#endif
67499
67500/*
67501** Test a register to see if it exceeds the current maximum blob size.
67502** If it does, record the new maximum blob size.
67503*/
67504#if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
67505# define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
67506#else
67507# define UPDATE_MAX_BLOBSIZE(P)
67508#endif
67509
67510/*
67511** Invoke the VDBE coverage callback, if that callback is defined.  This
67512** feature is used for test suite validation only and does not appear an
67513** production builds.
67514**
67515** M is an integer, 2 or 3, that indices how many different ways the
67516** branch can go.  It is usually 2.  "I" is the direction the branch
67517** goes.  0 means falls through.  1 means branch is taken.  2 means the
67518** second alternative branch is taken.
67519*/
67520#if !defined(SQLITE_VDBE_COVERAGE)
67521# define VdbeBranchTaken(I,M)
67522#else
67523# define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
67524  static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
67525    if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
67526      M = iSrcLine;
67527      /* Assert the truth of VdbeCoverageAlwaysTaken() and
67528      ** VdbeCoverageNeverTaken() */
67529      assert( (M & I)==I );
67530    }else{
67531      if( sqlite3GlobalConfig.xVdbeBranch==0 ) return;  /*NO_TEST*/
67532      sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
67533                                      iSrcLine,I,M);
67534    }
67535  }
67536#endif
67537
67538/*
67539** Convert the given register into a string if it isn't one
67540** already. Return non-zero if a malloc() fails.
67541*/
67542#define Stringify(P, enc) \
67543   if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
67544     { goto no_mem; }
67545
67546/*
67547** An ephemeral string value (signified by the MEM_Ephem flag) contains
67548** a pointer to a dynamically allocated string where some other entity
67549** is responsible for deallocating that string.  Because the register
67550** does not control the string, it might be deleted without the register
67551** knowing it.
67552**
67553** This routine converts an ephemeral string into a dynamically allocated
67554** string that the register itself controls.  In other words, it
67555** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
67556*/
67557#define Deephemeralize(P) \
67558   if( ((P)->flags&MEM_Ephem)!=0 \
67559       && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
67560
67561/* Return true if the cursor was opened using the OP_OpenSorter opcode. */
67562#define isSorter(x) ((x)->pSorter!=0)
67563
67564/*
67565** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
67566** if we run out of memory.
67567*/
67568static VdbeCursor *allocateCursor(
67569  Vdbe *p,              /* The virtual machine */
67570  int iCur,             /* Index of the new VdbeCursor */
67571  int nField,           /* Number of fields in the table or index */
67572  int iDb,              /* Database the cursor belongs to, or -1 */
67573  int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
67574){
67575  /* Find the memory cell that will be used to store the blob of memory
67576  ** required for this VdbeCursor structure. It is convenient to use a
67577  ** vdbe memory cell to manage the memory allocation required for a
67578  ** VdbeCursor structure for the following reasons:
67579  **
67580  **   * Sometimes cursor numbers are used for a couple of different
67581  **     purposes in a vdbe program. The different uses might require
67582  **     different sized allocations. Memory cells provide growable
67583  **     allocations.
67584  **
67585  **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
67586  **     be freed lazily via the sqlite3_release_memory() API. This
67587  **     minimizes the number of malloc calls made by the system.
67588  **
67589  ** Memory cells for cursors are allocated at the top of the address
67590  ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
67591  ** cursor 1 is managed by memory cell (p->nMem-1), etc.
67592  */
67593  Mem *pMem = &p->aMem[p->nMem-iCur];
67594
67595  int nByte;
67596  VdbeCursor *pCx = 0;
67597  nByte =
67598      ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
67599      (isBtreeCursor?sqlite3BtreeCursorSize():0);
67600
67601  assert( iCur<p->nCursor );
67602  if( p->apCsr[iCur] ){
67603    sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
67604    p->apCsr[iCur] = 0;
67605  }
67606  if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
67607    p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
67608    memset(pCx, 0, sizeof(VdbeCursor));
67609    pCx->iDb = iDb;
67610    pCx->nField = nField;
67611    if( isBtreeCursor ){
67612      pCx->pCursor = (BtCursor*)
67613          &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
67614      sqlite3BtreeCursorZero(pCx->pCursor);
67615    }
67616  }
67617  return pCx;
67618}
67619
67620/*
67621** Try to convert a value into a numeric representation if we can
67622** do so without loss of information.  In other words, if the string
67623** looks like a number, convert it into a number.  If it does not
67624** look like a number, leave it alone.
67625*/
67626static void applyNumericAffinity(Mem *pRec){
67627  if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
67628    double rValue;
67629    i64 iValue;
67630    u8 enc = pRec->enc;
67631    if( (pRec->flags&MEM_Str)==0 ) return;
67632    if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
67633    if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
67634      pRec->u.i = iValue;
67635      pRec->flags |= MEM_Int;
67636    }else{
67637      pRec->r = rValue;
67638      pRec->flags |= MEM_Real;
67639    }
67640  }
67641}
67642
67643/*
67644** Processing is determine by the affinity parameter:
67645**
67646** SQLITE_AFF_INTEGER:
67647** SQLITE_AFF_REAL:
67648** SQLITE_AFF_NUMERIC:
67649**    Try to convert pRec to an integer representation or a
67650**    floating-point representation if an integer representation
67651**    is not possible.  Note that the integer representation is
67652**    always preferred, even if the affinity is REAL, because
67653**    an integer representation is more space efficient on disk.
67654**
67655** SQLITE_AFF_TEXT:
67656**    Convert pRec to a text representation.
67657**
67658** SQLITE_AFF_NONE:
67659**    No-op.  pRec is unchanged.
67660*/
67661static void applyAffinity(
67662  Mem *pRec,          /* The value to apply affinity to */
67663  char affinity,      /* The affinity to be applied */
67664  u8 enc              /* Use this text encoding */
67665){
67666  if( affinity==SQLITE_AFF_TEXT ){
67667    /* Only attempt the conversion to TEXT if there is an integer or real
67668    ** representation (blob and NULL do not get converted) but no string
67669    ** representation.
67670    */
67671    if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
67672      sqlite3VdbeMemStringify(pRec, enc);
67673    }
67674    pRec->flags &= ~(MEM_Real|MEM_Int);
67675  }else if( affinity!=SQLITE_AFF_NONE ){
67676    assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
67677             || affinity==SQLITE_AFF_NUMERIC );
67678    applyNumericAffinity(pRec);
67679    if( pRec->flags & MEM_Real ){
67680      sqlite3VdbeIntegerAffinity(pRec);
67681    }
67682  }
67683}
67684
67685/*
67686** Try to convert the type of a function argument or a result column
67687** into a numeric representation.  Use either INTEGER or REAL whichever
67688** is appropriate.  But only do the conversion if it is possible without
67689** loss of information and return the revised type of the argument.
67690*/
67691SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
67692  int eType = sqlite3_value_type(pVal);
67693  if( eType==SQLITE_TEXT ){
67694    Mem *pMem = (Mem*)pVal;
67695    applyNumericAffinity(pMem);
67696    eType = sqlite3_value_type(pVal);
67697  }
67698  return eType;
67699}
67700
67701/*
67702** Exported version of applyAffinity(). This one works on sqlite3_value*,
67703** not the internal Mem* type.
67704*/
67705SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
67706  sqlite3_value *pVal,
67707  u8 affinity,
67708  u8 enc
67709){
67710  applyAffinity((Mem *)pVal, affinity, enc);
67711}
67712
67713/*
67714** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
67715** none.
67716**
67717** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
67718** But it does set pMem->r and pMem->u.i appropriately.
67719*/
67720static u16 numericType(Mem *pMem){
67721  if( pMem->flags & (MEM_Int|MEM_Real) ){
67722    return pMem->flags & (MEM_Int|MEM_Real);
67723  }
67724  if( pMem->flags & (MEM_Str|MEM_Blob) ){
67725    if( sqlite3AtoF(pMem->z, &pMem->r, pMem->n, pMem->enc)==0 ){
67726      return 0;
67727    }
67728    if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){
67729      return MEM_Int;
67730    }
67731    return MEM_Real;
67732  }
67733  return 0;
67734}
67735
67736#ifdef SQLITE_DEBUG
67737/*
67738** Write a nice string representation of the contents of cell pMem
67739** into buffer zBuf, length nBuf.
67740*/
67741SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
67742  char *zCsr = zBuf;
67743  int f = pMem->flags;
67744
67745  static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
67746
67747  if( f&MEM_Blob ){
67748    int i;
67749    char c;
67750    if( f & MEM_Dyn ){
67751      c = 'z';
67752      assert( (f & (MEM_Static|MEM_Ephem))==0 );
67753    }else if( f & MEM_Static ){
67754      c = 't';
67755      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
67756    }else if( f & MEM_Ephem ){
67757      c = 'e';
67758      assert( (f & (MEM_Static|MEM_Dyn))==0 );
67759    }else{
67760      c = 's';
67761    }
67762
67763    sqlite3_snprintf(100, zCsr, "%c", c);
67764    zCsr += sqlite3Strlen30(zCsr);
67765    sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
67766    zCsr += sqlite3Strlen30(zCsr);
67767    for(i=0; i<16 && i<pMem->n; i++){
67768      sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
67769      zCsr += sqlite3Strlen30(zCsr);
67770    }
67771    for(i=0; i<16 && i<pMem->n; i++){
67772      char z = pMem->z[i];
67773      if( z<32 || z>126 ) *zCsr++ = '.';
67774      else *zCsr++ = z;
67775    }
67776
67777    sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
67778    zCsr += sqlite3Strlen30(zCsr);
67779    if( f & MEM_Zero ){
67780      sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
67781      zCsr += sqlite3Strlen30(zCsr);
67782    }
67783    *zCsr = '\0';
67784  }else if( f & MEM_Str ){
67785    int j, k;
67786    zBuf[0] = ' ';
67787    if( f & MEM_Dyn ){
67788      zBuf[1] = 'z';
67789      assert( (f & (MEM_Static|MEM_Ephem))==0 );
67790    }else if( f & MEM_Static ){
67791      zBuf[1] = 't';
67792      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
67793    }else if( f & MEM_Ephem ){
67794      zBuf[1] = 'e';
67795      assert( (f & (MEM_Static|MEM_Dyn))==0 );
67796    }else{
67797      zBuf[1] = 's';
67798    }
67799    k = 2;
67800    sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
67801    k += sqlite3Strlen30(&zBuf[k]);
67802    zBuf[k++] = '[';
67803    for(j=0; j<15 && j<pMem->n; j++){
67804      u8 c = pMem->z[j];
67805      if( c>=0x20 && c<0x7f ){
67806        zBuf[k++] = c;
67807      }else{
67808        zBuf[k++] = '.';
67809      }
67810    }
67811    zBuf[k++] = ']';
67812    sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
67813    k += sqlite3Strlen30(&zBuf[k]);
67814    zBuf[k++] = 0;
67815  }
67816}
67817#endif
67818
67819#ifdef SQLITE_DEBUG
67820/*
67821** Print the value of a register for tracing purposes:
67822*/
67823static void memTracePrint(Mem *p){
67824  if( p->flags & MEM_Undefined ){
67825    printf(" undefined");
67826  }else if( p->flags & MEM_Null ){
67827    printf(" NULL");
67828  }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
67829    printf(" si:%lld", p->u.i);
67830  }else if( p->flags & MEM_Int ){
67831    printf(" i:%lld", p->u.i);
67832#ifndef SQLITE_OMIT_FLOATING_POINT
67833  }else if( p->flags & MEM_Real ){
67834    printf(" r:%g", p->r);
67835#endif
67836  }else if( p->flags & MEM_RowSet ){
67837    printf(" (rowset)");
67838  }else{
67839    char zBuf[200];
67840    sqlite3VdbeMemPrettyPrint(p, zBuf);
67841    printf(" %s", zBuf);
67842  }
67843}
67844static void registerTrace(int iReg, Mem *p){
67845  printf("REG[%d] = ", iReg);
67846  memTracePrint(p);
67847  printf("\n");
67848}
67849#endif
67850
67851#ifdef SQLITE_DEBUG
67852#  define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
67853#else
67854#  define REGISTER_TRACE(R,M)
67855#endif
67856
67857
67858#ifdef VDBE_PROFILE
67859
67860/*
67861** hwtime.h contains inline assembler code for implementing
67862** high-performance timing routines.
67863*/
67864/************** Include hwtime.h in the middle of vdbe.c *********************/
67865/************** Begin file hwtime.h ******************************************/
67866/*
67867** 2008 May 27
67868**
67869** The author disclaims copyright to this source code.  In place of
67870** a legal notice, here is a blessing:
67871**
67872**    May you do good and not evil.
67873**    May you find forgiveness for yourself and forgive others.
67874**    May you share freely, never taking more than you give.
67875**
67876******************************************************************************
67877**
67878** This file contains inline asm code for retrieving "high-performance"
67879** counters for x86 class CPUs.
67880*/
67881#ifndef _HWTIME_H_
67882#define _HWTIME_H_
67883
67884/*
67885** The following routine only works on pentium-class (or newer) processors.
67886** It uses the RDTSC opcode to read the cycle count value out of the
67887** processor and returns that value.  This can be used for high-res
67888** profiling.
67889*/
67890#if (defined(__GNUC__) || defined(_MSC_VER)) && \
67891      (defined(i386) || defined(__i386__) || defined(_M_IX86))
67892
67893  #if defined(__GNUC__)
67894
67895  __inline__ sqlite_uint64 sqlite3Hwtime(void){
67896     unsigned int lo, hi;
67897     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
67898     return (sqlite_uint64)hi << 32 | lo;
67899  }
67900
67901  #elif defined(_MSC_VER)
67902
67903  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
67904     __asm {
67905        rdtsc
67906        ret       ; return value at EDX:EAX
67907     }
67908  }
67909
67910  #endif
67911
67912#elif (defined(__GNUC__) && defined(__x86_64__))
67913
67914  __inline__ sqlite_uint64 sqlite3Hwtime(void){
67915      unsigned long val;
67916      __asm__ __volatile__ ("rdtsc" : "=A" (val));
67917      return val;
67918  }
67919
67920#elif (defined(__GNUC__) && defined(__ppc__))
67921
67922  __inline__ sqlite_uint64 sqlite3Hwtime(void){
67923      unsigned long long retval;
67924      unsigned long junk;
67925      __asm__ __volatile__ ("\n\
67926          1:      mftbu   %1\n\
67927                  mftb    %L0\n\
67928                  mftbu   %0\n\
67929                  cmpw    %0,%1\n\
67930                  bne     1b"
67931                  : "=r" (retval), "=r" (junk));
67932      return retval;
67933  }
67934
67935#else
67936
67937  #error Need implementation of sqlite3Hwtime() for your platform.
67938
67939  /*
67940  ** To compile without implementing sqlite3Hwtime() for your platform,
67941  ** you can remove the above #error and use the following
67942  ** stub function.  You will lose timing support for many
67943  ** of the debugging and testing utilities, but it should at
67944  ** least compile and run.
67945  */
67946SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
67947
67948#endif
67949
67950#endif /* !defined(_HWTIME_H_) */
67951
67952/************** End of hwtime.h **********************************************/
67953/************** Continuing where we left off in vdbe.c ***********************/
67954
67955#endif
67956
67957#ifndef NDEBUG
67958/*
67959** This function is only called from within an assert() expression. It
67960** checks that the sqlite3.nTransaction variable is correctly set to
67961** the number of non-transaction savepoints currently in the
67962** linked list starting at sqlite3.pSavepoint.
67963**
67964** Usage:
67965**
67966**     assert( checkSavepointCount(db) );
67967*/
67968static int checkSavepointCount(sqlite3 *db){
67969  int n = 0;
67970  Savepoint *p;
67971  for(p=db->pSavepoint; p; p=p->pNext) n++;
67972  assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
67973  return 1;
67974}
67975#endif
67976
67977
67978/*
67979** Execute as much of a VDBE program as we can.
67980** This is the core of sqlite3_step().
67981*/
67982SQLITE_PRIVATE int sqlite3VdbeExec(
67983  Vdbe *p                    /* The VDBE */
67984){
67985  int pc=0;                  /* The program counter */
67986  Op *aOp = p->aOp;          /* Copy of p->aOp */
67987  Op *pOp;                   /* Current operation */
67988  int rc = SQLITE_OK;        /* Value to return */
67989  sqlite3 *db = p->db;       /* The database */
67990  u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
67991  u8 encoding = ENC(db);     /* The database encoding */
67992  int iCompare = 0;          /* Result of last OP_Compare operation */
67993  unsigned nVmStep = 0;      /* Number of virtual machine steps */
67994#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
67995  unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
67996#endif
67997  Mem *aMem = p->aMem;       /* Copy of p->aMem */
67998  Mem *pIn1 = 0;             /* 1st input operand */
67999  Mem *pIn2 = 0;             /* 2nd input operand */
68000  Mem *pIn3 = 0;             /* 3rd input operand */
68001  Mem *pOut = 0;             /* Output operand */
68002  int *aPermute = 0;         /* Permutation of columns for OP_Compare */
68003  i64 lastRowid = db->lastRowid;  /* Saved value of the last insert ROWID */
68004#ifdef VDBE_PROFILE
68005  u64 start;                 /* CPU clock count at start of opcode */
68006#endif
68007  /*** INSERT STACK UNION HERE ***/
68008
68009  assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
68010  sqlite3VdbeEnter(p);
68011  if( p->rc==SQLITE_NOMEM ){
68012    /* This happens if a malloc() inside a call to sqlite3_column_text() or
68013    ** sqlite3_column_text16() failed.  */
68014    goto no_mem;
68015  }
68016  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
68017  assert( p->bIsReader || p->readOnly!=0 );
68018  p->rc = SQLITE_OK;
68019  p->iCurrentTime = 0;
68020  assert( p->explain==0 );
68021  p->pResultSet = 0;
68022  db->busyHandler.nBusy = 0;
68023  if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
68024  sqlite3VdbeIOTraceSql(p);
68025#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
68026  if( db->xProgress ){
68027    assert( 0 < db->nProgressOps );
68028    nProgressLimit = (unsigned)p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
68029    if( nProgressLimit==0 ){
68030      nProgressLimit = db->nProgressOps;
68031    }else{
68032      nProgressLimit %= (unsigned)db->nProgressOps;
68033    }
68034  }
68035#endif
68036#ifdef SQLITE_DEBUG
68037  sqlite3BeginBenignMalloc();
68038  if( p->pc==0
68039   && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
68040  ){
68041    int i;
68042    int once = 1;
68043    sqlite3VdbePrintSql(p);
68044    if( p->db->flags & SQLITE_VdbeListing ){
68045      printf("VDBE Program Listing:\n");
68046      for(i=0; i<p->nOp; i++){
68047        sqlite3VdbePrintOp(stdout, i, &aOp[i]);
68048      }
68049    }
68050    if( p->db->flags & SQLITE_VdbeEQP ){
68051      for(i=0; i<p->nOp; i++){
68052        if( aOp[i].opcode==OP_Explain ){
68053          if( once ) printf("VDBE Query Plan:\n");
68054          printf("%s\n", aOp[i].p4.z);
68055          once = 0;
68056        }
68057      }
68058    }
68059    if( p->db->flags & SQLITE_VdbeTrace )  printf("VDBE Trace:\n");
68060  }
68061  sqlite3EndBenignMalloc();
68062#endif
68063  for(pc=p->pc; rc==SQLITE_OK; pc++){
68064    assert( pc>=0 && pc<p->nOp );
68065    if( db->mallocFailed ) goto no_mem;
68066#ifdef VDBE_PROFILE
68067    start = sqlite3Hwtime();
68068#endif
68069    nVmStep++;
68070    pOp = &aOp[pc];
68071
68072    /* Only allow tracing if SQLITE_DEBUG is defined.
68073    */
68074#ifdef SQLITE_DEBUG
68075    if( db->flags & SQLITE_VdbeTrace ){
68076      sqlite3VdbePrintOp(stdout, pc, pOp);
68077    }
68078#endif
68079
68080
68081    /* Check to see if we need to simulate an interrupt.  This only happens
68082    ** if we have a special test build.
68083    */
68084#ifdef SQLITE_TEST
68085    if( sqlite3_interrupt_count>0 ){
68086      sqlite3_interrupt_count--;
68087      if( sqlite3_interrupt_count==0 ){
68088        sqlite3_interrupt(db);
68089      }
68090    }
68091#endif
68092
68093    /* On any opcode with the "out2-prerelease" tag, free any
68094    ** external allocations out of mem[p2] and set mem[p2] to be
68095    ** an undefined integer.  Opcodes will either fill in the integer
68096    ** value or convert mem[p2] to a different type.
68097    */
68098    assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
68099    if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
68100      assert( pOp->p2>0 );
68101      assert( pOp->p2<=(p->nMem-p->nCursor) );
68102      pOut = &aMem[pOp->p2];
68103      memAboutToChange(p, pOut);
68104      VdbeMemRelease(pOut);
68105      pOut->flags = MEM_Int;
68106    }
68107
68108    /* Sanity checking on other operands */
68109#ifdef SQLITE_DEBUG
68110    if( (pOp->opflags & OPFLG_IN1)!=0 ){
68111      assert( pOp->p1>0 );
68112      assert( pOp->p1<=(p->nMem-p->nCursor) );
68113      assert( memIsValid(&aMem[pOp->p1]) );
68114      assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
68115      REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
68116    }
68117    if( (pOp->opflags & OPFLG_IN2)!=0 ){
68118      assert( pOp->p2>0 );
68119      assert( pOp->p2<=(p->nMem-p->nCursor) );
68120      assert( memIsValid(&aMem[pOp->p2]) );
68121      assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
68122      REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
68123    }
68124    if( (pOp->opflags & OPFLG_IN3)!=0 ){
68125      assert( pOp->p3>0 );
68126      assert( pOp->p3<=(p->nMem-p->nCursor) );
68127      assert( memIsValid(&aMem[pOp->p3]) );
68128      assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
68129      REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
68130    }
68131    if( (pOp->opflags & OPFLG_OUT2)!=0 ){
68132      assert( pOp->p2>0 );
68133      assert( pOp->p2<=(p->nMem-p->nCursor) );
68134      memAboutToChange(p, &aMem[pOp->p2]);
68135    }
68136    if( (pOp->opflags & OPFLG_OUT3)!=0 ){
68137      assert( pOp->p3>0 );
68138      assert( pOp->p3<=(p->nMem-p->nCursor) );
68139      memAboutToChange(p, &aMem[pOp->p3]);
68140    }
68141#endif
68142
68143    switch( pOp->opcode ){
68144
68145/*****************************************************************************
68146** What follows is a massive switch statement where each case implements a
68147** separate instruction in the virtual machine.  If we follow the usual
68148** indentation conventions, each case should be indented by 6 spaces.  But
68149** that is a lot of wasted space on the left margin.  So the code within
68150** the switch statement will break with convention and be flush-left. Another
68151** big comment (similar to this one) will mark the point in the code where
68152** we transition back to normal indentation.
68153**
68154** The formatting of each case is important.  The makefile for SQLite
68155** generates two C files "opcodes.h" and "opcodes.c" by scanning this
68156** file looking for lines that begin with "case OP_".  The opcodes.h files
68157** will be filled with #defines that give unique integer values to each
68158** opcode and the opcodes.c file is filled with an array of strings where
68159** each string is the symbolic name for the corresponding opcode.  If the
68160** case statement is followed by a comment of the form "/# same as ... #/"
68161** that comment is used to determine the particular value of the opcode.
68162**
68163** Other keywords in the comment that follows each case are used to
68164** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
68165** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
68166** the mkopcodeh.awk script for additional information.
68167**
68168** Documentation about VDBE opcodes is generated by scanning this file
68169** for lines of that contain "Opcode:".  That line and all subsequent
68170** comment lines are used in the generation of the opcode.html documentation
68171** file.
68172**
68173** SUMMARY:
68174**
68175**     Formatting is important to scripts that scan this file.
68176**     Do not deviate from the formatting style currently in use.
68177**
68178*****************************************************************************/
68179
68180/* Opcode:  Goto * P2 * * *
68181**
68182** An unconditional jump to address P2.
68183** The next instruction executed will be
68184** the one at index P2 from the beginning of
68185** the program.
68186**
68187** The P1 parameter is not actually used by this opcode.  However, it
68188** is sometimes set to 1 instead of 0 as a hint to the command-line shell
68189** that this Goto is the bottom of a loop and that the lines from P2 down
68190** to the current line should be indented for EXPLAIN output.
68191*/
68192case OP_Goto: {             /* jump */
68193  pc = pOp->p2 - 1;
68194
68195  /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
68196  ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
68197  ** completion.  Check to see if sqlite3_interrupt() has been called
68198  ** or if the progress callback needs to be invoked.
68199  **
68200  ** This code uses unstructured "goto" statements and does not look clean.
68201  ** But that is not due to sloppy coding habits. The code is written this
68202  ** way for performance, to avoid having to run the interrupt and progress
68203  ** checks on every opcode.  This helps sqlite3_step() to run about 1.5%
68204  ** faster according to "valgrind --tool=cachegrind" */
68205check_for_interrupt:
68206  if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
68207#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
68208  /* Call the progress callback if it is configured and the required number
68209  ** of VDBE ops have been executed (either since this invocation of
68210  ** sqlite3VdbeExec() or since last time the progress callback was called).
68211  ** If the progress callback returns non-zero, exit the virtual machine with
68212  ** a return code SQLITE_ABORT.
68213  */
68214  if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
68215    assert( db->nProgressOps!=0 );
68216    nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
68217    if( db->xProgress(db->pProgressArg) ){
68218      rc = SQLITE_INTERRUPT;
68219      goto vdbe_error_halt;
68220    }
68221  }
68222#endif
68223
68224  break;
68225}
68226
68227/* Opcode:  Gosub P1 P2 * * *
68228**
68229** Write the current address onto register P1
68230** and then jump to address P2.
68231*/
68232case OP_Gosub: {            /* jump */
68233  assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
68234  pIn1 = &aMem[pOp->p1];
68235  assert( VdbeMemDynamic(pIn1)==0 );
68236  memAboutToChange(p, pIn1);
68237  pIn1->flags = MEM_Int;
68238  pIn1->u.i = pc;
68239  REGISTER_TRACE(pOp->p1, pIn1);
68240  pc = pOp->p2 - 1;
68241  break;
68242}
68243
68244/* Opcode:  Return P1 * * * *
68245**
68246** Jump to the next instruction after the address in register P1.  After
68247** the jump, register P1 becomes undefined.
68248*/
68249case OP_Return: {           /* in1 */
68250  pIn1 = &aMem[pOp->p1];
68251  assert( pIn1->flags==MEM_Int );
68252  pc = (int)pIn1->u.i;
68253  pIn1->flags = MEM_Undefined;
68254  break;
68255}
68256
68257/* Opcode: InitCoroutine P1 P2 P3 * *
68258**
68259** Set up register P1 so that it will OP_Yield to the co-routine
68260** located at address P3.
68261**
68262** If P2!=0 then the co-routine implementation immediately follows
68263** this opcode.  So jump over the co-routine implementation to
68264** address P2.
68265*/
68266case OP_InitCoroutine: {     /* jump */
68267  assert( pOp->p1>0 &&  pOp->p1<=(p->nMem-p->nCursor) );
68268  assert( pOp->p2>=0 && pOp->p2<p->nOp );
68269  assert( pOp->p3>=0 && pOp->p3<p->nOp );
68270  pOut = &aMem[pOp->p1];
68271  assert( !VdbeMemDynamic(pOut) );
68272  pOut->u.i = pOp->p3 - 1;
68273  pOut->flags = MEM_Int;
68274  if( pOp->p2 ) pc = pOp->p2 - 1;
68275  break;
68276}
68277
68278/* Opcode:  EndCoroutine P1 * * * *
68279**
68280** The instruction at the address in register P1 is an OP_Yield.
68281** Jump to the P2 parameter of that OP_Yield.
68282** After the jump, register P1 becomes undefined.
68283*/
68284case OP_EndCoroutine: {           /* in1 */
68285  VdbeOp *pCaller;
68286  pIn1 = &aMem[pOp->p1];
68287  assert( pIn1->flags==MEM_Int );
68288  assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
68289  pCaller = &aOp[pIn1->u.i];
68290  assert( pCaller->opcode==OP_Yield );
68291  assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
68292  pc = pCaller->p2 - 1;
68293  pIn1->flags = MEM_Undefined;
68294  break;
68295}
68296
68297/* Opcode:  Yield P1 P2 * * *
68298**
68299** Swap the program counter with the value in register P1.
68300**
68301** If the co-routine ends with OP_Yield or OP_Return then continue
68302** to the next instruction.  But if the co-routine ends with
68303** OP_EndCoroutine, jump immediately to P2.
68304*/
68305case OP_Yield: {            /* in1, jump */
68306  int pcDest;
68307  pIn1 = &aMem[pOp->p1];
68308  assert( VdbeMemDynamic(pIn1)==0 );
68309  pIn1->flags = MEM_Int;
68310  pcDest = (int)pIn1->u.i;
68311  pIn1->u.i = pc;
68312  REGISTER_TRACE(pOp->p1, pIn1);
68313  pc = pcDest;
68314  break;
68315}
68316
68317/* Opcode:  HaltIfNull  P1 P2 P3 P4 P5
68318** Synopsis:  if r[P3]=null halt
68319**
68320** Check the value in register P3.  If it is NULL then Halt using
68321** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
68322** value in register P3 is not NULL, then this routine is a no-op.
68323** The P5 parameter should be 1.
68324*/
68325case OP_HaltIfNull: {      /* in3 */
68326  pIn3 = &aMem[pOp->p3];
68327  if( (pIn3->flags & MEM_Null)==0 ) break;
68328  /* Fall through into OP_Halt */
68329}
68330
68331/* Opcode:  Halt P1 P2 * P4 P5
68332**
68333** Exit immediately.  All open cursors, etc are closed
68334** automatically.
68335**
68336** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
68337** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
68338** For errors, it can be some other value.  If P1!=0 then P2 will determine
68339** whether or not to rollback the current transaction.  Do not rollback
68340** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
68341** then back out all changes that have occurred during this execution of the
68342** VDBE, but do not rollback the transaction.
68343**
68344** If P4 is not null then it is an error message string.
68345**
68346** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
68347**
68348**    0:  (no change)
68349**    1:  NOT NULL contraint failed: P4
68350**    2:  UNIQUE constraint failed: P4
68351**    3:  CHECK constraint failed: P4
68352**    4:  FOREIGN KEY constraint failed: P4
68353**
68354** If P5 is not zero and P4 is NULL, then everything after the ":" is
68355** omitted.
68356**
68357** There is an implied "Halt 0 0 0" instruction inserted at the very end of
68358** every program.  So a jump past the last instruction of the program
68359** is the same as executing Halt.
68360*/
68361case OP_Halt: {
68362  const char *zType;
68363  const char *zLogFmt;
68364
68365  if( pOp->p1==SQLITE_OK && p->pFrame ){
68366    /* Halt the sub-program. Return control to the parent frame. */
68367    VdbeFrame *pFrame = p->pFrame;
68368    p->pFrame = pFrame->pParent;
68369    p->nFrame--;
68370    sqlite3VdbeSetChanges(db, p->nChange);
68371    pc = sqlite3VdbeFrameRestore(pFrame);
68372    lastRowid = db->lastRowid;
68373    if( pOp->p2==OE_Ignore ){
68374      /* Instruction pc is the OP_Program that invoked the sub-program
68375      ** currently being halted. If the p2 instruction of this OP_Halt
68376      ** instruction is set to OE_Ignore, then the sub-program is throwing
68377      ** an IGNORE exception. In this case jump to the address specified
68378      ** as the p2 of the calling OP_Program.  */
68379      pc = p->aOp[pc].p2-1;
68380    }
68381    aOp = p->aOp;
68382    aMem = p->aMem;
68383    break;
68384  }
68385  p->rc = pOp->p1;
68386  p->errorAction = (u8)pOp->p2;
68387  p->pc = pc;
68388  if( p->rc ){
68389    if( pOp->p5 ){
68390      static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
68391                                             "FOREIGN KEY" };
68392      assert( pOp->p5>=1 && pOp->p5<=4 );
68393      testcase( pOp->p5==1 );
68394      testcase( pOp->p5==2 );
68395      testcase( pOp->p5==3 );
68396      testcase( pOp->p5==4 );
68397      zType = azType[pOp->p5-1];
68398    }else{
68399      zType = 0;
68400    }
68401    assert( zType!=0 || pOp->p4.z!=0 );
68402    zLogFmt = "abort at %d in [%s]: %s";
68403    if( zType && pOp->p4.z ){
68404      sqlite3SetString(&p->zErrMsg, db, "%s constraint failed: %s",
68405                       zType, pOp->p4.z);
68406    }else if( pOp->p4.z ){
68407      sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
68408    }else{
68409      sqlite3SetString(&p->zErrMsg, db, "%s constraint failed", zType);
68410    }
68411    sqlite3_log(pOp->p1, zLogFmt, pc, p->zSql, p->zErrMsg);
68412  }
68413  rc = sqlite3VdbeHalt(p);
68414  assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
68415  if( rc==SQLITE_BUSY ){
68416    p->rc = rc = SQLITE_BUSY;
68417  }else{
68418    assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
68419    assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
68420    rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
68421  }
68422  goto vdbe_return;
68423}
68424
68425/* Opcode: Integer P1 P2 * * *
68426** Synopsis: r[P2]=P1
68427**
68428** The 32-bit integer value P1 is written into register P2.
68429*/
68430case OP_Integer: {         /* out2-prerelease */
68431  pOut->u.i = pOp->p1;
68432  break;
68433}
68434
68435/* Opcode: Int64 * P2 * P4 *
68436** Synopsis: r[P2]=P4
68437**
68438** P4 is a pointer to a 64-bit integer value.
68439** Write that value into register P2.
68440*/
68441case OP_Int64: {           /* out2-prerelease */
68442  assert( pOp->p4.pI64!=0 );
68443  pOut->u.i = *pOp->p4.pI64;
68444  break;
68445}
68446
68447#ifndef SQLITE_OMIT_FLOATING_POINT
68448/* Opcode: Real * P2 * P4 *
68449** Synopsis: r[P2]=P4
68450**
68451** P4 is a pointer to a 64-bit floating point value.
68452** Write that value into register P2.
68453*/
68454case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
68455  pOut->flags = MEM_Real;
68456  assert( !sqlite3IsNaN(*pOp->p4.pReal) );
68457  pOut->r = *pOp->p4.pReal;
68458  break;
68459}
68460#endif
68461
68462/* Opcode: String8 * P2 * P4 *
68463** Synopsis: r[P2]='P4'
68464**
68465** P4 points to a nul terminated UTF-8 string. This opcode is transformed
68466** into an OP_String before it is executed for the first time.  During
68467** this transformation, the length of string P4 is computed and stored
68468** as the P1 parameter.
68469*/
68470case OP_String8: {         /* same as TK_STRING, out2-prerelease */
68471  assert( pOp->p4.z!=0 );
68472  pOp->opcode = OP_String;
68473  pOp->p1 = sqlite3Strlen30(pOp->p4.z);
68474
68475#ifndef SQLITE_OMIT_UTF16
68476  if( encoding!=SQLITE_UTF8 ){
68477    rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
68478    if( rc==SQLITE_TOOBIG ) goto too_big;
68479    if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
68480    assert( pOut->zMalloc==pOut->z );
68481    assert( VdbeMemDynamic(pOut)==0 );
68482    pOut->zMalloc = 0;
68483    pOut->flags |= MEM_Static;
68484    if( pOp->p4type==P4_DYNAMIC ){
68485      sqlite3DbFree(db, pOp->p4.z);
68486    }
68487    pOp->p4type = P4_DYNAMIC;
68488    pOp->p4.z = pOut->z;
68489    pOp->p1 = pOut->n;
68490  }
68491#endif
68492  if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
68493    goto too_big;
68494  }
68495  /* Fall through to the next case, OP_String */
68496}
68497
68498/* Opcode: String P1 P2 * P4 *
68499** Synopsis: r[P2]='P4' (len=P1)
68500**
68501** The string value P4 of length P1 (bytes) is stored in register P2.
68502*/
68503case OP_String: {          /* out2-prerelease */
68504  assert( pOp->p4.z!=0 );
68505  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
68506  pOut->z = pOp->p4.z;
68507  pOut->n = pOp->p1;
68508  pOut->enc = encoding;
68509  UPDATE_MAX_BLOBSIZE(pOut);
68510  break;
68511}
68512
68513/* Opcode: Null P1 P2 P3 * *
68514** Synopsis:  r[P2..P3]=NULL
68515**
68516** Write a NULL into registers P2.  If P3 greater than P2, then also write
68517** NULL into register P3 and every register in between P2 and P3.  If P3
68518** is less than P2 (typically P3 is zero) then only register P2 is
68519** set to NULL.
68520**
68521** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
68522** NULL values will not compare equal even if SQLITE_NULLEQ is set on
68523** OP_Ne or OP_Eq.
68524*/
68525case OP_Null: {           /* out2-prerelease */
68526  int cnt;
68527  u16 nullFlag;
68528  cnt = pOp->p3-pOp->p2;
68529  assert( pOp->p3<=(p->nMem-p->nCursor) );
68530  pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
68531  while( cnt>0 ){
68532    pOut++;
68533    memAboutToChange(p, pOut);
68534    VdbeMemRelease(pOut);
68535    pOut->flags = nullFlag;
68536    cnt--;
68537  }
68538  break;
68539}
68540
68541/* Opcode: SoftNull P1 * * * *
68542** Synopsis:  r[P1]=NULL
68543**
68544** Set register P1 to have the value NULL as seen by the OP_MakeRecord
68545** instruction, but do not free any string or blob memory associated with
68546** the register, so that if the value was a string or blob that was
68547** previously copied using OP_SCopy, the copies will continue to be valid.
68548*/
68549case OP_SoftNull: {
68550  assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
68551  pOut = &aMem[pOp->p1];
68552  pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined;
68553  break;
68554}
68555
68556/* Opcode: Blob P1 P2 * P4 *
68557** Synopsis: r[P2]=P4 (len=P1)
68558**
68559** P4 points to a blob of data P1 bytes long.  Store this
68560** blob in register P2.
68561*/
68562case OP_Blob: {                /* out2-prerelease */
68563  assert( pOp->p1 <= SQLITE_MAX_LENGTH );
68564  sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
68565  pOut->enc = encoding;
68566  UPDATE_MAX_BLOBSIZE(pOut);
68567  break;
68568}
68569
68570/* Opcode: Variable P1 P2 * P4 *
68571** Synopsis: r[P2]=parameter(P1,P4)
68572**
68573** Transfer the values of bound parameter P1 into register P2
68574**
68575** If the parameter is named, then its name appears in P4.
68576** The P4 value is used by sqlite3_bind_parameter_name().
68577*/
68578case OP_Variable: {            /* out2-prerelease */
68579  Mem *pVar;       /* Value being transferred */
68580
68581  assert( pOp->p1>0 && pOp->p1<=p->nVar );
68582  assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
68583  pVar = &p->aVar[pOp->p1 - 1];
68584  if( sqlite3VdbeMemTooBig(pVar) ){
68585    goto too_big;
68586  }
68587  sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
68588  UPDATE_MAX_BLOBSIZE(pOut);
68589  break;
68590}
68591
68592/* Opcode: Move P1 P2 P3 * *
68593** Synopsis:  r[P2@P3]=r[P1@P3]
68594**
68595** Move the P3 values in register P1..P1+P3-1 over into
68596** registers P2..P2+P3-1.  Registers P1..P1+P3-1 are
68597** left holding a NULL.  It is an error for register ranges
68598** P1..P1+P3-1 and P2..P2+P3-1 to overlap.  It is an error
68599** for P3 to be less than 1.
68600*/
68601case OP_Move: {
68602  char *zMalloc;   /* Holding variable for allocated memory */
68603  int n;           /* Number of registers left to copy */
68604  int p1;          /* Register to copy from */
68605  int p2;          /* Register to copy to */
68606
68607  n = pOp->p3;
68608  p1 = pOp->p1;
68609  p2 = pOp->p2;
68610  assert( n>0 && p1>0 && p2>0 );
68611  assert( p1+n<=p2 || p2+n<=p1 );
68612
68613  pIn1 = &aMem[p1];
68614  pOut = &aMem[p2];
68615  do{
68616    assert( pOut<=&aMem[(p->nMem-p->nCursor)] );
68617    assert( pIn1<=&aMem[(p->nMem-p->nCursor)] );
68618    assert( memIsValid(pIn1) );
68619    memAboutToChange(p, pOut);
68620    VdbeMemRelease(pOut);
68621    zMalloc = pOut->zMalloc;
68622    memcpy(pOut, pIn1, sizeof(Mem));
68623#ifdef SQLITE_DEBUG
68624    if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<&aMem[p1+pOp->p3] ){
68625      pOut->pScopyFrom += p1 - pOp->p2;
68626    }
68627#endif
68628    pIn1->flags = MEM_Undefined;
68629    pIn1->xDel = 0;
68630    pIn1->zMalloc = zMalloc;
68631    REGISTER_TRACE(p2++, pOut);
68632    pIn1++;
68633    pOut++;
68634  }while( --n );
68635  break;
68636}
68637
68638/* Opcode: Copy P1 P2 P3 * *
68639** Synopsis: r[P2@P3+1]=r[P1@P3+1]
68640**
68641** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
68642**
68643** This instruction makes a deep copy of the value.  A duplicate
68644** is made of any string or blob constant.  See also OP_SCopy.
68645*/
68646case OP_Copy: {
68647  int n;
68648
68649  n = pOp->p3;
68650  pIn1 = &aMem[pOp->p1];
68651  pOut = &aMem[pOp->p2];
68652  assert( pOut!=pIn1 );
68653  while( 1 ){
68654    sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
68655    Deephemeralize(pOut);
68656#ifdef SQLITE_DEBUG
68657    pOut->pScopyFrom = 0;
68658#endif
68659    REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
68660    if( (n--)==0 ) break;
68661    pOut++;
68662    pIn1++;
68663  }
68664  break;
68665}
68666
68667/* Opcode: SCopy P1 P2 * * *
68668** Synopsis: r[P2]=r[P1]
68669**
68670** Make a shallow copy of register P1 into register P2.
68671**
68672** This instruction makes a shallow copy of the value.  If the value
68673** is a string or blob, then the copy is only a pointer to the
68674** original and hence if the original changes so will the copy.
68675** Worse, if the original is deallocated, the copy becomes invalid.
68676** Thus the program must guarantee that the original will not change
68677** during the lifetime of the copy.  Use OP_Copy to make a complete
68678** copy.
68679*/
68680case OP_SCopy: {            /* out2 */
68681  pIn1 = &aMem[pOp->p1];
68682  pOut = &aMem[pOp->p2];
68683  assert( pOut!=pIn1 );
68684  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
68685#ifdef SQLITE_DEBUG
68686  if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
68687#endif
68688  break;
68689}
68690
68691/* Opcode: ResultRow P1 P2 * * *
68692** Synopsis:  output=r[P1@P2]
68693**
68694** The registers P1 through P1+P2-1 contain a single row of
68695** results. This opcode causes the sqlite3_step() call to terminate
68696** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
68697** structure to provide access to the r(P1)..r(P1+P2-1) values as
68698** the result row.
68699*/
68700case OP_ResultRow: {
68701  Mem *pMem;
68702  int i;
68703  assert( p->nResColumn==pOp->p2 );
68704  assert( pOp->p1>0 );
68705  assert( pOp->p1+pOp->p2<=(p->nMem-p->nCursor)+1 );
68706
68707#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
68708  /* Run the progress counter just before returning.
68709  */
68710  if( db->xProgress!=0
68711   && nVmStep>=nProgressLimit
68712   && db->xProgress(db->pProgressArg)!=0
68713  ){
68714    rc = SQLITE_INTERRUPT;
68715    goto vdbe_error_halt;
68716  }
68717#endif
68718
68719  /* If this statement has violated immediate foreign key constraints, do
68720  ** not return the number of rows modified. And do not RELEASE the statement
68721  ** transaction. It needs to be rolled back.  */
68722  if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
68723    assert( db->flags&SQLITE_CountRows );
68724    assert( p->usesStmtJournal );
68725    break;
68726  }
68727
68728  /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
68729  ** DML statements invoke this opcode to return the number of rows
68730  ** modified to the user. This is the only way that a VM that
68731  ** opens a statement transaction may invoke this opcode.
68732  **
68733  ** In case this is such a statement, close any statement transaction
68734  ** opened by this VM before returning control to the user. This is to
68735  ** ensure that statement-transactions are always nested, not overlapping.
68736  ** If the open statement-transaction is not closed here, then the user
68737  ** may step another VM that opens its own statement transaction. This
68738  ** may lead to overlapping statement transactions.
68739  **
68740  ** The statement transaction is never a top-level transaction.  Hence
68741  ** the RELEASE call below can never fail.
68742  */
68743  assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
68744  rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
68745  if( NEVER(rc!=SQLITE_OK) ){
68746    break;
68747  }
68748
68749  /* Invalidate all ephemeral cursor row caches */
68750  p->cacheCtr = (p->cacheCtr + 2)|1;
68751
68752  /* Make sure the results of the current row are \000 terminated
68753  ** and have an assigned type.  The results are de-ephemeralized as
68754  ** a side effect.
68755  */
68756  pMem = p->pResultSet = &aMem[pOp->p1];
68757  for(i=0; i<pOp->p2; i++){
68758    assert( memIsValid(&pMem[i]) );
68759    Deephemeralize(&pMem[i]);
68760    assert( (pMem[i].flags & MEM_Ephem)==0
68761            || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
68762    sqlite3VdbeMemNulTerminate(&pMem[i]);
68763    REGISTER_TRACE(pOp->p1+i, &pMem[i]);
68764  }
68765  if( db->mallocFailed ) goto no_mem;
68766
68767  /* Return SQLITE_ROW
68768  */
68769  p->pc = pc + 1;
68770  rc = SQLITE_ROW;
68771  goto vdbe_return;
68772}
68773
68774/* Opcode: Concat P1 P2 P3 * *
68775** Synopsis: r[P3]=r[P2]+r[P1]
68776**
68777** Add the text in register P1 onto the end of the text in
68778** register P2 and store the result in register P3.
68779** If either the P1 or P2 text are NULL then store NULL in P3.
68780**
68781**   P3 = P2 || P1
68782**
68783** It is illegal for P1 and P3 to be the same register. Sometimes,
68784** if P3 is the same register as P2, the implementation is able
68785** to avoid a memcpy().
68786*/
68787case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
68788  i64 nByte;
68789
68790  pIn1 = &aMem[pOp->p1];
68791  pIn2 = &aMem[pOp->p2];
68792  pOut = &aMem[pOp->p3];
68793  assert( pIn1!=pOut );
68794  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
68795    sqlite3VdbeMemSetNull(pOut);
68796    break;
68797  }
68798  if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
68799  Stringify(pIn1, encoding);
68800  Stringify(pIn2, encoding);
68801  nByte = pIn1->n + pIn2->n;
68802  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
68803    goto too_big;
68804  }
68805  if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
68806    goto no_mem;
68807  }
68808  MemSetTypeFlag(pOut, MEM_Str);
68809  if( pOut!=pIn2 ){
68810    memcpy(pOut->z, pIn2->z, pIn2->n);
68811  }
68812  memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
68813  pOut->z[nByte]=0;
68814  pOut->z[nByte+1] = 0;
68815  pOut->flags |= MEM_Term;
68816  pOut->n = (int)nByte;
68817  pOut->enc = encoding;
68818  UPDATE_MAX_BLOBSIZE(pOut);
68819  break;
68820}
68821
68822/* Opcode: Add P1 P2 P3 * *
68823** Synopsis:  r[P3]=r[P1]+r[P2]
68824**
68825** Add the value in register P1 to the value in register P2
68826** and store the result in register P3.
68827** If either input is NULL, the result is NULL.
68828*/
68829/* Opcode: Multiply P1 P2 P3 * *
68830** Synopsis:  r[P3]=r[P1]*r[P2]
68831**
68832**
68833** Multiply the value in register P1 by the value in register P2
68834** and store the result in register P3.
68835** If either input is NULL, the result is NULL.
68836*/
68837/* Opcode: Subtract P1 P2 P3 * *
68838** Synopsis:  r[P3]=r[P2]-r[P1]
68839**
68840** Subtract the value in register P1 from the value in register P2
68841** and store the result in register P3.
68842** If either input is NULL, the result is NULL.
68843*/
68844/* Opcode: Divide P1 P2 P3 * *
68845** Synopsis:  r[P3]=r[P2]/r[P1]
68846**
68847** Divide the value in register P1 by the value in register P2
68848** and store the result in register P3 (P3=P2/P1). If the value in
68849** register P1 is zero, then the result is NULL. If either input is
68850** NULL, the result is NULL.
68851*/
68852/* Opcode: Remainder P1 P2 P3 * *
68853** Synopsis:  r[P3]=r[P2]%r[P1]
68854**
68855** Compute the remainder after integer register P2 is divided by
68856** register P1 and store the result in register P3.
68857** If the value in register P1 is zero the result is NULL.
68858** If either operand is NULL, the result is NULL.
68859*/
68860case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
68861case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
68862case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
68863case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
68864case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
68865  char bIntint;   /* Started out as two integer operands */
68866  u16 flags;      /* Combined MEM_* flags from both inputs */
68867  u16 type1;      /* Numeric type of left operand */
68868  u16 type2;      /* Numeric type of right operand */
68869  i64 iA;         /* Integer value of left operand */
68870  i64 iB;         /* Integer value of right operand */
68871  double rA;      /* Real value of left operand */
68872  double rB;      /* Real value of right operand */
68873
68874  pIn1 = &aMem[pOp->p1];
68875  type1 = numericType(pIn1);
68876  pIn2 = &aMem[pOp->p2];
68877  type2 = numericType(pIn2);
68878  pOut = &aMem[pOp->p3];
68879  flags = pIn1->flags | pIn2->flags;
68880  if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
68881  if( (type1 & type2 & MEM_Int)!=0 ){
68882    iA = pIn1->u.i;
68883    iB = pIn2->u.i;
68884    bIntint = 1;
68885    switch( pOp->opcode ){
68886      case OP_Add:       if( sqlite3AddInt64(&iB,iA) ) goto fp_math;  break;
68887      case OP_Subtract:  if( sqlite3SubInt64(&iB,iA) ) goto fp_math;  break;
68888      case OP_Multiply:  if( sqlite3MulInt64(&iB,iA) ) goto fp_math;  break;
68889      case OP_Divide: {
68890        if( iA==0 ) goto arithmetic_result_is_null;
68891        if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
68892        iB /= iA;
68893        break;
68894      }
68895      default: {
68896        if( iA==0 ) goto arithmetic_result_is_null;
68897        if( iA==-1 ) iA = 1;
68898        iB %= iA;
68899        break;
68900      }
68901    }
68902    pOut->u.i = iB;
68903    MemSetTypeFlag(pOut, MEM_Int);
68904  }else{
68905    bIntint = 0;
68906fp_math:
68907    rA = sqlite3VdbeRealValue(pIn1);
68908    rB = sqlite3VdbeRealValue(pIn2);
68909    switch( pOp->opcode ){
68910      case OP_Add:         rB += rA;       break;
68911      case OP_Subtract:    rB -= rA;       break;
68912      case OP_Multiply:    rB *= rA;       break;
68913      case OP_Divide: {
68914        /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
68915        if( rA==(double)0 ) goto arithmetic_result_is_null;
68916        rB /= rA;
68917        break;
68918      }
68919      default: {
68920        iA = (i64)rA;
68921        iB = (i64)rB;
68922        if( iA==0 ) goto arithmetic_result_is_null;
68923        if( iA==-1 ) iA = 1;
68924        rB = (double)(iB % iA);
68925        break;
68926      }
68927    }
68928#ifdef SQLITE_OMIT_FLOATING_POINT
68929    pOut->u.i = rB;
68930    MemSetTypeFlag(pOut, MEM_Int);
68931#else
68932    if( sqlite3IsNaN(rB) ){
68933      goto arithmetic_result_is_null;
68934    }
68935    pOut->r = rB;
68936    MemSetTypeFlag(pOut, MEM_Real);
68937    if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
68938      sqlite3VdbeIntegerAffinity(pOut);
68939    }
68940#endif
68941  }
68942  break;
68943
68944arithmetic_result_is_null:
68945  sqlite3VdbeMemSetNull(pOut);
68946  break;
68947}
68948
68949/* Opcode: CollSeq P1 * * P4
68950**
68951** P4 is a pointer to a CollSeq struct. If the next call to a user function
68952** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
68953** be returned. This is used by the built-in min(), max() and nullif()
68954** functions.
68955**
68956** If P1 is not zero, then it is a register that a subsequent min() or
68957** max() aggregate will set to 1 if the current row is not the minimum or
68958** maximum.  The P1 register is initialized to 0 by this instruction.
68959**
68960** The interface used by the implementation of the aforementioned functions
68961** to retrieve the collation sequence set by this opcode is not available
68962** publicly, only to user functions defined in func.c.
68963*/
68964case OP_CollSeq: {
68965  assert( pOp->p4type==P4_COLLSEQ );
68966  if( pOp->p1 ){
68967    sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
68968  }
68969  break;
68970}
68971
68972/* Opcode: Function P1 P2 P3 P4 P5
68973** Synopsis: r[P3]=func(r[P2@P5])
68974**
68975** Invoke a user function (P4 is a pointer to a Function structure that
68976** defines the function) with P5 arguments taken from register P2 and
68977** successors.  The result of the function is stored in register P3.
68978** Register P3 must not be one of the function inputs.
68979**
68980** P1 is a 32-bit bitmask indicating whether or not each argument to the
68981** function was determined to be constant at compile time. If the first
68982** argument was constant then bit 0 of P1 is set. This is used to determine
68983** whether meta data associated with a user function argument using the
68984** sqlite3_set_auxdata() API may be safely retained until the next
68985** invocation of this opcode.
68986**
68987** See also: AggStep and AggFinal
68988*/
68989case OP_Function: {
68990  int i;
68991  Mem *pArg;
68992  sqlite3_context ctx;
68993  sqlite3_value **apVal;
68994  int n;
68995
68996  n = pOp->p5;
68997  apVal = p->apArg;
68998  assert( apVal || n==0 );
68999  assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
69000  pOut = &aMem[pOp->p3];
69001  memAboutToChange(p, pOut);
69002
69003  assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem-p->nCursor)+1) );
69004  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
69005  pArg = &aMem[pOp->p2];
69006  for(i=0; i<n; i++, pArg++){
69007    assert( memIsValid(pArg) );
69008    apVal[i] = pArg;
69009    Deephemeralize(pArg);
69010    REGISTER_TRACE(pOp->p2+i, pArg);
69011  }
69012
69013  assert( pOp->p4type==P4_FUNCDEF );
69014  ctx.pFunc = pOp->p4.pFunc;
69015  ctx.iOp = pc;
69016  ctx.pVdbe = p;
69017
69018  /* The output cell may already have a buffer allocated. Move
69019  ** the pointer to ctx.s so in case the user-function can use
69020  ** the already allocated buffer instead of allocating a new one.
69021  */
69022  memcpy(&ctx.s, pOut, sizeof(Mem));
69023  pOut->flags = MEM_Null;
69024  pOut->xDel = 0;
69025  pOut->zMalloc = 0;
69026  MemSetTypeFlag(&ctx.s, MEM_Null);
69027
69028  ctx.fErrorOrAux = 0;
69029  if( ctx.pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
69030    assert( pOp>aOp );
69031    assert( pOp[-1].p4type==P4_COLLSEQ );
69032    assert( pOp[-1].opcode==OP_CollSeq );
69033    ctx.pColl = pOp[-1].p4.pColl;
69034  }
69035  db->lastRowid = lastRowid;
69036  (*ctx.pFunc->xFunc)(&ctx, n, apVal); /* IMP: R-24505-23230 */
69037  lastRowid = db->lastRowid;
69038
69039  if( db->mallocFailed ){
69040    /* Even though a malloc() has failed, the implementation of the
69041    ** user function may have called an sqlite3_result_XXX() function
69042    ** to return a value. The following call releases any resources
69043    ** associated with such a value.
69044    */
69045    sqlite3VdbeMemRelease(&ctx.s);
69046    goto no_mem;
69047  }
69048
69049  /* If the function returned an error, throw an exception */
69050  if( ctx.fErrorOrAux ){
69051    if( ctx.isError ){
69052      sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s));
69053      rc = ctx.isError;
69054    }
69055    sqlite3VdbeDeleteAuxData(p, pc, pOp->p1);
69056  }
69057
69058  /* Copy the result of the function into register P3 */
69059  sqlite3VdbeChangeEncoding(&ctx.s, encoding);
69060  assert( pOut->flags==MEM_Null );
69061  memcpy(pOut, &ctx.s, sizeof(Mem));
69062  if( sqlite3VdbeMemTooBig(pOut) ){
69063    goto too_big;
69064  }
69065
69066#if 0
69067  /* The app-defined function has done something that as caused this
69068  ** statement to expire.  (Perhaps the function called sqlite3_exec()
69069  ** with a CREATE TABLE statement.)
69070  */
69071  if( p->expired ) rc = SQLITE_ABORT;
69072#endif
69073
69074  REGISTER_TRACE(pOp->p3, pOut);
69075  UPDATE_MAX_BLOBSIZE(pOut);
69076  break;
69077}
69078
69079/* Opcode: BitAnd P1 P2 P3 * *
69080** Synopsis:  r[P3]=r[P1]&r[P2]
69081**
69082** Take the bit-wise AND of the values in register P1 and P2 and
69083** store the result in register P3.
69084** If either input is NULL, the result is NULL.
69085*/
69086/* Opcode: BitOr P1 P2 P3 * *
69087** Synopsis:  r[P3]=r[P1]|r[P2]
69088**
69089** Take the bit-wise OR of the values in register P1 and P2 and
69090** store the result in register P3.
69091** If either input is NULL, the result is NULL.
69092*/
69093/* Opcode: ShiftLeft P1 P2 P3 * *
69094** Synopsis:  r[P3]=r[P2]<<r[P1]
69095**
69096** Shift the integer value in register P2 to the left by the
69097** number of bits specified by the integer in register P1.
69098** Store the result in register P3.
69099** If either input is NULL, the result is NULL.
69100*/
69101/* Opcode: ShiftRight P1 P2 P3 * *
69102** Synopsis:  r[P3]=r[P2]>>r[P1]
69103**
69104** Shift the integer value in register P2 to the right by the
69105** number of bits specified by the integer in register P1.
69106** Store the result in register P3.
69107** If either input is NULL, the result is NULL.
69108*/
69109case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
69110case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
69111case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
69112case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
69113  i64 iA;
69114  u64 uA;
69115  i64 iB;
69116  u8 op;
69117
69118  pIn1 = &aMem[pOp->p1];
69119  pIn2 = &aMem[pOp->p2];
69120  pOut = &aMem[pOp->p3];
69121  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
69122    sqlite3VdbeMemSetNull(pOut);
69123    break;
69124  }
69125  iA = sqlite3VdbeIntValue(pIn2);
69126  iB = sqlite3VdbeIntValue(pIn1);
69127  op = pOp->opcode;
69128  if( op==OP_BitAnd ){
69129    iA &= iB;
69130  }else if( op==OP_BitOr ){
69131    iA |= iB;
69132  }else if( iB!=0 ){
69133    assert( op==OP_ShiftRight || op==OP_ShiftLeft );
69134
69135    /* If shifting by a negative amount, shift in the other direction */
69136    if( iB<0 ){
69137      assert( OP_ShiftRight==OP_ShiftLeft+1 );
69138      op = 2*OP_ShiftLeft + 1 - op;
69139      iB = iB>(-64) ? -iB : 64;
69140    }
69141
69142    if( iB>=64 ){
69143      iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
69144    }else{
69145      memcpy(&uA, &iA, sizeof(uA));
69146      if( op==OP_ShiftLeft ){
69147        uA <<= iB;
69148      }else{
69149        uA >>= iB;
69150        /* Sign-extend on a right shift of a negative number */
69151        if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
69152      }
69153      memcpy(&iA, &uA, sizeof(iA));
69154    }
69155  }
69156  pOut->u.i = iA;
69157  MemSetTypeFlag(pOut, MEM_Int);
69158  break;
69159}
69160
69161/* Opcode: AddImm  P1 P2 * * *
69162** Synopsis:  r[P1]=r[P1]+P2
69163**
69164** Add the constant P2 to the value in register P1.
69165** The result is always an integer.
69166**
69167** To force any register to be an integer, just add 0.
69168*/
69169case OP_AddImm: {            /* in1 */
69170  pIn1 = &aMem[pOp->p1];
69171  memAboutToChange(p, pIn1);
69172  sqlite3VdbeMemIntegerify(pIn1);
69173  pIn1->u.i += pOp->p2;
69174  break;
69175}
69176
69177/* Opcode: MustBeInt P1 P2 * * *
69178**
69179** Force the value in register P1 to be an integer.  If the value
69180** in P1 is not an integer and cannot be converted into an integer
69181** without data loss, then jump immediately to P2, or if P2==0
69182** raise an SQLITE_MISMATCH exception.
69183*/
69184case OP_MustBeInt: {            /* jump, in1 */
69185  pIn1 = &aMem[pOp->p1];
69186  if( (pIn1->flags & MEM_Int)==0 ){
69187    applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
69188    VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
69189    if( (pIn1->flags & MEM_Int)==0 ){
69190      if( pOp->p2==0 ){
69191        rc = SQLITE_MISMATCH;
69192        goto abort_due_to_error;
69193      }else{
69194        pc = pOp->p2 - 1;
69195        break;
69196      }
69197    }
69198  }
69199  MemSetTypeFlag(pIn1, MEM_Int);
69200  break;
69201}
69202
69203#ifndef SQLITE_OMIT_FLOATING_POINT
69204/* Opcode: RealAffinity P1 * * * *
69205**
69206** If register P1 holds an integer convert it to a real value.
69207**
69208** This opcode is used when extracting information from a column that
69209** has REAL affinity.  Such column values may still be stored as
69210** integers, for space efficiency, but after extraction we want them
69211** to have only a real value.
69212*/
69213case OP_RealAffinity: {                  /* in1 */
69214  pIn1 = &aMem[pOp->p1];
69215  if( pIn1->flags & MEM_Int ){
69216    sqlite3VdbeMemRealify(pIn1);
69217  }
69218  break;
69219}
69220#endif
69221
69222#ifndef SQLITE_OMIT_CAST
69223/* Opcode: ToText P1 * * * *
69224**
69225** Force the value in register P1 to be text.
69226** If the value is numeric, convert it to a string using the
69227** equivalent of sprintf().  Blob values are unchanged and
69228** are afterwards simply interpreted as text.
69229**
69230** A NULL value is not changed by this routine.  It remains NULL.
69231*/
69232case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
69233  pIn1 = &aMem[pOp->p1];
69234  memAboutToChange(p, pIn1);
69235  if( pIn1->flags & MEM_Null ) break;
69236  assert( MEM_Str==(MEM_Blob>>3) );
69237  pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
69238  applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
69239  rc = ExpandBlob(pIn1);
69240  assert( pIn1->flags & MEM_Str || db->mallocFailed );
69241  pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
69242  UPDATE_MAX_BLOBSIZE(pIn1);
69243  break;
69244}
69245
69246/* Opcode: ToBlob P1 * * * *
69247**
69248** Force the value in register P1 to be a BLOB.
69249** If the value is numeric, convert it to a string first.
69250** Strings are simply reinterpreted as blobs with no change
69251** to the underlying data.
69252**
69253** A NULL value is not changed by this routine.  It remains NULL.
69254*/
69255case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
69256  pIn1 = &aMem[pOp->p1];
69257  if( pIn1->flags & MEM_Null ) break;
69258  if( (pIn1->flags & MEM_Blob)==0 ){
69259    applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
69260    assert( pIn1->flags & MEM_Str || db->mallocFailed );
69261    MemSetTypeFlag(pIn1, MEM_Blob);
69262  }else{
69263    pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
69264  }
69265  UPDATE_MAX_BLOBSIZE(pIn1);
69266  break;
69267}
69268
69269/* Opcode: ToNumeric P1 * * * *
69270**
69271** Force the value in register P1 to be numeric (either an
69272** integer or a floating-point number.)
69273** If the value is text or blob, try to convert it to an using the
69274** equivalent of atoi() or atof() and store 0 if no such conversion
69275** is possible.
69276**
69277** A NULL value is not changed by this routine.  It remains NULL.
69278*/
69279case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
69280  pIn1 = &aMem[pOp->p1];
69281  sqlite3VdbeMemNumerify(pIn1);
69282  break;
69283}
69284#endif /* SQLITE_OMIT_CAST */
69285
69286/* Opcode: ToInt P1 * * * *
69287**
69288** Force the value in register P1 to be an integer.  If
69289** The value is currently a real number, drop its fractional part.
69290** If the value is text or blob, try to convert it to an integer using the
69291** equivalent of atoi() and store 0 if no such conversion is possible.
69292**
69293** A NULL value is not changed by this routine.  It remains NULL.
69294*/
69295case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
69296  pIn1 = &aMem[pOp->p1];
69297  if( (pIn1->flags & MEM_Null)==0 ){
69298    sqlite3VdbeMemIntegerify(pIn1);
69299  }
69300  break;
69301}
69302
69303#if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
69304/* Opcode: ToReal P1 * * * *
69305**
69306** Force the value in register P1 to be a floating point number.
69307** If The value is currently an integer, convert it.
69308** If the value is text or blob, try to convert it to an integer using the
69309** equivalent of atoi() and store 0.0 if no such conversion is possible.
69310**
69311** A NULL value is not changed by this routine.  It remains NULL.
69312*/
69313case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
69314  pIn1 = &aMem[pOp->p1];
69315  memAboutToChange(p, pIn1);
69316  if( (pIn1->flags & MEM_Null)==0 ){
69317    sqlite3VdbeMemRealify(pIn1);
69318  }
69319  break;
69320}
69321#endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
69322
69323/* Opcode: Lt P1 P2 P3 P4 P5
69324** Synopsis: if r[P1]<r[P3] goto P2
69325**
69326** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
69327** jump to address P2.
69328**
69329** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
69330** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL
69331** bit is clear then fall through if either operand is NULL.
69332**
69333** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
69334** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
69335** to coerce both inputs according to this affinity before the
69336** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
69337** affinity is used. Note that the affinity conversions are stored
69338** back into the input registers P1 and P3.  So this opcode can cause
69339** persistent changes to registers P1 and P3.
69340**
69341** Once any conversions have taken place, and neither value is NULL,
69342** the values are compared. If both values are blobs then memcmp() is
69343** used to determine the results of the comparison.  If both values
69344** are text, then the appropriate collating function specified in
69345** P4 is  used to do the comparison.  If P4 is not specified then
69346** memcmp() is used to compare text string.  If both values are
69347** numeric, then a numeric comparison is used. If the two values
69348** are of different types, then numbers are considered less than
69349** strings and strings are considered less than blobs.
69350**
69351** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
69352** store a boolean result (either 0, or 1, or NULL) in register P2.
69353**
69354** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
69355** equal to one another, provided that they do not have their MEM_Cleared
69356** bit set.
69357*/
69358/* Opcode: Ne P1 P2 P3 P4 P5
69359** Synopsis: if r[P1]!=r[P3] goto P2
69360**
69361** This works just like the Lt opcode except that the jump is taken if
69362** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
69363** additional information.
69364**
69365** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
69366** true or false and is never NULL.  If both operands are NULL then the result
69367** of comparison is false.  If either operand is NULL then the result is true.
69368** If neither operand is NULL the result is the same as it would be if
69369** the SQLITE_NULLEQ flag were omitted from P5.
69370*/
69371/* Opcode: Eq P1 P2 P3 P4 P5
69372** Synopsis: if r[P1]==r[P3] goto P2
69373**
69374** This works just like the Lt opcode except that the jump is taken if
69375** the operands in registers P1 and P3 are equal.
69376** See the Lt opcode for additional information.
69377**
69378** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
69379** true or false and is never NULL.  If both operands are NULL then the result
69380** of comparison is true.  If either operand is NULL then the result is false.
69381** If neither operand is NULL the result is the same as it would be if
69382** the SQLITE_NULLEQ flag were omitted from P5.
69383*/
69384/* Opcode: Le P1 P2 P3 P4 P5
69385** Synopsis: if r[P1]<=r[P3] goto P2
69386**
69387** This works just like the Lt opcode except that the jump is taken if
69388** the content of register P3 is less than or equal to the content of
69389** register P1.  See the Lt opcode for additional information.
69390*/
69391/* Opcode: Gt P1 P2 P3 P4 P5
69392** Synopsis: if r[P1]>r[P3] goto P2
69393**
69394** This works just like the Lt opcode except that the jump is taken if
69395** the content of register P3 is greater than the content of
69396** register P1.  See the Lt opcode for additional information.
69397*/
69398/* Opcode: Ge P1 P2 P3 P4 P5
69399** Synopsis: if r[P1]>=r[P3] goto P2
69400**
69401** This works just like the Lt opcode except that the jump is taken if
69402** the content of register P3 is greater than or equal to the content of
69403** register P1.  See the Lt opcode for additional information.
69404*/
69405case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
69406case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
69407case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
69408case OP_Le:               /* same as TK_LE, jump, in1, in3 */
69409case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
69410case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
69411  int res;            /* Result of the comparison of pIn1 against pIn3 */
69412  char affinity;      /* Affinity to use for comparison */
69413  u16 flags1;         /* Copy of initial value of pIn1->flags */
69414  u16 flags3;         /* Copy of initial value of pIn3->flags */
69415
69416  pIn1 = &aMem[pOp->p1];
69417  pIn3 = &aMem[pOp->p3];
69418  flags1 = pIn1->flags;
69419  flags3 = pIn3->flags;
69420  if( (flags1 | flags3)&MEM_Null ){
69421    /* One or both operands are NULL */
69422    if( pOp->p5 & SQLITE_NULLEQ ){
69423      /* If SQLITE_NULLEQ is set (which will only happen if the operator is
69424      ** OP_Eq or OP_Ne) then take the jump or not depending on whether
69425      ** or not both operands are null.
69426      */
69427      assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
69428      assert( (flags1 & MEM_Cleared)==0 );
69429      assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
69430      if( (flags1&MEM_Null)!=0
69431       && (flags3&MEM_Null)!=0
69432       && (flags3&MEM_Cleared)==0
69433      ){
69434        res = 0;  /* Results are equal */
69435      }else{
69436        res = 1;  /* Results are not equal */
69437      }
69438    }else{
69439      /* SQLITE_NULLEQ is clear and at least one operand is NULL,
69440      ** then the result is always NULL.
69441      ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
69442      */
69443      if( pOp->p5 & SQLITE_STOREP2 ){
69444        pOut = &aMem[pOp->p2];
69445        MemSetTypeFlag(pOut, MEM_Null);
69446        REGISTER_TRACE(pOp->p2, pOut);
69447      }else{
69448        VdbeBranchTaken(2,3);
69449        if( pOp->p5 & SQLITE_JUMPIFNULL ){
69450          pc = pOp->p2-1;
69451        }
69452      }
69453      break;
69454    }
69455  }else{
69456    /* Neither operand is NULL.  Do a comparison. */
69457    affinity = pOp->p5 & SQLITE_AFF_MASK;
69458    if( affinity ){
69459      applyAffinity(pIn1, affinity, encoding);
69460      applyAffinity(pIn3, affinity, encoding);
69461      if( db->mallocFailed ) goto no_mem;
69462    }
69463
69464    assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
69465    ExpandBlob(pIn1);
69466    ExpandBlob(pIn3);
69467    res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
69468  }
69469  switch( pOp->opcode ){
69470    case OP_Eq:    res = res==0;     break;
69471    case OP_Ne:    res = res!=0;     break;
69472    case OP_Lt:    res = res<0;      break;
69473    case OP_Le:    res = res<=0;     break;
69474    case OP_Gt:    res = res>0;      break;
69475    default:       res = res>=0;     break;
69476  }
69477
69478  if( pOp->p5 & SQLITE_STOREP2 ){
69479    pOut = &aMem[pOp->p2];
69480    memAboutToChange(p, pOut);
69481    MemSetTypeFlag(pOut, MEM_Int);
69482    pOut->u.i = res;
69483    REGISTER_TRACE(pOp->p2, pOut);
69484  }else{
69485    VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
69486    if( res ){
69487      pc = pOp->p2-1;
69488    }
69489  }
69490  /* Undo any changes made by applyAffinity() to the input registers. */
69491  pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (flags1&MEM_TypeMask);
69492  pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (flags3&MEM_TypeMask);
69493  break;
69494}
69495
69496/* Opcode: Permutation * * * P4 *
69497**
69498** Set the permutation used by the OP_Compare operator to be the array
69499** of integers in P4.
69500**
69501** The permutation is only valid until the next OP_Compare that has
69502** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
69503** occur immediately prior to the OP_Compare.
69504*/
69505case OP_Permutation: {
69506  assert( pOp->p4type==P4_INTARRAY );
69507  assert( pOp->p4.ai );
69508  aPermute = pOp->p4.ai;
69509  break;
69510}
69511
69512/* Opcode: Compare P1 P2 P3 P4 P5
69513** Synopsis: r[P1@P3] <-> r[P2@P3]
69514**
69515** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
69516** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
69517** the comparison for use by the next OP_Jump instruct.
69518**
69519** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
69520** determined by the most recent OP_Permutation operator.  If the
69521** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
69522** order.
69523**
69524** P4 is a KeyInfo structure that defines collating sequences and sort
69525** orders for the comparison.  The permutation applies to registers
69526** only.  The KeyInfo elements are used sequentially.
69527**
69528** The comparison is a sort comparison, so NULLs compare equal,
69529** NULLs are less than numbers, numbers are less than strings,
69530** and strings are less than blobs.
69531*/
69532case OP_Compare: {
69533  int n;
69534  int i;
69535  int p1;
69536  int p2;
69537  const KeyInfo *pKeyInfo;
69538  int idx;
69539  CollSeq *pColl;    /* Collating sequence to use on this term */
69540  int bRev;          /* True for DESCENDING sort order */
69541
69542  if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
69543  n = pOp->p3;
69544  pKeyInfo = pOp->p4.pKeyInfo;
69545  assert( n>0 );
69546  assert( pKeyInfo!=0 );
69547  p1 = pOp->p1;
69548  p2 = pOp->p2;
69549#if SQLITE_DEBUG
69550  if( aPermute ){
69551    int k, mx = 0;
69552    for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
69553    assert( p1>0 && p1+mx<=(p->nMem-p->nCursor)+1 );
69554    assert( p2>0 && p2+mx<=(p->nMem-p->nCursor)+1 );
69555  }else{
69556    assert( p1>0 && p1+n<=(p->nMem-p->nCursor)+1 );
69557    assert( p2>0 && p2+n<=(p->nMem-p->nCursor)+1 );
69558  }
69559#endif /* SQLITE_DEBUG */
69560  for(i=0; i<n; i++){
69561    idx = aPermute ? aPermute[i] : i;
69562    assert( memIsValid(&aMem[p1+idx]) );
69563    assert( memIsValid(&aMem[p2+idx]) );
69564    REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
69565    REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
69566    assert( i<pKeyInfo->nField );
69567    pColl = pKeyInfo->aColl[i];
69568    bRev = pKeyInfo->aSortOrder[i];
69569    iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
69570    if( iCompare ){
69571      if( bRev ) iCompare = -iCompare;
69572      break;
69573    }
69574  }
69575  aPermute = 0;
69576  break;
69577}
69578
69579/* Opcode: Jump P1 P2 P3 * *
69580**
69581** Jump to the instruction at address P1, P2, or P3 depending on whether
69582** in the most recent OP_Compare instruction the P1 vector was less than
69583** equal to, or greater than the P2 vector, respectively.
69584*/
69585case OP_Jump: {             /* jump */
69586  if( iCompare<0 ){
69587    pc = pOp->p1 - 1;  VdbeBranchTaken(0,3);
69588  }else if( iCompare==0 ){
69589    pc = pOp->p2 - 1;  VdbeBranchTaken(1,3);
69590  }else{
69591    pc = pOp->p3 - 1;  VdbeBranchTaken(2,3);
69592  }
69593  break;
69594}
69595
69596/* Opcode: And P1 P2 P3 * *
69597** Synopsis: r[P3]=(r[P1] && r[P2])
69598**
69599** Take the logical AND of the values in registers P1 and P2 and
69600** write the result into register P3.
69601**
69602** If either P1 or P2 is 0 (false) then the result is 0 even if
69603** the other input is NULL.  A NULL and true or two NULLs give
69604** a NULL output.
69605*/
69606/* Opcode: Or P1 P2 P3 * *
69607** Synopsis: r[P3]=(r[P1] || r[P2])
69608**
69609** Take the logical OR of the values in register P1 and P2 and
69610** store the answer in register P3.
69611**
69612** If either P1 or P2 is nonzero (true) then the result is 1 (true)
69613** even if the other input is NULL.  A NULL and false or two NULLs
69614** give a NULL output.
69615*/
69616case OP_And:              /* same as TK_AND, in1, in2, out3 */
69617case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
69618  int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
69619  int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
69620
69621  pIn1 = &aMem[pOp->p1];
69622  if( pIn1->flags & MEM_Null ){
69623    v1 = 2;
69624  }else{
69625    v1 = sqlite3VdbeIntValue(pIn1)!=0;
69626  }
69627  pIn2 = &aMem[pOp->p2];
69628  if( pIn2->flags & MEM_Null ){
69629    v2 = 2;
69630  }else{
69631    v2 = sqlite3VdbeIntValue(pIn2)!=0;
69632  }
69633  if( pOp->opcode==OP_And ){
69634    static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
69635    v1 = and_logic[v1*3+v2];
69636  }else{
69637    static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
69638    v1 = or_logic[v1*3+v2];
69639  }
69640  pOut = &aMem[pOp->p3];
69641  if( v1==2 ){
69642    MemSetTypeFlag(pOut, MEM_Null);
69643  }else{
69644    pOut->u.i = v1;
69645    MemSetTypeFlag(pOut, MEM_Int);
69646  }
69647  break;
69648}
69649
69650/* Opcode: Not P1 P2 * * *
69651** Synopsis: r[P2]= !r[P1]
69652**
69653** Interpret the value in register P1 as a boolean value.  Store the
69654** boolean complement in register P2.  If the value in register P1 is
69655** NULL, then a NULL is stored in P2.
69656*/
69657case OP_Not: {                /* same as TK_NOT, in1, out2 */
69658  pIn1 = &aMem[pOp->p1];
69659  pOut = &aMem[pOp->p2];
69660  if( pIn1->flags & MEM_Null ){
69661    sqlite3VdbeMemSetNull(pOut);
69662  }else{
69663    sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
69664  }
69665  break;
69666}
69667
69668/* Opcode: BitNot P1 P2 * * *
69669** Synopsis: r[P1]= ~r[P1]
69670**
69671** Interpret the content of register P1 as an integer.  Store the
69672** ones-complement of the P1 value into register P2.  If P1 holds
69673** a NULL then store a NULL in P2.
69674*/
69675case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
69676  pIn1 = &aMem[pOp->p1];
69677  pOut = &aMem[pOp->p2];
69678  if( pIn1->flags & MEM_Null ){
69679    sqlite3VdbeMemSetNull(pOut);
69680  }else{
69681    sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
69682  }
69683  break;
69684}
69685
69686/* Opcode: Once P1 P2 * * *
69687**
69688** Check if OP_Once flag P1 is set. If so, jump to instruction P2. Otherwise,
69689** set the flag and fall through to the next instruction.  In other words,
69690** this opcode causes all following opcodes up through P2 (but not including
69691** P2) to run just once and to be skipped on subsequent times through the loop.
69692*/
69693case OP_Once: {             /* jump */
69694  assert( pOp->p1<p->nOnceFlag );
69695  VdbeBranchTaken(p->aOnceFlag[pOp->p1]!=0, 2);
69696  if( p->aOnceFlag[pOp->p1] ){
69697    pc = pOp->p2-1;
69698  }else{
69699    p->aOnceFlag[pOp->p1] = 1;
69700  }
69701  break;
69702}
69703
69704/* Opcode: If P1 P2 P3 * *
69705**
69706** Jump to P2 if the value in register P1 is true.  The value
69707** is considered true if it is numeric and non-zero.  If the value
69708** in P1 is NULL then take the jump if P3 is non-zero.
69709*/
69710/* Opcode: IfNot P1 P2 P3 * *
69711**
69712** Jump to P2 if the value in register P1 is False.  The value
69713** is considered false if it has a numeric value of zero.  If the value
69714** in P1 is NULL then take the jump if P3 is zero.
69715*/
69716case OP_If:                 /* jump, in1 */
69717case OP_IfNot: {            /* jump, in1 */
69718  int c;
69719  pIn1 = &aMem[pOp->p1];
69720  if( pIn1->flags & MEM_Null ){
69721    c = pOp->p3;
69722  }else{
69723#ifdef SQLITE_OMIT_FLOATING_POINT
69724    c = sqlite3VdbeIntValue(pIn1)!=0;
69725#else
69726    c = sqlite3VdbeRealValue(pIn1)!=0.0;
69727#endif
69728    if( pOp->opcode==OP_IfNot ) c = !c;
69729  }
69730  VdbeBranchTaken(c!=0, 2);
69731  if( c ){
69732    pc = pOp->p2-1;
69733  }
69734  break;
69735}
69736
69737/* Opcode: IsNull P1 P2 * * *
69738** Synopsis:  if r[P1]==NULL goto P2
69739**
69740** Jump to P2 if the value in register P1 is NULL.
69741*/
69742case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
69743  pIn1 = &aMem[pOp->p1];
69744  VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
69745  if( (pIn1->flags & MEM_Null)!=0 ){
69746    pc = pOp->p2 - 1;
69747  }
69748  break;
69749}
69750
69751/* Opcode: NotNull P1 P2 * * *
69752** Synopsis: if r[P1]!=NULL goto P2
69753**
69754** Jump to P2 if the value in register P1 is not NULL.
69755*/
69756case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
69757  pIn1 = &aMem[pOp->p1];
69758  VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
69759  if( (pIn1->flags & MEM_Null)==0 ){
69760    pc = pOp->p2 - 1;
69761  }
69762  break;
69763}
69764
69765/* Opcode: Column P1 P2 P3 P4 P5
69766** Synopsis:  r[P3]=PX
69767**
69768** Interpret the data that cursor P1 points to as a structure built using
69769** the MakeRecord instruction.  (See the MakeRecord opcode for additional
69770** information about the format of the data.)  Extract the P2-th column
69771** from this record.  If there are less that (P2+1)
69772** values in the record, extract a NULL.
69773**
69774** The value extracted is stored in register P3.
69775**
69776** If the column contains fewer than P2 fields, then extract a NULL.  Or,
69777** if the P4 argument is a P4_MEM use the value of the P4 argument as
69778** the result.
69779**
69780** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
69781** then the cache of the cursor is reset prior to extracting the column.
69782** The first OP_Column against a pseudo-table after the value of the content
69783** register has changed should have this bit set.
69784**
69785** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
69786** the result is guaranteed to only be used as the argument of a length()
69787** or typeof() function, respectively.  The loading of large blobs can be
69788** skipped for length() and all content loading can be skipped for typeof().
69789*/
69790case OP_Column: {
69791  i64 payloadSize64; /* Number of bytes in the record */
69792  int p2;            /* column number to retrieve */
69793  VdbeCursor *pC;    /* The VDBE cursor */
69794  BtCursor *pCrsr;   /* The BTree cursor */
69795  u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
69796  u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
69797  int len;           /* The length of the serialized data for the column */
69798  int i;             /* Loop counter */
69799  Mem *pDest;        /* Where to write the extracted value */
69800  Mem sMem;          /* For storing the record being decoded */
69801  const u8 *zData;   /* Part of the record being decoded */
69802  const u8 *zHdr;    /* Next unparsed byte of the header */
69803  const u8 *zEndHdr; /* Pointer to first byte after the header */
69804  u32 offset;        /* Offset into the data */
69805  u32 szField;       /* Number of bytes in the content of a field */
69806  u32 avail;         /* Number of bytes of available data */
69807  u32 t;             /* A type code from the record header */
69808  Mem *pReg;         /* PseudoTable input register */
69809
69810  p2 = pOp->p2;
69811  assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
69812  pDest = &aMem[pOp->p3];
69813  memAboutToChange(p, pDest);
69814  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69815  pC = p->apCsr[pOp->p1];
69816  assert( pC!=0 );
69817  assert( p2<pC->nField );
69818  aType = pC->aType;
69819  aOffset = aType + pC->nField;
69820#ifndef SQLITE_OMIT_VIRTUALTABLE
69821  assert( pC->pVtabCursor==0 ); /* OP_Column never called on virtual table */
69822#endif
69823  pCrsr = pC->pCursor;
69824  assert( pCrsr!=0 || pC->pseudoTableReg>0 ); /* pCrsr NULL on PseudoTables */
69825  assert( pCrsr!=0 || pC->nullRow );          /* pC->nullRow on PseudoTables */
69826
69827  /* If the cursor cache is stale, bring it up-to-date */
69828  rc = sqlite3VdbeCursorMoveto(pC);
69829  if( rc ) goto abort_due_to_error;
69830  if( pC->cacheStatus!=p->cacheCtr || (pOp->p5&OPFLAG_CLEARCACHE)!=0 ){
69831    if( pC->nullRow ){
69832      if( pCrsr==0 ){
69833        assert( pC->pseudoTableReg>0 );
69834        pReg = &aMem[pC->pseudoTableReg];
69835        assert( pReg->flags & MEM_Blob );
69836        assert( memIsValid(pReg) );
69837        pC->payloadSize = pC->szRow = avail = pReg->n;
69838        pC->aRow = (u8*)pReg->z;
69839      }else{
69840        MemSetTypeFlag(pDest, MEM_Null);
69841        goto op_column_out;
69842      }
69843    }else{
69844      assert( pCrsr );
69845      if( pC->isTable==0 ){
69846        assert( sqlite3BtreeCursorIsValid(pCrsr) );
69847        VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &payloadSize64);
69848        assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
69849        /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
69850        ** payload size, so it is impossible for payloadSize64 to be
69851        ** larger than 32 bits. */
69852        assert( (payloadSize64 & SQLITE_MAX_U32)==(u64)payloadSize64 );
69853        pC->aRow = sqlite3BtreeKeyFetch(pCrsr, &avail);
69854        pC->payloadSize = (u32)payloadSize64;
69855      }else{
69856        assert( sqlite3BtreeCursorIsValid(pCrsr) );
69857        VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &pC->payloadSize);
69858        assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
69859        pC->aRow = sqlite3BtreeDataFetch(pCrsr, &avail);
69860      }
69861      assert( avail<=65536 );  /* Maximum page size is 64KiB */
69862      if( pC->payloadSize <= (u32)avail ){
69863        pC->szRow = pC->payloadSize;
69864      }else{
69865        pC->szRow = avail;
69866      }
69867      if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
69868        goto too_big;
69869      }
69870    }
69871    pC->cacheStatus = p->cacheCtr;
69872    pC->iHdrOffset = getVarint32(pC->aRow, offset);
69873    pC->nHdrParsed = 0;
69874    aOffset[0] = offset;
69875    if( avail<offset ){
69876      /* pC->aRow does not have to hold the entire row, but it does at least
69877      ** need to cover the header of the record.  If pC->aRow does not contain
69878      ** the complete header, then set it to zero, forcing the header to be
69879      ** dynamically allocated. */
69880      pC->aRow = 0;
69881      pC->szRow = 0;
69882    }
69883
69884    /* Make sure a corrupt database has not given us an oversize header.
69885    ** Do this now to avoid an oversize memory allocation.
69886    **
69887    ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
69888    ** types use so much data space that there can only be 4096 and 32 of
69889    ** them, respectively.  So the maximum header length results from a
69890    ** 3-byte type for each of the maximum of 32768 columns plus three
69891    ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
69892    */
69893    if( offset > 98307 || offset > pC->payloadSize ){
69894      rc = SQLITE_CORRUPT_BKPT;
69895      goto op_column_error;
69896    }
69897  }
69898
69899  /* Make sure at least the first p2+1 entries of the header have been
69900  ** parsed and valid information is in aOffset[] and aType[].
69901  */
69902  if( pC->nHdrParsed<=p2 ){
69903    /* If there is more header available for parsing in the record, try
69904    ** to extract additional fields up through the p2+1-th field
69905    */
69906    if( pC->iHdrOffset<aOffset[0] ){
69907      /* Make sure zData points to enough of the record to cover the header. */
69908      if( pC->aRow==0 ){
69909        memset(&sMem, 0, sizeof(sMem));
69910        rc = sqlite3VdbeMemFromBtree(pCrsr, 0, aOffset[0],
69911                                     !pC->isTable, &sMem);
69912        if( rc!=SQLITE_OK ){
69913          goto op_column_error;
69914        }
69915        zData = (u8*)sMem.z;
69916      }else{
69917        zData = pC->aRow;
69918      }
69919
69920      /* Fill in aType[i] and aOffset[i] values through the p2-th field. */
69921      i = pC->nHdrParsed;
69922      offset = aOffset[i];
69923      zHdr = zData + pC->iHdrOffset;
69924      zEndHdr = zData + aOffset[0];
69925      assert( i<=p2 && zHdr<zEndHdr );
69926      do{
69927        if( zHdr[0]<0x80 ){
69928          t = zHdr[0];
69929          zHdr++;
69930        }else{
69931          zHdr += sqlite3GetVarint32(zHdr, &t);
69932        }
69933        aType[i] = t;
69934        szField = sqlite3VdbeSerialTypeLen(t);
69935        offset += szField;
69936        if( offset<szField ){  /* True if offset overflows */
69937          zHdr = &zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
69938          break;
69939        }
69940        i++;
69941        aOffset[i] = offset;
69942      }while( i<=p2 && zHdr<zEndHdr );
69943      pC->nHdrParsed = i;
69944      pC->iHdrOffset = (u32)(zHdr - zData);
69945      if( pC->aRow==0 ){
69946        sqlite3VdbeMemRelease(&sMem);
69947        sMem.flags = MEM_Null;
69948      }
69949
69950      /* If we have read more header data than was contained in the header,
69951      ** or if the end of the last field appears to be past the end of the
69952      ** record, or if the end of the last field appears to be before the end
69953      ** of the record (when all fields present), then we must be dealing
69954      ** with a corrupt database.
69955      */
69956      if( (zHdr > zEndHdr)
69957       || (offset > pC->payloadSize)
69958       || (zHdr==zEndHdr && offset!=pC->payloadSize)
69959      ){
69960        rc = SQLITE_CORRUPT_BKPT;
69961        goto op_column_error;
69962      }
69963    }
69964
69965    /* If after trying to extra new entries from the header, nHdrParsed is
69966    ** still not up to p2, that means that the record has fewer than p2
69967    ** columns.  So the result will be either the default value or a NULL.
69968    */
69969    if( pC->nHdrParsed<=p2 ){
69970      if( pOp->p4type==P4_MEM ){
69971        sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
69972      }else{
69973        MemSetTypeFlag(pDest, MEM_Null);
69974      }
69975      goto op_column_out;
69976    }
69977  }
69978
69979  /* Extract the content for the p2+1-th column.  Control can only
69980  ** reach this point if aOffset[p2], aOffset[p2+1], and aType[p2] are
69981  ** all valid.
69982  */
69983  assert( p2<pC->nHdrParsed );
69984  assert( rc==SQLITE_OK );
69985  assert( sqlite3VdbeCheckMemInvariants(pDest) );
69986  if( pC->szRow>=aOffset[p2+1] ){
69987    /* This is the common case where the desired content fits on the original
69988    ** page - where the content is not on an overflow page */
69989    VdbeMemRelease(pDest);
69990    sqlite3VdbeSerialGet(pC->aRow+aOffset[p2], aType[p2], pDest);
69991  }else{
69992    /* This branch happens only when content is on overflow pages */
69993    t = aType[p2];
69994    if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
69995          && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
69996     || (len = sqlite3VdbeSerialTypeLen(t))==0
69997    ){
69998      /* Content is irrelevant for the typeof() function and for
69999      ** the length(X) function if X is a blob.  So we might as well use
70000      ** bogus content rather than reading content from disk.  NULL works
70001      ** for text and blob and whatever is in the payloadSize64 variable
70002      ** will work for everything else.  Content is also irrelevant if
70003      ** the content length is 0. */
70004      zData = t<=13 ? (u8*)&payloadSize64 : 0;
70005      sMem.zMalloc = 0;
70006    }else{
70007      memset(&sMem, 0, sizeof(sMem));
70008      sqlite3VdbeMemMove(&sMem, pDest);
70009      rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, !pC->isTable,
70010                                   &sMem);
70011      if( rc!=SQLITE_OK ){
70012        goto op_column_error;
70013      }
70014      zData = (u8*)sMem.z;
70015    }
70016    sqlite3VdbeSerialGet(zData, t, pDest);
70017    /* If we dynamically allocated space to hold the data (in the
70018    ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
70019    ** dynamically allocated space over to the pDest structure.
70020    ** This prevents a memory copy. */
70021    if( sMem.zMalloc ){
70022      assert( sMem.z==sMem.zMalloc );
70023      assert( VdbeMemDynamic(pDest)==0 );
70024      assert( (pDest->flags & (MEM_Blob|MEM_Str))==0 || pDest->z==sMem.z );
70025      pDest->flags &= ~(MEM_Ephem|MEM_Static);
70026      pDest->flags |= MEM_Term;
70027      pDest->z = sMem.z;
70028      pDest->zMalloc = sMem.zMalloc;
70029    }
70030  }
70031  pDest->enc = encoding;
70032
70033op_column_out:
70034  Deephemeralize(pDest);
70035op_column_error:
70036  UPDATE_MAX_BLOBSIZE(pDest);
70037  REGISTER_TRACE(pOp->p3, pDest);
70038  break;
70039}
70040
70041/* Opcode: Affinity P1 P2 * P4 *
70042** Synopsis: affinity(r[P1@P2])
70043**
70044** Apply affinities to a range of P2 registers starting with P1.
70045**
70046** P4 is a string that is P2 characters long. The nth character of the
70047** string indicates the column affinity that should be used for the nth
70048** memory cell in the range.
70049*/
70050case OP_Affinity: {
70051  const char *zAffinity;   /* The affinity to be applied */
70052  char cAff;               /* A single character of affinity */
70053
70054  zAffinity = pOp->p4.z;
70055  assert( zAffinity!=0 );
70056  assert( zAffinity[pOp->p2]==0 );
70057  pIn1 = &aMem[pOp->p1];
70058  while( (cAff = *(zAffinity++))!=0 ){
70059    assert( pIn1 <= &p->aMem[(p->nMem-p->nCursor)] );
70060    assert( memIsValid(pIn1) );
70061    applyAffinity(pIn1, cAff, encoding);
70062    pIn1++;
70063  }
70064  break;
70065}
70066
70067/* Opcode: MakeRecord P1 P2 P3 P4 *
70068** Synopsis: r[P3]=mkrec(r[P1@P2])
70069**
70070** Convert P2 registers beginning with P1 into the [record format]
70071** use as a data record in a database table or as a key
70072** in an index.  The OP_Column opcode can decode the record later.
70073**
70074** P4 may be a string that is P2 characters long.  The nth character of the
70075** string indicates the column affinity that should be used for the nth
70076** field of the index key.
70077**
70078** The mapping from character to affinity is given by the SQLITE_AFF_
70079** macros defined in sqliteInt.h.
70080**
70081** If P4 is NULL then all index fields have the affinity NONE.
70082*/
70083case OP_MakeRecord: {
70084  u8 *zNewRecord;        /* A buffer to hold the data for the new record */
70085  Mem *pRec;             /* The new record */
70086  u64 nData;             /* Number of bytes of data space */
70087  int nHdr;              /* Number of bytes of header space */
70088  i64 nByte;             /* Data space required for this record */
70089  int nZero;             /* Number of zero bytes at the end of the record */
70090  int nVarint;           /* Number of bytes in a varint */
70091  u32 serial_type;       /* Type field */
70092  Mem *pData0;           /* First field to be combined into the record */
70093  Mem *pLast;            /* Last field of the record */
70094  int nField;            /* Number of fields in the record */
70095  char *zAffinity;       /* The affinity string for the record */
70096  int file_format;       /* File format to use for encoding */
70097  int i;                 /* Space used in zNewRecord[] header */
70098  int j;                 /* Space used in zNewRecord[] content */
70099  int len;               /* Length of a field */
70100
70101  /* Assuming the record contains N fields, the record format looks
70102  ** like this:
70103  **
70104  ** ------------------------------------------------------------------------
70105  ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
70106  ** ------------------------------------------------------------------------
70107  **
70108  ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
70109  ** and so froth.
70110  **
70111  ** Each type field is a varint representing the serial type of the
70112  ** corresponding data element (see sqlite3VdbeSerialType()). The
70113  ** hdr-size field is also a varint which is the offset from the beginning
70114  ** of the record to data0.
70115  */
70116  nData = 0;         /* Number of bytes of data space */
70117  nHdr = 0;          /* Number of bytes of header space */
70118  nZero = 0;         /* Number of zero bytes at the end of the record */
70119  nField = pOp->p1;
70120  zAffinity = pOp->p4.z;
70121  assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem-p->nCursor)+1 );
70122  pData0 = &aMem[nField];
70123  nField = pOp->p2;
70124  pLast = &pData0[nField-1];
70125  file_format = p->minWriteFileFormat;
70126
70127  /* Identify the output register */
70128  assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
70129  pOut = &aMem[pOp->p3];
70130  memAboutToChange(p, pOut);
70131
70132  /* Apply the requested affinity to all inputs
70133  */
70134  assert( pData0<=pLast );
70135  if( zAffinity ){
70136    pRec = pData0;
70137    do{
70138      applyAffinity(pRec++, *(zAffinity++), encoding);
70139      assert( zAffinity[0]==0 || pRec<=pLast );
70140    }while( zAffinity[0] );
70141  }
70142
70143  /* Loop through the elements that will make up the record to figure
70144  ** out how much space is required for the new record.
70145  */
70146  pRec = pLast;
70147  do{
70148    assert( memIsValid(pRec) );
70149    serial_type = sqlite3VdbeSerialType(pRec, file_format);
70150    len = sqlite3VdbeSerialTypeLen(serial_type);
70151    if( pRec->flags & MEM_Zero ){
70152      if( nData ){
70153        sqlite3VdbeMemExpandBlob(pRec);
70154      }else{
70155        nZero += pRec->u.nZero;
70156        len -= pRec->u.nZero;
70157      }
70158    }
70159    nData += len;
70160    testcase( serial_type==127 );
70161    testcase( serial_type==128 );
70162    nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
70163  }while( (--pRec)>=pData0 );
70164
70165  /* Add the initial header varint and total the size */
70166  testcase( nHdr==126 );
70167  testcase( nHdr==127 );
70168  if( nHdr<=126 ){
70169    /* The common case */
70170    nHdr += 1;
70171  }else{
70172    /* Rare case of a really large header */
70173    nVarint = sqlite3VarintLen(nHdr);
70174    nHdr += nVarint;
70175    if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
70176  }
70177  nByte = nHdr+nData;
70178  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
70179    goto too_big;
70180  }
70181
70182  /* Make sure the output register has a buffer large enough to store
70183  ** the new record. The output register (pOp->p3) is not allowed to
70184  ** be one of the input registers (because the following call to
70185  ** sqlite3VdbeMemGrow() could clobber the value before it is used).
70186  */
70187  if( sqlite3VdbeMemGrow(pOut, (int)nByte, 0) ){
70188    goto no_mem;
70189  }
70190  zNewRecord = (u8 *)pOut->z;
70191
70192  /* Write the record */
70193  i = putVarint32(zNewRecord, nHdr);
70194  j = nHdr;
70195  assert( pData0<=pLast );
70196  pRec = pData0;
70197  do{
70198    serial_type = sqlite3VdbeSerialType(pRec, file_format);
70199    i += putVarint32(&zNewRecord[i], serial_type);            /* serial type */
70200    j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
70201  }while( (++pRec)<=pLast );
70202  assert( i==nHdr );
70203  assert( j==nByte );
70204
70205  assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
70206  pOut->n = (int)nByte;
70207  pOut->flags = MEM_Blob;
70208  pOut->xDel = 0;
70209  if( nZero ){
70210    pOut->u.nZero = nZero;
70211    pOut->flags |= MEM_Zero;
70212  }
70213  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
70214  REGISTER_TRACE(pOp->p3, pOut);
70215  UPDATE_MAX_BLOBSIZE(pOut);
70216  break;
70217}
70218
70219/* Opcode: Count P1 P2 * * *
70220** Synopsis: r[P2]=count()
70221**
70222** Store the number of entries (an integer value) in the table or index
70223** opened by cursor P1 in register P2
70224*/
70225#ifndef SQLITE_OMIT_BTREECOUNT
70226case OP_Count: {         /* out2-prerelease */
70227  i64 nEntry;
70228  BtCursor *pCrsr;
70229
70230  pCrsr = p->apCsr[pOp->p1]->pCursor;
70231  assert( pCrsr );
70232  nEntry = 0;  /* Not needed.  Only used to silence a warning. */
70233  rc = sqlite3BtreeCount(pCrsr, &nEntry);
70234  pOut->u.i = nEntry;
70235  break;
70236}
70237#endif
70238
70239/* Opcode: Savepoint P1 * * P4 *
70240**
70241** Open, release or rollback the savepoint named by parameter P4, depending
70242** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
70243** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
70244*/
70245case OP_Savepoint: {
70246  int p1;                         /* Value of P1 operand */
70247  char *zName;                    /* Name of savepoint */
70248  int nName;
70249  Savepoint *pNew;
70250  Savepoint *pSavepoint;
70251  Savepoint *pTmp;
70252  int iSavepoint;
70253  int ii;
70254
70255  p1 = pOp->p1;
70256  zName = pOp->p4.z;
70257
70258  /* Assert that the p1 parameter is valid. Also that if there is no open
70259  ** transaction, then there cannot be any savepoints.
70260  */
70261  assert( db->pSavepoint==0 || db->autoCommit==0 );
70262  assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
70263  assert( db->pSavepoint || db->isTransactionSavepoint==0 );
70264  assert( checkSavepointCount(db) );
70265  assert( p->bIsReader );
70266
70267  if( p1==SAVEPOINT_BEGIN ){
70268    if( db->nVdbeWrite>0 ){
70269      /* A new savepoint cannot be created if there are active write
70270      ** statements (i.e. open read/write incremental blob handles).
70271      */
70272      sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
70273        "SQL statements in progress");
70274      rc = SQLITE_BUSY;
70275    }else{
70276      nName = sqlite3Strlen30(zName);
70277
70278#ifndef SQLITE_OMIT_VIRTUALTABLE
70279      /* This call is Ok even if this savepoint is actually a transaction
70280      ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
70281      ** If this is a transaction savepoint being opened, it is guaranteed
70282      ** that the db->aVTrans[] array is empty.  */
70283      assert( db->autoCommit==0 || db->nVTrans==0 );
70284      rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
70285                                db->nStatement+db->nSavepoint);
70286      if( rc!=SQLITE_OK ) goto abort_due_to_error;
70287#endif
70288
70289      /* Create a new savepoint structure. */
70290      pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+nName+1);
70291      if( pNew ){
70292        pNew->zName = (char *)&pNew[1];
70293        memcpy(pNew->zName, zName, nName+1);
70294
70295        /* If there is no open transaction, then mark this as a special
70296        ** "transaction savepoint". */
70297        if( db->autoCommit ){
70298          db->autoCommit = 0;
70299          db->isTransactionSavepoint = 1;
70300        }else{
70301          db->nSavepoint++;
70302        }
70303
70304        /* Link the new savepoint into the database handle's list. */
70305        pNew->pNext = db->pSavepoint;
70306        db->pSavepoint = pNew;
70307        pNew->nDeferredCons = db->nDeferredCons;
70308        pNew->nDeferredImmCons = db->nDeferredImmCons;
70309      }
70310    }
70311  }else{
70312    iSavepoint = 0;
70313
70314    /* Find the named savepoint. If there is no such savepoint, then an
70315    ** an error is returned to the user.  */
70316    for(
70317      pSavepoint = db->pSavepoint;
70318      pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
70319      pSavepoint = pSavepoint->pNext
70320    ){
70321      iSavepoint++;
70322    }
70323    if( !pSavepoint ){
70324      sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", zName);
70325      rc = SQLITE_ERROR;
70326    }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
70327      /* It is not possible to release (commit) a savepoint if there are
70328      ** active write statements.
70329      */
70330      sqlite3SetString(&p->zErrMsg, db,
70331        "cannot release savepoint - SQL statements in progress"
70332      );
70333      rc = SQLITE_BUSY;
70334    }else{
70335
70336      /* Determine whether or not this is a transaction savepoint. If so,
70337      ** and this is a RELEASE command, then the current transaction
70338      ** is committed.
70339      */
70340      int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
70341      if( isTransaction && p1==SAVEPOINT_RELEASE ){
70342        if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
70343          goto vdbe_return;
70344        }
70345        db->autoCommit = 1;
70346        if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
70347          p->pc = pc;
70348          db->autoCommit = 0;
70349          p->rc = rc = SQLITE_BUSY;
70350          goto vdbe_return;
70351        }
70352        db->isTransactionSavepoint = 0;
70353        rc = p->rc;
70354      }else{
70355        iSavepoint = db->nSavepoint - iSavepoint - 1;
70356        if( p1==SAVEPOINT_ROLLBACK ){
70357          for(ii=0; ii<db->nDb; ii++){
70358            sqlite3BtreeTripAllCursors(db->aDb[ii].pBt, SQLITE_ABORT);
70359          }
70360        }
70361        for(ii=0; ii<db->nDb; ii++){
70362          rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
70363          if( rc!=SQLITE_OK ){
70364            goto abort_due_to_error;
70365          }
70366        }
70367        if( p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
70368          sqlite3ExpirePreparedStatements(db);
70369          sqlite3ResetAllSchemasOfConnection(db);
70370          db->flags = (db->flags | SQLITE_InternChanges);
70371        }
70372      }
70373
70374      /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
70375      ** savepoints nested inside of the savepoint being operated on. */
70376      while( db->pSavepoint!=pSavepoint ){
70377        pTmp = db->pSavepoint;
70378        db->pSavepoint = pTmp->pNext;
70379        sqlite3DbFree(db, pTmp);
70380        db->nSavepoint--;
70381      }
70382
70383      /* If it is a RELEASE, then destroy the savepoint being operated on
70384      ** too. If it is a ROLLBACK TO, then set the number of deferred
70385      ** constraint violations present in the database to the value stored
70386      ** when the savepoint was created.  */
70387      if( p1==SAVEPOINT_RELEASE ){
70388        assert( pSavepoint==db->pSavepoint );
70389        db->pSavepoint = pSavepoint->pNext;
70390        sqlite3DbFree(db, pSavepoint);
70391        if( !isTransaction ){
70392          db->nSavepoint--;
70393        }
70394      }else{
70395        db->nDeferredCons = pSavepoint->nDeferredCons;
70396        db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
70397      }
70398
70399      if( !isTransaction ){
70400        rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
70401        if( rc!=SQLITE_OK ) goto abort_due_to_error;
70402      }
70403    }
70404  }
70405
70406  break;
70407}
70408
70409/* Opcode: AutoCommit P1 P2 * * *
70410**
70411** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
70412** back any currently active btree transactions. If there are any active
70413** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
70414** there are active writing VMs or active VMs that use shared cache.
70415**
70416** This instruction causes the VM to halt.
70417*/
70418case OP_AutoCommit: {
70419  int desiredAutoCommit;
70420  int iRollback;
70421  int turnOnAC;
70422
70423  desiredAutoCommit = pOp->p1;
70424  iRollback = pOp->p2;
70425  turnOnAC = desiredAutoCommit && !db->autoCommit;
70426  assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
70427  assert( desiredAutoCommit==1 || iRollback==0 );
70428  assert( db->nVdbeActive>0 );  /* At least this one VM is active */
70429  assert( p->bIsReader );
70430
70431#if 0
70432  if( turnOnAC && iRollback && db->nVdbeActive>1 ){
70433    /* If this instruction implements a ROLLBACK and other VMs are
70434    ** still running, and a transaction is active, return an error indicating
70435    ** that the other VMs must complete first.
70436    */
70437    sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
70438        "SQL statements in progress");
70439    rc = SQLITE_BUSY;
70440  }else
70441#endif
70442  if( turnOnAC && !iRollback && db->nVdbeWrite>0 ){
70443    /* If this instruction implements a COMMIT and other VMs are writing
70444    ** return an error indicating that the other VMs must complete first.
70445    */
70446    sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
70447        "SQL statements in progress");
70448    rc = SQLITE_BUSY;
70449  }else if( desiredAutoCommit!=db->autoCommit ){
70450    if( iRollback ){
70451      assert( desiredAutoCommit==1 );
70452      sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
70453      db->autoCommit = 1;
70454    }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
70455      goto vdbe_return;
70456    }else{
70457      db->autoCommit = (u8)desiredAutoCommit;
70458      if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
70459        p->pc = pc;
70460        db->autoCommit = (u8)(1-desiredAutoCommit);
70461        p->rc = rc = SQLITE_BUSY;
70462        goto vdbe_return;
70463      }
70464    }
70465    assert( db->nStatement==0 );
70466    sqlite3CloseSavepoints(db);
70467    if( p->rc==SQLITE_OK ){
70468      rc = SQLITE_DONE;
70469    }else{
70470      rc = SQLITE_ERROR;
70471    }
70472    goto vdbe_return;
70473  }else{
70474    sqlite3SetString(&p->zErrMsg, db,
70475        (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
70476        (iRollback)?"cannot rollback - no transaction is active":
70477                   "cannot commit - no transaction is active"));
70478
70479    rc = SQLITE_ERROR;
70480  }
70481  break;
70482}
70483
70484/* Opcode: Transaction P1 P2 P3 P4 P5
70485**
70486** Begin a transaction on database P1 if a transaction is not already
70487** active.
70488** If P2 is non-zero, then a write-transaction is started, or if a
70489** read-transaction is already active, it is upgraded to a write-transaction.
70490** If P2 is zero, then a read-transaction is started.
70491**
70492** P1 is the index of the database file on which the transaction is
70493** started.  Index 0 is the main database file and index 1 is the
70494** file used for temporary tables.  Indices of 2 or more are used for
70495** attached databases.
70496**
70497** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
70498** true (this flag is set if the Vdbe may modify more than one row and may
70499** throw an ABORT exception), a statement transaction may also be opened.
70500** More specifically, a statement transaction is opened iff the database
70501** connection is currently not in autocommit mode, or if there are other
70502** active statements. A statement transaction allows the changes made by this
70503** VDBE to be rolled back after an error without having to roll back the
70504** entire transaction. If no error is encountered, the statement transaction
70505** will automatically commit when the VDBE halts.
70506**
70507** If P5!=0 then this opcode also checks the schema cookie against P3
70508** and the schema generation counter against P4.
70509** The cookie changes its value whenever the database schema changes.
70510** This operation is used to detect when that the cookie has changed
70511** and that the current process needs to reread the schema.  If the schema
70512** cookie in P3 differs from the schema cookie in the database header or
70513** if the schema generation counter in P4 differs from the current
70514** generation counter, then an SQLITE_SCHEMA error is raised and execution
70515** halts.  The sqlite3_step() wrapper function might then reprepare the
70516** statement and rerun it from the beginning.
70517*/
70518case OP_Transaction: {
70519  Btree *pBt;
70520  int iMeta;
70521  int iGen;
70522
70523  assert( p->bIsReader );
70524  assert( p->readOnly==0 || pOp->p2==0 );
70525  assert( pOp->p1>=0 && pOp->p1<db->nDb );
70526  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
70527  if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
70528    rc = SQLITE_READONLY;
70529    goto abort_due_to_error;
70530  }
70531  pBt = db->aDb[pOp->p1].pBt;
70532
70533  if( pBt ){
70534    rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
70535    if( rc==SQLITE_BUSY ){
70536      p->pc = pc;
70537      p->rc = rc = SQLITE_BUSY;
70538      goto vdbe_return;
70539    }
70540    if( rc!=SQLITE_OK ){
70541      goto abort_due_to_error;
70542    }
70543
70544    if( pOp->p2 && p->usesStmtJournal
70545     && (db->autoCommit==0 || db->nVdbeRead>1)
70546    ){
70547      assert( sqlite3BtreeIsInTrans(pBt) );
70548      if( p->iStatement==0 ){
70549        assert( db->nStatement>=0 && db->nSavepoint>=0 );
70550        db->nStatement++;
70551        p->iStatement = db->nSavepoint + db->nStatement;
70552      }
70553
70554      rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
70555      if( rc==SQLITE_OK ){
70556        rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
70557      }
70558
70559      /* Store the current value of the database handles deferred constraint
70560      ** counter. If the statement transaction needs to be rolled back,
70561      ** the value of this counter needs to be restored too.  */
70562      p->nStmtDefCons = db->nDeferredCons;
70563      p->nStmtDefImmCons = db->nDeferredImmCons;
70564    }
70565
70566    /* Gather the schema version number for checking */
70567    sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
70568    iGen = db->aDb[pOp->p1].pSchema->iGeneration;
70569  }else{
70570    iGen = iMeta = 0;
70571  }
70572  assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
70573  if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
70574    sqlite3DbFree(db, p->zErrMsg);
70575    p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
70576    /* If the schema-cookie from the database file matches the cookie
70577    ** stored with the in-memory representation of the schema, do
70578    ** not reload the schema from the database file.
70579    **
70580    ** If virtual-tables are in use, this is not just an optimization.
70581    ** Often, v-tables store their data in other SQLite tables, which
70582    ** are queried from within xNext() and other v-table methods using
70583    ** prepared queries. If such a query is out-of-date, we do not want to
70584    ** discard the database schema, as the user code implementing the
70585    ** v-table would have to be ready for the sqlite3_vtab structure itself
70586    ** to be invalidated whenever sqlite3_step() is called from within
70587    ** a v-table method.
70588    */
70589    if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
70590      sqlite3ResetOneSchema(db, pOp->p1);
70591    }
70592    p->expired = 1;
70593    rc = SQLITE_SCHEMA;
70594  }
70595  break;
70596}
70597
70598/* Opcode: ReadCookie P1 P2 P3 * *
70599**
70600** Read cookie number P3 from database P1 and write it into register P2.
70601** P3==1 is the schema version.  P3==2 is the database format.
70602** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
70603** the main database file and P1==1 is the database file used to store
70604** temporary tables.
70605**
70606** There must be a read-lock on the database (either a transaction
70607** must be started or there must be an open cursor) before
70608** executing this instruction.
70609*/
70610case OP_ReadCookie: {               /* out2-prerelease */
70611  int iMeta;
70612  int iDb;
70613  int iCookie;
70614
70615  assert( p->bIsReader );
70616  iDb = pOp->p1;
70617  iCookie = pOp->p3;
70618  assert( pOp->p3<SQLITE_N_BTREE_META );
70619  assert( iDb>=0 && iDb<db->nDb );
70620  assert( db->aDb[iDb].pBt!=0 );
70621  assert( (p->btreeMask & (((yDbMask)1)<<iDb))!=0 );
70622
70623  sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
70624  pOut->u.i = iMeta;
70625  break;
70626}
70627
70628/* Opcode: SetCookie P1 P2 P3 * *
70629**
70630** Write the content of register P3 (interpreted as an integer)
70631** into cookie number P2 of database P1.  P2==1 is the schema version.
70632** P2==2 is the database format. P2==3 is the recommended pager cache
70633** size, and so forth.  P1==0 is the main database file and P1==1 is the
70634** database file used to store temporary tables.
70635**
70636** A transaction must be started before executing this opcode.
70637*/
70638case OP_SetCookie: {       /* in3 */
70639  Db *pDb;
70640  assert( pOp->p2<SQLITE_N_BTREE_META );
70641  assert( pOp->p1>=0 && pOp->p1<db->nDb );
70642  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
70643  assert( p->readOnly==0 );
70644  pDb = &db->aDb[pOp->p1];
70645  assert( pDb->pBt!=0 );
70646  assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
70647  pIn3 = &aMem[pOp->p3];
70648  sqlite3VdbeMemIntegerify(pIn3);
70649  /* See note about index shifting on OP_ReadCookie */
70650  rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, (int)pIn3->u.i);
70651  if( pOp->p2==BTREE_SCHEMA_VERSION ){
70652    /* When the schema cookie changes, record the new cookie internally */
70653    pDb->pSchema->schema_cookie = (int)pIn3->u.i;
70654    db->flags |= SQLITE_InternChanges;
70655  }else if( pOp->p2==BTREE_FILE_FORMAT ){
70656    /* Record changes in the file format */
70657    pDb->pSchema->file_format = (u8)pIn3->u.i;
70658  }
70659  if( pOp->p1==1 ){
70660    /* Invalidate all prepared statements whenever the TEMP database
70661    ** schema is changed.  Ticket #1644 */
70662    sqlite3ExpirePreparedStatements(db);
70663    p->expired = 0;
70664  }
70665  break;
70666}
70667
70668/* Opcode: OpenRead P1 P2 P3 P4 P5
70669** Synopsis: root=P2 iDb=P3
70670**
70671** Open a read-only cursor for the database table whose root page is
70672** P2 in a database file.  The database file is determined by P3.
70673** P3==0 means the main database, P3==1 means the database used for
70674** temporary tables, and P3>1 means used the corresponding attached
70675** database.  Give the new cursor an identifier of P1.  The P1
70676** values need not be contiguous but all P1 values should be small integers.
70677** It is an error for P1 to be negative.
70678**
70679** If P5!=0 then use the content of register P2 as the root page, not
70680** the value of P2 itself.
70681**
70682** There will be a read lock on the database whenever there is an
70683** open cursor.  If the database was unlocked prior to this instruction
70684** then a read lock is acquired as part of this instruction.  A read
70685** lock allows other processes to read the database but prohibits
70686** any other process from modifying the database.  The read lock is
70687** released when all cursors are closed.  If this instruction attempts
70688** to get a read lock but fails, the script terminates with an
70689** SQLITE_BUSY error code.
70690**
70691** The P4 value may be either an integer (P4_INT32) or a pointer to
70692** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
70693** structure, then said structure defines the content and collating
70694** sequence of the index being opened. Otherwise, if P4 is an integer
70695** value, it is set to the number of columns in the table.
70696**
70697** See also OpenWrite.
70698*/
70699/* Opcode: OpenWrite P1 P2 P3 P4 P5
70700** Synopsis: root=P2 iDb=P3
70701**
70702** Open a read/write cursor named P1 on the table or index whose root
70703** page is P2.  Or if P5!=0 use the content of register P2 to find the
70704** root page.
70705**
70706** The P4 value may be either an integer (P4_INT32) or a pointer to
70707** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
70708** structure, then said structure defines the content and collating
70709** sequence of the index being opened. Otherwise, if P4 is an integer
70710** value, it is set to the number of columns in the table, or to the
70711** largest index of any column of the table that is actually used.
70712**
70713** This instruction works just like OpenRead except that it opens the cursor
70714** in read/write mode.  For a given table, there can be one or more read-only
70715** cursors or a single read/write cursor but not both.
70716**
70717** See also OpenRead.
70718*/
70719case OP_OpenRead:
70720case OP_OpenWrite: {
70721  int nField;
70722  KeyInfo *pKeyInfo;
70723  int p2;
70724  int iDb;
70725  int wrFlag;
70726  Btree *pX;
70727  VdbeCursor *pCur;
70728  Db *pDb;
70729
70730  assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR))==pOp->p5 );
70731  assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 );
70732  assert( p->bIsReader );
70733  assert( pOp->opcode==OP_OpenRead || p->readOnly==0 );
70734
70735  if( p->expired ){
70736    rc = SQLITE_ABORT;
70737    break;
70738  }
70739
70740  nField = 0;
70741  pKeyInfo = 0;
70742  p2 = pOp->p2;
70743  iDb = pOp->p3;
70744  assert( iDb>=0 && iDb<db->nDb );
70745  assert( (p->btreeMask & (((yDbMask)1)<<iDb))!=0 );
70746  pDb = &db->aDb[iDb];
70747  pX = pDb->pBt;
70748  assert( pX!=0 );
70749  if( pOp->opcode==OP_OpenWrite ){
70750    wrFlag = 1;
70751    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
70752    if( pDb->pSchema->file_format < p->minWriteFileFormat ){
70753      p->minWriteFileFormat = pDb->pSchema->file_format;
70754    }
70755  }else{
70756    wrFlag = 0;
70757  }
70758  if( pOp->p5 & OPFLAG_P2ISREG ){
70759    assert( p2>0 );
70760    assert( p2<=(p->nMem-p->nCursor) );
70761    pIn2 = &aMem[p2];
70762    assert( memIsValid(pIn2) );
70763    assert( (pIn2->flags & MEM_Int)!=0 );
70764    sqlite3VdbeMemIntegerify(pIn2);
70765    p2 = (int)pIn2->u.i;
70766    /* The p2 value always comes from a prior OP_CreateTable opcode and
70767    ** that opcode will always set the p2 value to 2 or more or else fail.
70768    ** If there were a failure, the prepared statement would have halted
70769    ** before reaching this instruction. */
70770    if( NEVER(p2<2) ) {
70771      rc = SQLITE_CORRUPT_BKPT;
70772      goto abort_due_to_error;
70773    }
70774  }
70775  if( pOp->p4type==P4_KEYINFO ){
70776    pKeyInfo = pOp->p4.pKeyInfo;
70777    assert( pKeyInfo->enc==ENC(db) );
70778    assert( pKeyInfo->db==db );
70779    nField = pKeyInfo->nField+pKeyInfo->nXField;
70780  }else if( pOp->p4type==P4_INT32 ){
70781    nField = pOp->p4.i;
70782  }
70783  assert( pOp->p1>=0 );
70784  assert( nField>=0 );
70785  testcase( nField==0 );  /* Table with INTEGER PRIMARY KEY and nothing else */
70786  pCur = allocateCursor(p, pOp->p1, nField, iDb, 1);
70787  if( pCur==0 ) goto no_mem;
70788  pCur->nullRow = 1;
70789  pCur->isOrdered = 1;
70790  rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->pCursor);
70791  pCur->pKeyInfo = pKeyInfo;
70792  assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
70793  sqlite3BtreeCursorHints(pCur->pCursor, (pOp->p5 & OPFLAG_BULKCSR));
70794
70795  /* Since it performs no memory allocation or IO, the only value that
70796  ** sqlite3BtreeCursor() may return is SQLITE_OK. */
70797  assert( rc==SQLITE_OK );
70798
70799  /* Set the VdbeCursor.isTable variable. Previous versions of
70800  ** SQLite used to check if the root-page flags were sane at this point
70801  ** and report database corruption if they were not, but this check has
70802  ** since moved into the btree layer.  */
70803  pCur->isTable = pOp->p4type!=P4_KEYINFO;
70804  break;
70805}
70806
70807/* Opcode: OpenEphemeral P1 P2 * P4 P5
70808** Synopsis: nColumn=P2
70809**
70810** Open a new cursor P1 to a transient table.
70811** The cursor is always opened read/write even if
70812** the main database is read-only.  The ephemeral
70813** table is deleted automatically when the cursor is closed.
70814**
70815** P2 is the number of columns in the ephemeral table.
70816** The cursor points to a BTree table if P4==0 and to a BTree index
70817** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
70818** that defines the format of keys in the index.
70819**
70820** The P5 parameter can be a mask of the BTREE_* flags defined
70821** in btree.h.  These flags control aspects of the operation of
70822** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
70823** added automatically.
70824*/
70825/* Opcode: OpenAutoindex P1 P2 * P4 *
70826** Synopsis: nColumn=P2
70827**
70828** This opcode works the same as OP_OpenEphemeral.  It has a
70829** different name to distinguish its use.  Tables created using
70830** by this opcode will be used for automatically created transient
70831** indices in joins.
70832*/
70833case OP_OpenAutoindex:
70834case OP_OpenEphemeral: {
70835  VdbeCursor *pCx;
70836  KeyInfo *pKeyInfo;
70837
70838  static const int vfsFlags =
70839      SQLITE_OPEN_READWRITE |
70840      SQLITE_OPEN_CREATE |
70841      SQLITE_OPEN_EXCLUSIVE |
70842      SQLITE_OPEN_DELETEONCLOSE |
70843      SQLITE_OPEN_TRANSIENT_DB;
70844  assert( pOp->p1>=0 );
70845  assert( pOp->p2>=0 );
70846  pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
70847  if( pCx==0 ) goto no_mem;
70848  pCx->nullRow = 1;
70849  pCx->isEphemeral = 1;
70850  rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBt,
70851                        BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
70852  if( rc==SQLITE_OK ){
70853    rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
70854  }
70855  if( rc==SQLITE_OK ){
70856    /* If a transient index is required, create it by calling
70857    ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
70858    ** opening it. If a transient table is required, just use the
70859    ** automatically created table with root-page 1 (an BLOB_INTKEY table).
70860    */
70861    if( (pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
70862      int pgno;
70863      assert( pOp->p4type==P4_KEYINFO );
70864      rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
70865      if( rc==SQLITE_OK ){
70866        assert( pgno==MASTER_ROOT+1 );
70867        assert( pKeyInfo->db==db );
70868        assert( pKeyInfo->enc==ENC(db) );
70869        pCx->pKeyInfo = pKeyInfo;
70870        rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, pKeyInfo, pCx->pCursor);
70871      }
70872      pCx->isTable = 0;
70873    }else{
70874      rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, pCx->pCursor);
70875      pCx->isTable = 1;
70876    }
70877  }
70878  pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
70879  break;
70880}
70881
70882/* Opcode: SorterOpen P1 P2 * P4 *
70883**
70884** This opcode works like OP_OpenEphemeral except that it opens
70885** a transient index that is specifically designed to sort large
70886** tables using an external merge-sort algorithm.
70887*/
70888case OP_SorterOpen: {
70889  VdbeCursor *pCx;
70890
70891  assert( pOp->p1>=0 );
70892  assert( pOp->p2>=0 );
70893  pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
70894  if( pCx==0 ) goto no_mem;
70895  pCx->pKeyInfo = pOp->p4.pKeyInfo;
70896  assert( pCx->pKeyInfo->db==db );
70897  assert( pCx->pKeyInfo->enc==ENC(db) );
70898  rc = sqlite3VdbeSorterInit(db, pCx);
70899  break;
70900}
70901
70902/* Opcode: OpenPseudo P1 P2 P3 * *
70903** Synopsis: P3 columns in r[P2]
70904**
70905** Open a new cursor that points to a fake table that contains a single
70906** row of data.  The content of that one row is the content of memory
70907** register P2.  In other words, cursor P1 becomes an alias for the
70908** MEM_Blob content contained in register P2.
70909**
70910** A pseudo-table created by this opcode is used to hold a single
70911** row output from the sorter so that the row can be decomposed into
70912** individual columns using the OP_Column opcode.  The OP_Column opcode
70913** is the only cursor opcode that works with a pseudo-table.
70914**
70915** P3 is the number of fields in the records that will be stored by
70916** the pseudo-table.
70917*/
70918case OP_OpenPseudo: {
70919  VdbeCursor *pCx;
70920
70921  assert( pOp->p1>=0 );
70922  assert( pOp->p3>=0 );
70923  pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
70924  if( pCx==0 ) goto no_mem;
70925  pCx->nullRow = 1;
70926  pCx->pseudoTableReg = pOp->p2;
70927  pCx->isTable = 1;
70928  assert( pOp->p5==0 );
70929  break;
70930}
70931
70932/* Opcode: Close P1 * * * *
70933**
70934** Close a cursor previously opened as P1.  If P1 is not
70935** currently open, this instruction is a no-op.
70936*/
70937case OP_Close: {
70938  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70939  sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
70940  p->apCsr[pOp->p1] = 0;
70941  break;
70942}
70943
70944/* Opcode: SeekGe P1 P2 P3 P4 *
70945** Synopsis: key=r[P3@P4]
70946**
70947** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
70948** use the value in register P3 as the key.  If cursor P1 refers
70949** to an SQL index, then P3 is the first in an array of P4 registers
70950** that are used as an unpacked index key.
70951**
70952** Reposition cursor P1 so that  it points to the smallest entry that
70953** is greater than or equal to the key value. If there are no records
70954** greater than or equal to the key and P2 is not zero, then jump to P2.
70955**
70956** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
70957*/
70958/* Opcode: SeekGt P1 P2 P3 P4 *
70959** Synopsis: key=r[P3@P4]
70960**
70961** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
70962** use the value in register P3 as a key. If cursor P1 refers
70963** to an SQL index, then P3 is the first in an array of P4 registers
70964** that are used as an unpacked index key.
70965**
70966** Reposition cursor P1 so that  it points to the smallest entry that
70967** is greater than the key value. If there are no records greater than
70968** the key and P2 is not zero, then jump to P2.
70969**
70970** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
70971*/
70972/* Opcode: SeekLt P1 P2 P3 P4 *
70973** Synopsis: key=r[P3@P4]
70974**
70975** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
70976** use the value in register P3 as a key. If cursor P1 refers
70977** to an SQL index, then P3 is the first in an array of P4 registers
70978** that are used as an unpacked index key.
70979**
70980** Reposition cursor P1 so that  it points to the largest entry that
70981** is less than the key value. If there are no records less than
70982** the key and P2 is not zero, then jump to P2.
70983**
70984** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
70985*/
70986/* Opcode: SeekLe P1 P2 P3 P4 *
70987** Synopsis: key=r[P3@P4]
70988**
70989** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
70990** use the value in register P3 as a key. If cursor P1 refers
70991** to an SQL index, then P3 is the first in an array of P4 registers
70992** that are used as an unpacked index key.
70993**
70994** Reposition cursor P1 so that it points to the largest entry that
70995** is less than or equal to the key value. If there are no records
70996** less than or equal to the key and P2 is not zero, then jump to P2.
70997**
70998** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
70999*/
71000case OP_SeekLT:         /* jump, in3 */
71001case OP_SeekLE:         /* jump, in3 */
71002case OP_SeekGE:         /* jump, in3 */
71003case OP_SeekGT: {       /* jump, in3 */
71004  int res;
71005  int oc;
71006  VdbeCursor *pC;
71007  UnpackedRecord r;
71008  int nField;
71009  i64 iKey;      /* The rowid we are to seek to */
71010
71011  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
71012  assert( pOp->p2!=0 );
71013  pC = p->apCsr[pOp->p1];
71014  assert( pC!=0 );
71015  assert( pC->pseudoTableReg==0 );
71016  assert( OP_SeekLE == OP_SeekLT+1 );
71017  assert( OP_SeekGE == OP_SeekLT+2 );
71018  assert( OP_SeekGT == OP_SeekLT+3 );
71019  assert( pC->isOrdered );
71020  assert( pC->pCursor!=0 );
71021  oc = pOp->opcode;
71022  pC->nullRow = 0;
71023  if( pC->isTable ){
71024    /* The input value in P3 might be of any type: integer, real, string,
71025    ** blob, or NULL.  But it needs to be an integer before we can do
71026    ** the seek, so covert it. */
71027    pIn3 = &aMem[pOp->p3];
71028    applyNumericAffinity(pIn3);
71029    iKey = sqlite3VdbeIntValue(pIn3);
71030    pC->rowidIsValid = 0;
71031
71032    /* If the P3 value could not be converted into an integer without
71033    ** loss of information, then special processing is required... */
71034    if( (pIn3->flags & MEM_Int)==0 ){
71035      if( (pIn3->flags & MEM_Real)==0 ){
71036        /* If the P3 value cannot be converted into any kind of a number,
71037        ** then the seek is not possible, so jump to P2 */
71038        pc = pOp->p2 - 1;  VdbeBranchTaken(1,2);
71039        break;
71040      }
71041
71042      /* If the approximation iKey is larger than the actual real search
71043      ** term, substitute >= for > and < for <=. e.g. if the search term
71044      ** is 4.9 and the integer approximation 5:
71045      **
71046      **        (x >  4.9)    ->     (x >= 5)
71047      **        (x <= 4.9)    ->     (x <  5)
71048      */
71049      if( pIn3->r<(double)iKey ){
71050        assert( OP_SeekGE==(OP_SeekGT-1) );
71051        assert( OP_SeekLT==(OP_SeekLE-1) );
71052        assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
71053        if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
71054      }
71055
71056      /* If the approximation iKey is smaller than the actual real search
71057      ** term, substitute <= for < and > for >=.  */
71058      else if( pIn3->r>(double)iKey ){
71059        assert( OP_SeekLE==(OP_SeekLT+1) );
71060        assert( OP_SeekGT==(OP_SeekGE+1) );
71061        assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
71062        if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
71063      }
71064    }
71065    rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)iKey, 0, &res);
71066    if( rc!=SQLITE_OK ){
71067      goto abort_due_to_error;
71068    }
71069    if( res==0 ){
71070      pC->rowidIsValid = 1;
71071      pC->lastRowid = iKey;
71072    }
71073  }else{
71074    nField = pOp->p4.i;
71075    assert( pOp->p4type==P4_INT32 );
71076    assert( nField>0 );
71077    r.pKeyInfo = pC->pKeyInfo;
71078    r.nField = (u16)nField;
71079
71080    /* The next line of code computes as follows, only faster:
71081    **   if( oc==OP_SeekGT || oc==OP_SeekLE ){
71082    **     r.default_rc = -1;
71083    **   }else{
71084    **     r.default_rc = +1;
71085    **   }
71086    */
71087    r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
71088    assert( oc!=OP_SeekGT || r.default_rc==-1 );
71089    assert( oc!=OP_SeekLE || r.default_rc==-1 );
71090    assert( oc!=OP_SeekGE || r.default_rc==+1 );
71091    assert( oc!=OP_SeekLT || r.default_rc==+1 );
71092
71093    r.aMem = &aMem[pOp->p3];
71094#ifdef SQLITE_DEBUG
71095    { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
71096#endif
71097    ExpandBlob(r.aMem);
71098    rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, &r, 0, 0, &res);
71099    if( rc!=SQLITE_OK ){
71100      goto abort_due_to_error;
71101    }
71102    pC->rowidIsValid = 0;
71103  }
71104  pC->deferredMoveto = 0;
71105  pC->cacheStatus = CACHE_STALE;
71106#ifdef SQLITE_TEST
71107  sqlite3_search_count++;
71108#endif
71109  if( oc>=OP_SeekGE ){  assert( oc==OP_SeekGE || oc==OP_SeekGT );
71110    if( res<0 || (res==0 && oc==OP_SeekGT) ){
71111      res = 0;
71112      rc = sqlite3BtreeNext(pC->pCursor, &res);
71113      if( rc!=SQLITE_OK ) goto abort_due_to_error;
71114      pC->rowidIsValid = 0;
71115    }else{
71116      res = 0;
71117    }
71118  }else{
71119    assert( oc==OP_SeekLT || oc==OP_SeekLE );
71120    if( res>0 || (res==0 && oc==OP_SeekLT) ){
71121      res = 0;
71122      rc = sqlite3BtreePrevious(pC->pCursor, &res);
71123      if( rc!=SQLITE_OK ) goto abort_due_to_error;
71124      pC->rowidIsValid = 0;
71125    }else{
71126      /* res might be negative because the table is empty.  Check to
71127      ** see if this is the case.
71128      */
71129      res = sqlite3BtreeEof(pC->pCursor);
71130    }
71131  }
71132  assert( pOp->p2>0 );
71133  VdbeBranchTaken(res!=0,2);
71134  if( res ){
71135    pc = pOp->p2 - 1;
71136  }
71137  break;
71138}
71139
71140/* Opcode: Seek P1 P2 * * *
71141** Synopsis:  intkey=r[P2]
71142**
71143** P1 is an open table cursor and P2 is a rowid integer.  Arrange
71144** for P1 to move so that it points to the rowid given by P2.
71145**
71146** This is actually a deferred seek.  Nothing actually happens until
71147** the cursor is used to read a record.  That way, if no reads
71148** occur, no unnecessary I/O happens.
71149*/
71150case OP_Seek: {    /* in2 */
71151  VdbeCursor *pC;
71152
71153  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
71154  pC = p->apCsr[pOp->p1];
71155  assert( pC!=0 );
71156  assert( pC->pCursor!=0 );
71157  assert( pC->isTable );
71158  pC->nullRow = 0;
71159  pIn2 = &aMem[pOp->p2];
71160  pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
71161  pC->rowidIsValid = 0;
71162  pC->deferredMoveto = 1;
71163  break;
71164}
71165
71166
71167/* Opcode: Found P1 P2 P3 P4 *
71168** Synopsis: key=r[P3@P4]
71169**
71170** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
71171** P4>0 then register P3 is the first of P4 registers that form an unpacked
71172** record.
71173**
71174** Cursor P1 is on an index btree.  If the record identified by P3 and P4
71175** is a prefix of any entry in P1 then a jump is made to P2 and
71176** P1 is left pointing at the matching entry.
71177**
71178** See also: NotFound, NoConflict, NotExists. SeekGe
71179*/
71180/* Opcode: NotFound P1 P2 P3 P4 *
71181** Synopsis: key=r[P3@P4]
71182**
71183** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
71184** P4>0 then register P3 is the first of P4 registers that form an unpacked
71185** record.
71186**
71187** Cursor P1 is on an index btree.  If the record identified by P3 and P4
71188** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
71189** does contain an entry whose prefix matches the P3/P4 record then control
71190** falls through to the next instruction and P1 is left pointing at the
71191** matching entry.
71192**
71193** See also: Found, NotExists, NoConflict
71194*/
71195/* Opcode: NoConflict P1 P2 P3 P4 *
71196** Synopsis: key=r[P3@P4]
71197**
71198** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
71199** P4>0 then register P3 is the first of P4 registers that form an unpacked
71200** record.
71201**
71202** Cursor P1 is on an index btree.  If the record identified by P3 and P4
71203** contains any NULL value, jump immediately to P2.  If all terms of the
71204** record are not-NULL then a check is done to determine if any row in the
71205** P1 index btree has a matching key prefix.  If there are no matches, jump
71206** immediately to P2.  If there is a match, fall through and leave the P1
71207** cursor pointing to the matching row.
71208**
71209** This opcode is similar to OP_NotFound with the exceptions that the
71210** branch is always taken if any part of the search key input is NULL.
71211**
71212** See also: NotFound, Found, NotExists
71213*/
71214case OP_NoConflict:     /* jump, in3 */
71215case OP_NotFound:       /* jump, in3 */
71216case OP_Found: {        /* jump, in3 */
71217  int alreadyExists;
71218  int ii;
71219  VdbeCursor *pC;
71220  int res;
71221  char *pFree;
71222  UnpackedRecord *pIdxKey;
71223  UnpackedRecord r;
71224  char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*4 + 7];
71225
71226#ifdef SQLITE_TEST
71227  if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
71228#endif
71229
71230  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
71231  assert( pOp->p4type==P4_INT32 );
71232  pC = p->apCsr[pOp->p1];
71233  assert( pC!=0 );
71234  pIn3 = &aMem[pOp->p3];
71235  assert( pC->pCursor!=0 );
71236  assert( pC->isTable==0 );
71237  pFree = 0;  /* Not needed.  Only used to suppress a compiler warning. */
71238  if( pOp->p4.i>0 ){
71239    r.pKeyInfo = pC->pKeyInfo;
71240    r.nField = (u16)pOp->p4.i;
71241    r.aMem = pIn3;
71242    for(ii=0; ii<r.nField; ii++){
71243      assert( memIsValid(&r.aMem[ii]) );
71244      ExpandBlob(&r.aMem[ii]);
71245#ifdef SQLITE_DEBUG
71246      if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
71247#endif
71248    }
71249    pIdxKey = &r;
71250  }else{
71251    pIdxKey = sqlite3VdbeAllocUnpackedRecord(
71252        pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree
71253    );
71254    if( pIdxKey==0 ) goto no_mem;
71255    assert( pIn3->flags & MEM_Blob );
71256    assert( (pIn3->flags & MEM_Zero)==0 );  /* zeroblobs already expanded */
71257    sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
71258  }
71259  pIdxKey->default_rc = 0;
71260  if( pOp->opcode==OP_NoConflict ){
71261    /* For the OP_NoConflict opcode, take the jump if any of the
71262    ** input fields are NULL, since any key with a NULL will not
71263    ** conflict */
71264    for(ii=0; ii<r.nField; ii++){
71265      if( r.aMem[ii].flags & MEM_Null ){
71266        pc = pOp->p2 - 1; VdbeBranchTaken(1,2);
71267        break;
71268      }
71269    }
71270  }
71271  rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, pIdxKey, 0, 0, &res);
71272  if( pOp->p4.i==0 ){
71273    sqlite3DbFree(db, pFree);
71274  }
71275  if( rc!=SQLITE_OK ){
71276    break;
71277  }
71278  pC->seekResult = res;
71279  alreadyExists = (res==0);
71280  pC->nullRow = 1-alreadyExists;
71281  pC->deferredMoveto = 0;
71282  pC->cacheStatus = CACHE_STALE;
71283  if( pOp->opcode==OP_Found ){
71284    VdbeBranchTaken(alreadyExists!=0,2);
71285    if( alreadyExists ) pc = pOp->p2 - 1;
71286  }else{
71287    VdbeBranchTaken(alreadyExists==0,2);
71288    if( !alreadyExists ) pc = pOp->p2 - 1;
71289  }
71290  break;
71291}
71292
71293/* Opcode: NotExists P1 P2 P3 * *
71294** Synopsis: intkey=r[P3]
71295**
71296** P1 is the index of a cursor open on an SQL table btree (with integer
71297** keys).  P3 is an integer rowid.  If P1 does not contain a record with
71298** rowid P3 then jump immediately to P2.  If P1 does contain a record
71299** with rowid P3 then leave the cursor pointing at that record and fall
71300** through to the next instruction.
71301**
71302** The OP_NotFound opcode performs the same operation on index btrees
71303** (with arbitrary multi-value keys).
71304**
71305** See also: Found, NotFound, NoConflict
71306*/
71307case OP_NotExists: {        /* jump, in3 */
71308  VdbeCursor *pC;
71309  BtCursor *pCrsr;
71310  int res;
71311  u64 iKey;
71312
71313  pIn3 = &aMem[pOp->p3];
71314  assert( pIn3->flags & MEM_Int );
71315  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
71316  pC = p->apCsr[pOp->p1];
71317  assert( pC!=0 );
71318  assert( pC->isTable );
71319  assert( pC->pseudoTableReg==0 );
71320  pCrsr = pC->pCursor;
71321  assert( pCrsr!=0 );
71322  res = 0;
71323  iKey = pIn3->u.i;
71324  rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
71325  pC->lastRowid = pIn3->u.i;
71326  pC->rowidIsValid = res==0 ?1:0;
71327  pC->nullRow = 0;
71328  pC->cacheStatus = CACHE_STALE;
71329  pC->deferredMoveto = 0;
71330  VdbeBranchTaken(res!=0,2);
71331  if( res!=0 ){
71332    pc = pOp->p2 - 1;
71333    assert( pC->rowidIsValid==0 );
71334  }
71335  pC->seekResult = res;
71336  break;
71337}
71338
71339/* Opcode: Sequence P1 P2 * * *
71340** Synopsis: r[P2]=cursor[P1].ctr++
71341**
71342** Find the next available sequence number for cursor P1.
71343** Write the sequence number into register P2.
71344** The sequence number on the cursor is incremented after this
71345** instruction.
71346*/
71347case OP_Sequence: {           /* out2-prerelease */
71348  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
71349  assert( p->apCsr[pOp->p1]!=0 );
71350  pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
71351  break;
71352}
71353
71354
71355/* Opcode: NewRowid P1 P2 P3 * *
71356** Synopsis: r[P2]=rowid
71357**
71358** Get a new integer record number (a.k.a "rowid") used as the key to a table.
71359** The record number is not previously used as a key in the database
71360** table that cursor P1 points to.  The new record number is written
71361** written to register P2.
71362**
71363** If P3>0 then P3 is a register in the root frame of this VDBE that holds
71364** the largest previously generated record number. No new record numbers are
71365** allowed to be less than this value. When this value reaches its maximum,
71366** an SQLITE_FULL error is generated. The P3 register is updated with the '
71367** generated record number. This P3 mechanism is used to help implement the
71368** AUTOINCREMENT feature.
71369*/
71370case OP_NewRowid: {           /* out2-prerelease */
71371  i64 v;                 /* The new rowid */
71372  VdbeCursor *pC;        /* Cursor of table to get the new rowid */
71373  int res;               /* Result of an sqlite3BtreeLast() */
71374  int cnt;               /* Counter to limit the number of searches */
71375  Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
71376  VdbeFrame *pFrame;     /* Root frame of VDBE */
71377
71378  v = 0;
71379  res = 0;
71380  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
71381  pC = p->apCsr[pOp->p1];
71382  assert( pC!=0 );
71383  if( NEVER(pC->pCursor==0) ){
71384    /* The zero initialization above is all that is needed */
71385  }else{
71386    /* The next rowid or record number (different terms for the same
71387    ** thing) is obtained in a two-step algorithm.
71388    **
71389    ** First we attempt to find the largest existing rowid and add one
71390    ** to that.  But if the largest existing rowid is already the maximum
71391    ** positive integer, we have to fall through to the second
71392    ** probabilistic algorithm
71393    **
71394    ** The second algorithm is to select a rowid at random and see if
71395    ** it already exists in the table.  If it does not exist, we have
71396    ** succeeded.  If the random rowid does exist, we select a new one
71397    ** and try again, up to 100 times.
71398    */
71399    assert( pC->isTable );
71400
71401#ifdef SQLITE_32BIT_ROWID
71402#   define MAX_ROWID 0x7fffffff
71403#else
71404    /* Some compilers complain about constants of the form 0x7fffffffffffffff.
71405    ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
71406    ** to provide the constant while making all compilers happy.
71407    */
71408#   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
71409#endif
71410
71411    if( !pC->useRandomRowid ){
71412      rc = sqlite3BtreeLast(pC->pCursor, &res);
71413      if( rc!=SQLITE_OK ){
71414        goto abort_due_to_error;
71415      }
71416      if( res ){
71417        v = 1;   /* IMP: R-61914-48074 */
71418      }else{
71419        assert( sqlite3BtreeCursorIsValid(pC->pCursor) );
71420        rc = sqlite3BtreeKeySize(pC->pCursor, &v);
71421        assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
71422        if( v>=MAX_ROWID ){
71423          pC->useRandomRowid = 1;
71424        }else{
71425          v++;   /* IMP: R-29538-34987 */
71426        }
71427      }
71428    }
71429
71430#ifndef SQLITE_OMIT_AUTOINCREMENT
71431    if( pOp->p3 ){
71432      /* Assert that P3 is a valid memory cell. */
71433      assert( pOp->p3>0 );
71434      if( p->pFrame ){
71435        for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
71436        /* Assert that P3 is a valid memory cell. */
71437        assert( pOp->p3<=pFrame->nMem );
71438        pMem = &pFrame->aMem[pOp->p3];
71439      }else{
71440        /* Assert that P3 is a valid memory cell. */
71441        assert( pOp->p3<=(p->nMem-p->nCursor) );
71442        pMem = &aMem[pOp->p3];
71443        memAboutToChange(p, pMem);
71444      }
71445      assert( memIsValid(pMem) );
71446
71447      REGISTER_TRACE(pOp->p3, pMem);
71448      sqlite3VdbeMemIntegerify(pMem);
71449      assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
71450      if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
71451        rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
71452        goto abort_due_to_error;
71453      }
71454      if( v<pMem->u.i+1 ){
71455        v = pMem->u.i + 1;
71456      }
71457      pMem->u.i = v;
71458    }
71459#endif
71460    if( pC->useRandomRowid ){
71461      /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
71462      ** largest possible integer (9223372036854775807) then the database
71463      ** engine starts picking positive candidate ROWIDs at random until
71464      ** it finds one that is not previously used. */
71465      assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
71466                             ** an AUTOINCREMENT table. */
71467      /* on the first attempt, simply do one more than previous */
71468      v = lastRowid;
71469      v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
71470      v++; /* ensure non-zero */
71471      cnt = 0;
71472      while(   ((rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)v,
71473                                                 0, &res))==SQLITE_OK)
71474            && (res==0)
71475            && (++cnt<100)){
71476        /* collision - try another random rowid */
71477        sqlite3_randomness(sizeof(v), &v);
71478        if( cnt<5 ){
71479          /* try "small" random rowids for the initial attempts */
71480          v &= 0xffffff;
71481        }else{
71482          v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
71483        }
71484        v++; /* ensure non-zero */
71485      }
71486      if( rc==SQLITE_OK && res==0 ){
71487        rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
71488        goto abort_due_to_error;
71489      }
71490      assert( v>0 );  /* EV: R-40812-03570 */
71491    }
71492    pC->rowidIsValid = 0;
71493    pC->deferredMoveto = 0;
71494    pC->cacheStatus = CACHE_STALE;
71495  }
71496  pOut->u.i = v;
71497  break;
71498}
71499
71500/* Opcode: Insert P1 P2 P3 P4 P5
71501** Synopsis: intkey=r[P3] data=r[P2]
71502**
71503** Write an entry into the table of cursor P1.  A new entry is
71504** created if it doesn't already exist or the data for an existing
71505** entry is overwritten.  The data is the value MEM_Blob stored in register
71506** number P2. The key is stored in register P3. The key must
71507** be a MEM_Int.
71508**
71509** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
71510** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
71511** then rowid is stored for subsequent return by the
71512** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
71513**
71514** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
71515** the last seek operation (OP_NotExists) was a success, then this
71516** operation will not attempt to find the appropriate row before doing
71517** the insert but will instead overwrite the row that the cursor is
71518** currently pointing to.  Presumably, the prior OP_NotExists opcode
71519** has already positioned the cursor correctly.  This is an optimization
71520** that boosts performance by avoiding redundant seeks.
71521**
71522** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
71523** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
71524** is part of an INSERT operation.  The difference is only important to
71525** the update hook.
71526**
71527** Parameter P4 may point to a string containing the table-name, or
71528** may be NULL. If it is not NULL, then the update-hook
71529** (sqlite3.xUpdateCallback) is invoked following a successful insert.
71530**
71531** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
71532** allocated, then ownership of P2 is transferred to the pseudo-cursor
71533** and register P2 becomes ephemeral.  If the cursor is changed, the
71534** value of register P2 will then change.  Make sure this does not
71535** cause any problems.)
71536**
71537** This instruction only works on tables.  The equivalent instruction
71538** for indices is OP_IdxInsert.
71539*/
71540/* Opcode: InsertInt P1 P2 P3 P4 P5
71541** Synopsis:  intkey=P3 data=r[P2]
71542**
71543** This works exactly like OP_Insert except that the key is the
71544** integer value P3, not the value of the integer stored in register P3.
71545*/
71546case OP_Insert:
71547case OP_InsertInt: {
71548  Mem *pData;       /* MEM cell holding data for the record to be inserted */
71549  Mem *pKey;        /* MEM cell holding key  for the record */
71550  i64 iKey;         /* The integer ROWID or key for the record to be inserted */
71551  VdbeCursor *pC;   /* Cursor to table into which insert is written */
71552  int nZero;        /* Number of zero-bytes to append */
71553  int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
71554  const char *zDb;  /* database name - used by the update hook */
71555  const char *zTbl; /* Table name - used by the opdate hook */
71556  int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
71557
71558  pData = &aMem[pOp->p2];
71559  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
71560  assert( memIsValid(pData) );
71561  pC = p->apCsr[pOp->p1];
71562  assert( pC!=0 );
71563  assert( pC->pCursor!=0 );
71564  assert( pC->pseudoTableReg==0 );
71565  assert( pC->isTable );
71566  REGISTER_TRACE(pOp->p2, pData);
71567
71568  if( pOp->opcode==OP_Insert ){
71569    pKey = &aMem[pOp->p3];
71570    assert( pKey->flags & MEM_Int );
71571    assert( memIsValid(pKey) );
71572    REGISTER_TRACE(pOp->p3, pKey);
71573    iKey = pKey->u.i;
71574  }else{
71575    assert( pOp->opcode==OP_InsertInt );
71576    iKey = pOp->p3;
71577  }
71578
71579  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
71580  if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = iKey;
71581  if( pData->flags & MEM_Null ){
71582    pData->z = 0;
71583    pData->n = 0;
71584  }else{
71585    assert( pData->flags & (MEM_Blob|MEM_Str) );
71586  }
71587  seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
71588  if( pData->flags & MEM_Zero ){
71589    nZero = pData->u.nZero;
71590  }else{
71591    nZero = 0;
71592  }
71593  rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
71594                          pData->z, pData->n, nZero,
71595                          (pOp->p5 & OPFLAG_APPEND)!=0, seekResult
71596  );
71597  pC->rowidIsValid = 0;
71598  pC->deferredMoveto = 0;
71599  pC->cacheStatus = CACHE_STALE;
71600
71601  /* Invoke the update-hook if required. */
71602  if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
71603    zDb = db->aDb[pC->iDb].zName;
71604    zTbl = pOp->p4.z;
71605    op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
71606    assert( pC->isTable );
71607    db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
71608    assert( pC->iDb>=0 );
71609  }
71610  break;
71611}
71612
71613/* Opcode: Delete P1 P2 * P4 *
71614**
71615** Delete the record at which the P1 cursor is currently pointing.
71616**
71617** The cursor will be left pointing at either the next or the previous
71618** record in the table. If it is left pointing at the next record, then
71619** the next Next instruction will be a no-op.  Hence it is OK to delete
71620** a record from within an Next loop.
71621**
71622** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
71623** incremented (otherwise not).
71624**
71625** P1 must not be pseudo-table.  It has to be a real table with
71626** multiple rows.
71627**
71628** If P4 is not NULL, then it is the name of the table that P1 is
71629** pointing to.  The update hook will be invoked, if it exists.
71630** If P4 is not NULL then the P1 cursor must have been positioned
71631** using OP_NotFound prior to invoking this opcode.
71632*/
71633case OP_Delete: {
71634  i64 iKey;
71635  VdbeCursor *pC;
71636
71637  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
71638  pC = p->apCsr[pOp->p1];
71639  assert( pC!=0 );
71640  assert( pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
71641  iKey = pC->lastRowid;      /* Only used for the update hook */
71642
71643  /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
71644  ** OP_Column on the same table without any intervening operations that
71645  ** might move or invalidate the cursor.  Hence cursor pC is always pointing
71646  ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
71647  ** below is always a no-op and cannot fail.  We will run it anyhow, though,
71648  ** to guard against future changes to the code generator.
71649  **/
71650  assert( pC->deferredMoveto==0 );
71651  rc = sqlite3VdbeCursorMoveto(pC);
71652  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
71653
71654  rc = sqlite3BtreeDelete(pC->pCursor);
71655  pC->cacheStatus = CACHE_STALE;
71656
71657  /* Invoke the update-hook if required. */
71658  if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z && pC->isTable ){
71659    db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE,
71660                        db->aDb[pC->iDb].zName, pOp->p4.z, iKey);
71661    assert( pC->iDb>=0 );
71662  }
71663  if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
71664  break;
71665}
71666/* Opcode: ResetCount * * * * *
71667**
71668** The value of the change counter is copied to the database handle
71669** change counter (returned by subsequent calls to sqlite3_changes()).
71670** Then the VMs internal change counter resets to 0.
71671** This is used by trigger programs.
71672*/
71673case OP_ResetCount: {
71674  sqlite3VdbeSetChanges(db, p->nChange);
71675  p->nChange = 0;
71676  break;
71677}
71678
71679/* Opcode: SorterCompare P1 P2 P3 P4
71680** Synopsis:  if key(P1)!=rtrim(r[P3],P4) goto P2
71681**
71682** P1 is a sorter cursor. This instruction compares a prefix of the
71683** the record blob in register P3 against a prefix of the entry that
71684** the sorter cursor currently points to.  The final P4 fields of both
71685** the P3 and sorter record are ignored.
71686**
71687** If either P3 or the sorter contains a NULL in one of their significant
71688** fields (not counting the P4 fields at the end which are ignored) then
71689** the comparison is assumed to be equal.
71690**
71691** Fall through to next instruction if the two records compare equal to
71692** each other.  Jump to P2 if they are different.
71693*/
71694case OP_SorterCompare: {
71695  VdbeCursor *pC;
71696  int res;
71697  int nIgnore;
71698
71699  pC = p->apCsr[pOp->p1];
71700  assert( isSorter(pC) );
71701  assert( pOp->p4type==P4_INT32 );
71702  pIn3 = &aMem[pOp->p3];
71703  nIgnore = pOp->p4.i;
71704  rc = sqlite3VdbeSorterCompare(pC, pIn3, nIgnore, &res);
71705  VdbeBranchTaken(res!=0,2);
71706  if( res ){
71707    pc = pOp->p2-1;
71708  }
71709  break;
71710};
71711
71712/* Opcode: SorterData P1 P2 * * *
71713** Synopsis: r[P2]=data
71714**
71715** Write into register P2 the current sorter data for sorter cursor P1.
71716*/
71717case OP_SorterData: {
71718  VdbeCursor *pC;
71719
71720  pOut = &aMem[pOp->p2];
71721  pC = p->apCsr[pOp->p1];
71722  assert( isSorter(pC) );
71723  rc = sqlite3VdbeSorterRowkey(pC, pOut);
71724  assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
71725  break;
71726}
71727
71728/* Opcode: RowData P1 P2 * * *
71729** Synopsis: r[P2]=data
71730**
71731** Write into register P2 the complete row data for cursor P1.
71732** There is no interpretation of the data.
71733** It is just copied onto the P2 register exactly as
71734** it is found in the database file.
71735**
71736** If the P1 cursor must be pointing to a valid row (not a NULL row)
71737** of a real table, not a pseudo-table.
71738*/
71739/* Opcode: RowKey P1 P2 * * *
71740** Synopsis: r[P2]=key
71741**
71742** Write into register P2 the complete row key for cursor P1.
71743** There is no interpretation of the data.
71744** The key is copied onto the P2 register exactly as
71745** it is found in the database file.
71746**
71747** If the P1 cursor must be pointing to a valid row (not a NULL row)
71748** of a real table, not a pseudo-table.
71749*/
71750case OP_RowKey:
71751case OP_RowData: {
71752  VdbeCursor *pC;
71753  BtCursor *pCrsr;
71754  u32 n;
71755  i64 n64;
71756
71757  pOut = &aMem[pOp->p2];
71758  memAboutToChange(p, pOut);
71759
71760  /* Note that RowKey and RowData are really exactly the same instruction */
71761  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
71762  pC = p->apCsr[pOp->p1];
71763  assert( isSorter(pC)==0 );
71764  assert( pC->isTable || pOp->opcode!=OP_RowData );
71765  assert( pC->isTable==0 || pOp->opcode==OP_RowData );
71766  assert( pC!=0 );
71767  assert( pC->nullRow==0 );
71768  assert( pC->pseudoTableReg==0 );
71769  assert( pC->pCursor!=0 );
71770  pCrsr = pC->pCursor;
71771  assert( sqlite3BtreeCursorIsValid(pCrsr) );
71772
71773  /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
71774  ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
71775  ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
71776  ** a no-op and can never fail.  But we leave it in place as a safety.
71777  */
71778  assert( pC->deferredMoveto==0 );
71779  rc = sqlite3VdbeCursorMoveto(pC);
71780  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
71781
71782  if( pC->isTable==0 ){
71783    assert( !pC->isTable );
71784    VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &n64);
71785    assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
71786    if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
71787      goto too_big;
71788    }
71789    n = (u32)n64;
71790  }else{
71791    VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &n);
71792    assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
71793    if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
71794      goto too_big;
71795    }
71796  }
71797  if( sqlite3VdbeMemGrow(pOut, n, 0) ){
71798    goto no_mem;
71799  }
71800  pOut->n = n;
71801  MemSetTypeFlag(pOut, MEM_Blob);
71802  if( pC->isTable==0 ){
71803    rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
71804  }else{
71805    rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
71806  }
71807  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
71808  UPDATE_MAX_BLOBSIZE(pOut);
71809  REGISTER_TRACE(pOp->p2, pOut);
71810  break;
71811}
71812
71813/* Opcode: Rowid P1 P2 * * *
71814** Synopsis: r[P2]=rowid
71815**
71816** Store in register P2 an integer which is the key of the table entry that
71817** P1 is currently point to.
71818**
71819** P1 can be either an ordinary table or a virtual table.  There used to
71820** be a separate OP_VRowid opcode for use with virtual tables, but this
71821** one opcode now works for both table types.
71822*/
71823case OP_Rowid: {                 /* out2-prerelease */
71824  VdbeCursor *pC;
71825  i64 v;
71826  sqlite3_vtab *pVtab;
71827  const sqlite3_module *pModule;
71828
71829  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
71830  pC = p->apCsr[pOp->p1];
71831  assert( pC!=0 );
71832  assert( pC->pseudoTableReg==0 || pC->nullRow );
71833  if( pC->nullRow ){
71834    pOut->flags = MEM_Null;
71835    break;
71836  }else if( pC->deferredMoveto ){
71837    v = pC->movetoTarget;
71838#ifndef SQLITE_OMIT_VIRTUALTABLE
71839  }else if( pC->pVtabCursor ){
71840    pVtab = pC->pVtabCursor->pVtab;
71841    pModule = pVtab->pModule;
71842    assert( pModule->xRowid );
71843    rc = pModule->xRowid(pC->pVtabCursor, &v);
71844    sqlite3VtabImportErrmsg(p, pVtab);
71845#endif /* SQLITE_OMIT_VIRTUALTABLE */
71846  }else{
71847    assert( pC->pCursor!=0 );
71848    rc = sqlite3VdbeCursorMoveto(pC);
71849    if( rc ) goto abort_due_to_error;
71850    if( pC->rowidIsValid ){
71851      v = pC->lastRowid;
71852    }else{
71853      rc = sqlite3BtreeKeySize(pC->pCursor, &v);
71854      assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
71855    }
71856  }
71857  pOut->u.i = v;
71858  break;
71859}
71860
71861/* Opcode: NullRow P1 * * * *
71862**
71863** Move the cursor P1 to a null row.  Any OP_Column operations
71864** that occur while the cursor is on the null row will always
71865** write a NULL.
71866*/
71867case OP_NullRow: {
71868  VdbeCursor *pC;
71869
71870  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
71871  pC = p->apCsr[pOp->p1];
71872  assert( pC!=0 );
71873  pC->nullRow = 1;
71874  pC->rowidIsValid = 0;
71875  pC->cacheStatus = CACHE_STALE;
71876  if( pC->pCursor ){
71877    sqlite3BtreeClearCursor(pC->pCursor);
71878  }
71879  break;
71880}
71881
71882/* Opcode: Last P1 P2 * * *
71883**
71884** The next use of the Rowid or Column or Next instruction for P1
71885** will refer to the last entry in the database table or index.
71886** If the table or index is empty and P2>0, then jump immediately to P2.
71887** If P2 is 0 or if the table or index is not empty, fall through
71888** to the following instruction.
71889*/
71890case OP_Last: {        /* jump */
71891  VdbeCursor *pC;
71892  BtCursor *pCrsr;
71893  int res;
71894
71895  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
71896  pC = p->apCsr[pOp->p1];
71897  assert( pC!=0 );
71898  pCrsr = pC->pCursor;
71899  res = 0;
71900  assert( pCrsr!=0 );
71901  rc = sqlite3BtreeLast(pCrsr, &res);
71902  pC->nullRow = (u8)res;
71903  pC->deferredMoveto = 0;
71904  pC->rowidIsValid = 0;
71905  pC->cacheStatus = CACHE_STALE;
71906  if( pOp->p2>0 ){
71907    VdbeBranchTaken(res!=0,2);
71908    if( res ) pc = pOp->p2 - 1;
71909  }
71910  break;
71911}
71912
71913
71914/* Opcode: Sort P1 P2 * * *
71915**
71916** This opcode does exactly the same thing as OP_Rewind except that
71917** it increments an undocumented global variable used for testing.
71918**
71919** Sorting is accomplished by writing records into a sorting index,
71920** then rewinding that index and playing it back from beginning to
71921** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
71922** rewinding so that the global variable will be incremented and
71923** regression tests can determine whether or not the optimizer is
71924** correctly optimizing out sorts.
71925*/
71926case OP_SorterSort:    /* jump */
71927case OP_Sort: {        /* jump */
71928#ifdef SQLITE_TEST
71929  sqlite3_sort_count++;
71930  sqlite3_search_count--;
71931#endif
71932  p->aCounter[SQLITE_STMTSTATUS_SORT]++;
71933  /* Fall through into OP_Rewind */
71934}
71935/* Opcode: Rewind P1 P2 * * *
71936**
71937** The next use of the Rowid or Column or Next instruction for P1
71938** will refer to the first entry in the database table or index.
71939** If the table or index is empty and P2>0, then jump immediately to P2.
71940** If P2 is 0 or if the table or index is not empty, fall through
71941** to the following instruction.
71942*/
71943case OP_Rewind: {        /* jump */
71944  VdbeCursor *pC;
71945  BtCursor *pCrsr;
71946  int res;
71947
71948  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
71949  pC = p->apCsr[pOp->p1];
71950  assert( pC!=0 );
71951  assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
71952  res = 1;
71953  if( isSorter(pC) ){
71954    rc = sqlite3VdbeSorterRewind(db, pC, &res);
71955  }else{
71956    pCrsr = pC->pCursor;
71957    assert( pCrsr );
71958    rc = sqlite3BtreeFirst(pCrsr, &res);
71959    pC->deferredMoveto = 0;
71960    pC->cacheStatus = CACHE_STALE;
71961    pC->rowidIsValid = 0;
71962  }
71963  pC->nullRow = (u8)res;
71964  assert( pOp->p2>0 && pOp->p2<p->nOp );
71965  VdbeBranchTaken(res!=0,2);
71966  if( res ){
71967    pc = pOp->p2 - 1;
71968  }
71969  break;
71970}
71971
71972/* Opcode: Next P1 P2 P3 P4 P5
71973**
71974** Advance cursor P1 so that it points to the next key/data pair in its
71975** table or index.  If there are no more key/value pairs then fall through
71976** to the following instruction.  But if the cursor advance was successful,
71977** jump immediately to P2.
71978**
71979** The P1 cursor must be for a real table, not a pseudo-table.  P1 must have
71980** been opened prior to this opcode or the program will segfault.
71981**
71982** The P3 value is a hint to the btree implementation. If P3==1, that
71983** means P1 is an SQL index and that this instruction could have been
71984** omitted if that index had been unique.  P3 is usually 0.  P3 is
71985** always either 0 or 1.
71986**
71987** P4 is always of type P4_ADVANCE. The function pointer points to
71988** sqlite3BtreeNext().
71989**
71990** If P5 is positive and the jump is taken, then event counter
71991** number P5-1 in the prepared statement is incremented.
71992**
71993** See also: Prev, NextIfOpen
71994*/
71995/* Opcode: NextIfOpen P1 P2 P3 P4 P5
71996**
71997** This opcode works just like OP_Next except that if cursor P1 is not
71998** open it behaves a no-op.
71999*/
72000/* Opcode: Prev P1 P2 P3 P4 P5
72001**
72002** Back up cursor P1 so that it points to the previous key/data pair in its
72003** table or index.  If there is no previous key/value pairs then fall through
72004** to the following instruction.  But if the cursor backup was successful,
72005** jump immediately to P2.
72006**
72007** The P1 cursor must be for a real table, not a pseudo-table.  If P1 is
72008** not open then the behavior is undefined.
72009**
72010** The P3 value is a hint to the btree implementation. If P3==1, that
72011** means P1 is an SQL index and that this instruction could have been
72012** omitted if that index had been unique.  P3 is usually 0.  P3 is
72013** always either 0 or 1.
72014**
72015** P4 is always of type P4_ADVANCE. The function pointer points to
72016** sqlite3BtreePrevious().
72017**
72018** If P5 is positive and the jump is taken, then event counter
72019** number P5-1 in the prepared statement is incremented.
72020*/
72021/* Opcode: PrevIfOpen P1 P2 P3 P4 P5
72022**
72023** This opcode works just like OP_Prev except that if cursor P1 is not
72024** open it behaves a no-op.
72025*/
72026case OP_SorterNext: {  /* jump */
72027  VdbeCursor *pC;
72028  int res;
72029
72030  pC = p->apCsr[pOp->p1];
72031  assert( isSorter(pC) );
72032  res = 0;
72033  rc = sqlite3VdbeSorterNext(db, pC, &res);
72034  goto next_tail;
72035case OP_PrevIfOpen:    /* jump */
72036case OP_NextIfOpen:    /* jump */
72037  if( p->apCsr[pOp->p1]==0 ) break;
72038  /* Fall through */
72039case OP_Prev:          /* jump */
72040case OP_Next:          /* jump */
72041  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
72042  assert( pOp->p5<ArraySize(p->aCounter) );
72043  pC = p->apCsr[pOp->p1];
72044  res = pOp->p3;
72045  assert( pC!=0 );
72046  assert( pC->deferredMoveto==0 );
72047  assert( pC->pCursor );
72048  assert( res==0 || (res==1 && pC->isTable==0) );
72049  testcase( res==1 );
72050  assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
72051  assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
72052  assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
72053  assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
72054  rc = pOp->p4.xAdvance(pC->pCursor, &res);
72055next_tail:
72056  pC->cacheStatus = CACHE_STALE;
72057  VdbeBranchTaken(res==0,2);
72058  if( res==0 ){
72059    pC->nullRow = 0;
72060    pc = pOp->p2 - 1;
72061    p->aCounter[pOp->p5]++;
72062#ifdef SQLITE_TEST
72063    sqlite3_search_count++;
72064#endif
72065  }else{
72066    pC->nullRow = 1;
72067  }
72068  pC->rowidIsValid = 0;
72069  goto check_for_interrupt;
72070}
72071
72072/* Opcode: IdxInsert P1 P2 P3 * P5
72073** Synopsis: key=r[P2]
72074**
72075** Register P2 holds an SQL index key made using the
72076** MakeRecord instructions.  This opcode writes that key
72077** into the index P1.  Data for the entry is nil.
72078**
72079** P3 is a flag that provides a hint to the b-tree layer that this
72080** insert is likely to be an append.
72081**
72082** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
72083** incremented by this instruction.  If the OPFLAG_NCHANGE bit is clear,
72084** then the change counter is unchanged.
72085**
72086** If P5 has the OPFLAG_USESEEKRESULT bit set, then the cursor must have
72087** just done a seek to the spot where the new entry is to be inserted.
72088** This flag avoids doing an extra seek.
72089**
72090** This instruction only works for indices.  The equivalent instruction
72091** for tables is OP_Insert.
72092*/
72093case OP_SorterInsert:       /* in2 */
72094case OP_IdxInsert: {        /* in2 */
72095  VdbeCursor *pC;
72096  BtCursor *pCrsr;
72097  int nKey;
72098  const char *zKey;
72099
72100  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
72101  pC = p->apCsr[pOp->p1];
72102  assert( pC!=0 );
72103  assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
72104  pIn2 = &aMem[pOp->p2];
72105  assert( pIn2->flags & MEM_Blob );
72106  pCrsr = pC->pCursor;
72107  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
72108  assert( pCrsr!=0 );
72109  assert( pC->isTable==0 );
72110  rc = ExpandBlob(pIn2);
72111  if( rc==SQLITE_OK ){
72112    if( isSorter(pC) ){
72113      rc = sqlite3VdbeSorterWrite(db, pC, pIn2);
72114    }else{
72115      nKey = pIn2->n;
72116      zKey = pIn2->z;
72117      rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3,
72118          ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
72119          );
72120      assert( pC->deferredMoveto==0 );
72121      pC->cacheStatus = CACHE_STALE;
72122    }
72123  }
72124  break;
72125}
72126
72127/* Opcode: IdxDelete P1 P2 P3 * *
72128** Synopsis: key=r[P2@P3]
72129**
72130** The content of P3 registers starting at register P2 form
72131** an unpacked index key. This opcode removes that entry from the
72132** index opened by cursor P1.
72133*/
72134case OP_IdxDelete: {
72135  VdbeCursor *pC;
72136  BtCursor *pCrsr;
72137  int res;
72138  UnpackedRecord r;
72139
72140  assert( pOp->p3>0 );
72141  assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem-p->nCursor)+1 );
72142  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
72143  pC = p->apCsr[pOp->p1];
72144  assert( pC!=0 );
72145  pCrsr = pC->pCursor;
72146  assert( pCrsr!=0 );
72147  assert( pOp->p5==0 );
72148  r.pKeyInfo = pC->pKeyInfo;
72149  r.nField = (u16)pOp->p3;
72150  r.default_rc = 0;
72151  r.aMem = &aMem[pOp->p2];
72152#ifdef SQLITE_DEBUG
72153  { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
72154#endif
72155  rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
72156  if( rc==SQLITE_OK && res==0 ){
72157    rc = sqlite3BtreeDelete(pCrsr);
72158  }
72159  assert( pC->deferredMoveto==0 );
72160  pC->cacheStatus = CACHE_STALE;
72161  break;
72162}
72163
72164/* Opcode: IdxRowid P1 P2 * * *
72165** Synopsis: r[P2]=rowid
72166**
72167** Write into register P2 an integer which is the last entry in the record at
72168** the end of the index key pointed to by cursor P1.  This integer should be
72169** the rowid of the table entry to which this index entry points.
72170**
72171** See also: Rowid, MakeRecord.
72172*/
72173case OP_IdxRowid: {              /* out2-prerelease */
72174  BtCursor *pCrsr;
72175  VdbeCursor *pC;
72176  i64 rowid;
72177
72178  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
72179  pC = p->apCsr[pOp->p1];
72180  assert( pC!=0 );
72181  pCrsr = pC->pCursor;
72182  assert( pCrsr!=0 );
72183  pOut->flags = MEM_Null;
72184  rc = sqlite3VdbeCursorMoveto(pC);
72185  if( NEVER(rc) ) goto abort_due_to_error;
72186  assert( pC->deferredMoveto==0 );
72187  assert( pC->isTable==0 );
72188  if( !pC->nullRow ){
72189    rowid = 0;  /* Not needed.  Only used to silence a warning. */
72190    rc = sqlite3VdbeIdxRowid(db, pCrsr, &rowid);
72191    if( rc!=SQLITE_OK ){
72192      goto abort_due_to_error;
72193    }
72194    pOut->u.i = rowid;
72195    pOut->flags = MEM_Int;
72196  }
72197  break;
72198}
72199
72200/* Opcode: IdxGE P1 P2 P3 P4 P5
72201** Synopsis: key=r[P3@P4]
72202**
72203** The P4 register values beginning with P3 form an unpacked index
72204** key that omits the PRIMARY KEY.  Compare this key value against the index
72205** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
72206** fields at the end.
72207**
72208** If the P1 index entry is greater than or equal to the key value
72209** then jump to P2.  Otherwise fall through to the next instruction.
72210*/
72211/* Opcode: IdxGT P1 P2 P3 P4 P5
72212** Synopsis: key=r[P3@P4]
72213**
72214** The P4 register values beginning with P3 form an unpacked index
72215** key that omits the PRIMARY KEY.  Compare this key value against the index
72216** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
72217** fields at the end.
72218**
72219** If the P1 index entry is greater than the key value
72220** then jump to P2.  Otherwise fall through to the next instruction.
72221*/
72222/* Opcode: IdxLT P1 P2 P3 P4 P5
72223** Synopsis: key=r[P3@P4]
72224**
72225** The P4 register values beginning with P3 form an unpacked index
72226** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
72227** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
72228** ROWID on the P1 index.
72229**
72230** If the P1 index entry is less than the key value then jump to P2.
72231** Otherwise fall through to the next instruction.
72232*/
72233/* Opcode: IdxLE P1 P2 P3 P4 P5
72234** Synopsis: key=r[P3@P4]
72235**
72236** The P4 register values beginning with P3 form an unpacked index
72237** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
72238** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
72239** ROWID on the P1 index.
72240**
72241** If the P1 index entry is less than or equal to the key value then jump
72242** to P2. Otherwise fall through to the next instruction.
72243*/
72244case OP_IdxLE:          /* jump */
72245case OP_IdxGT:          /* jump */
72246case OP_IdxLT:          /* jump */
72247case OP_IdxGE:  {       /* jump */
72248  VdbeCursor *pC;
72249  int res;
72250  UnpackedRecord r;
72251
72252  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
72253  pC = p->apCsr[pOp->p1];
72254  assert( pC!=0 );
72255  assert( pC->isOrdered );
72256  assert( pC->pCursor!=0);
72257  assert( pC->deferredMoveto==0 );
72258  assert( pOp->p5==0 || pOp->p5==1 );
72259  assert( pOp->p4type==P4_INT32 );
72260  r.pKeyInfo = pC->pKeyInfo;
72261  r.nField = (u16)pOp->p4.i;
72262  if( pOp->opcode<OP_IdxLT ){
72263    assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
72264    r.default_rc = -1;
72265  }else{
72266    assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
72267    r.default_rc = 0;
72268  }
72269  r.aMem = &aMem[pOp->p3];
72270#ifdef SQLITE_DEBUG
72271  { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
72272#endif
72273  res = 0;  /* Not needed.  Only used to silence a warning. */
72274  rc = sqlite3VdbeIdxKeyCompare(pC, &r, &res);
72275  assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
72276  if( (pOp->opcode&1)==(OP_IdxLT&1) ){
72277    assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
72278    res = -res;
72279  }else{
72280    assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
72281    res++;
72282  }
72283  VdbeBranchTaken(res>0,2);
72284  if( res>0 ){
72285    pc = pOp->p2 - 1 ;
72286  }
72287  break;
72288}
72289
72290/* Opcode: Destroy P1 P2 P3 * *
72291**
72292** Delete an entire database table or index whose root page in the database
72293** file is given by P1.
72294**
72295** The table being destroyed is in the main database file if P3==0.  If
72296** P3==1 then the table to be clear is in the auxiliary database file
72297** that is used to store tables create using CREATE TEMPORARY TABLE.
72298**
72299** If AUTOVACUUM is enabled then it is possible that another root page
72300** might be moved into the newly deleted root page in order to keep all
72301** root pages contiguous at the beginning of the database.  The former
72302** value of the root page that moved - its value before the move occurred -
72303** is stored in register P2.  If no page
72304** movement was required (because the table being dropped was already
72305** the last one in the database) then a zero is stored in register P2.
72306** If AUTOVACUUM is disabled then a zero is stored in register P2.
72307**
72308** See also: Clear
72309*/
72310case OP_Destroy: {     /* out2-prerelease */
72311  int iMoved;
72312  int iCnt;
72313  Vdbe *pVdbe;
72314  int iDb;
72315
72316  assert( p->readOnly==0 );
72317#ifndef SQLITE_OMIT_VIRTUALTABLE
72318  iCnt = 0;
72319  for(pVdbe=db->pVdbe; pVdbe; pVdbe = pVdbe->pNext){
72320    if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->bIsReader
72321     && pVdbe->inVtabMethod<2 && pVdbe->pc>=0
72322    ){
72323      iCnt++;
72324    }
72325  }
72326#else
72327  iCnt = db->nVdbeRead;
72328#endif
72329  pOut->flags = MEM_Null;
72330  if( iCnt>1 ){
72331    rc = SQLITE_LOCKED;
72332    p->errorAction = OE_Abort;
72333  }else{
72334    iDb = pOp->p3;
72335    assert( iCnt==1 );
72336    assert( (p->btreeMask & (((yDbMask)1)<<iDb))!=0 );
72337    iMoved = 0;  /* Not needed.  Only to silence a warning. */
72338    rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
72339    pOut->flags = MEM_Int;
72340    pOut->u.i = iMoved;
72341#ifndef SQLITE_OMIT_AUTOVACUUM
72342    if( rc==SQLITE_OK && iMoved!=0 ){
72343      sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
72344      /* All OP_Destroy operations occur on the same btree */
72345      assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
72346      resetSchemaOnFault = iDb+1;
72347    }
72348#endif
72349  }
72350  break;
72351}
72352
72353/* Opcode: Clear P1 P2 P3
72354**
72355** Delete all contents of the database table or index whose root page
72356** in the database file is given by P1.  But, unlike Destroy, do not
72357** remove the table or index from the database file.
72358**
72359** The table being clear is in the main database file if P2==0.  If
72360** P2==1 then the table to be clear is in the auxiliary database file
72361** that is used to store tables create using CREATE TEMPORARY TABLE.
72362**
72363** If the P3 value is non-zero, then the table referred to must be an
72364** intkey table (an SQL table, not an index). In this case the row change
72365** count is incremented by the number of rows in the table being cleared.
72366** If P3 is greater than zero, then the value stored in register P3 is
72367** also incremented by the number of rows in the table being cleared.
72368**
72369** See also: Destroy
72370*/
72371case OP_Clear: {
72372  int nChange;
72373
72374  nChange = 0;
72375  assert( p->readOnly==0 );
72376  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
72377  rc = sqlite3BtreeClearTable(
72378      db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
72379  );
72380  if( pOp->p3 ){
72381    p->nChange += nChange;
72382    if( pOp->p3>0 ){
72383      assert( memIsValid(&aMem[pOp->p3]) );
72384      memAboutToChange(p, &aMem[pOp->p3]);
72385      aMem[pOp->p3].u.i += nChange;
72386    }
72387  }
72388  break;
72389}
72390
72391/* Opcode: ResetSorter P1 * * * *
72392**
72393** Delete all contents from the ephemeral table or sorter
72394** that is open on cursor P1.
72395**
72396** This opcode only works for cursors used for sorting and
72397** opened with OP_OpenEphemeral or OP_SorterOpen.
72398*/
72399case OP_ResetSorter: {
72400  VdbeCursor *pC;
72401
72402  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
72403  pC = p->apCsr[pOp->p1];
72404  assert( pC!=0 );
72405  if( pC->pSorter ){
72406    sqlite3VdbeSorterReset(db, pC->pSorter);
72407  }else{
72408    assert( pC->isEphemeral );
72409    rc = sqlite3BtreeClearTableOfCursor(pC->pCursor);
72410  }
72411  break;
72412}
72413
72414/* Opcode: CreateTable P1 P2 * * *
72415** Synopsis: r[P2]=root iDb=P1
72416**
72417** Allocate a new table in the main database file if P1==0 or in the
72418** auxiliary database file if P1==1 or in an attached database if
72419** P1>1.  Write the root page number of the new table into
72420** register P2
72421**
72422** The difference between a table and an index is this:  A table must
72423** have a 4-byte integer key and can have arbitrary data.  An index
72424** has an arbitrary key but no data.
72425**
72426** See also: CreateIndex
72427*/
72428/* Opcode: CreateIndex P1 P2 * * *
72429** Synopsis: r[P2]=root iDb=P1
72430**
72431** Allocate a new index in the main database file if P1==0 or in the
72432** auxiliary database file if P1==1 or in an attached database if
72433** P1>1.  Write the root page number of the new table into
72434** register P2.
72435**
72436** See documentation on OP_CreateTable for additional information.
72437*/
72438case OP_CreateIndex:            /* out2-prerelease */
72439case OP_CreateTable: {          /* out2-prerelease */
72440  int pgno;
72441  int flags;
72442  Db *pDb;
72443
72444  pgno = 0;
72445  assert( pOp->p1>=0 && pOp->p1<db->nDb );
72446  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
72447  assert( p->readOnly==0 );
72448  pDb = &db->aDb[pOp->p1];
72449  assert( pDb->pBt!=0 );
72450  if( pOp->opcode==OP_CreateTable ){
72451    /* flags = BTREE_INTKEY; */
72452    flags = BTREE_INTKEY;
72453  }else{
72454    flags = BTREE_BLOBKEY;
72455  }
72456  rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
72457  pOut->u.i = pgno;
72458  break;
72459}
72460
72461/* Opcode: ParseSchema P1 * * P4 *
72462**
72463** Read and parse all entries from the SQLITE_MASTER table of database P1
72464** that match the WHERE clause P4.
72465**
72466** This opcode invokes the parser to create a new virtual machine,
72467** then runs the new virtual machine.  It is thus a re-entrant opcode.
72468*/
72469case OP_ParseSchema: {
72470  int iDb;
72471  const char *zMaster;
72472  char *zSql;
72473  InitData initData;
72474
72475  /* Any prepared statement that invokes this opcode will hold mutexes
72476  ** on every btree.  This is a prerequisite for invoking
72477  ** sqlite3InitCallback().
72478  */
72479#ifdef SQLITE_DEBUG
72480  for(iDb=0; iDb<db->nDb; iDb++){
72481    assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
72482  }
72483#endif
72484
72485  iDb = pOp->p1;
72486  assert( iDb>=0 && iDb<db->nDb );
72487  assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
72488  /* Used to be a conditional */ {
72489    zMaster = SCHEMA_TABLE(iDb);
72490    initData.db = db;
72491    initData.iDb = pOp->p1;
72492    initData.pzErrMsg = &p->zErrMsg;
72493    zSql = sqlite3MPrintf(db,
72494       "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
72495       db->aDb[iDb].zName, zMaster, pOp->p4.z);
72496    if( zSql==0 ){
72497      rc = SQLITE_NOMEM;
72498    }else{
72499      assert( db->init.busy==0 );
72500      db->init.busy = 1;
72501      initData.rc = SQLITE_OK;
72502      assert( !db->mallocFailed );
72503      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
72504      if( rc==SQLITE_OK ) rc = initData.rc;
72505      sqlite3DbFree(db, zSql);
72506      db->init.busy = 0;
72507    }
72508  }
72509  if( rc ) sqlite3ResetAllSchemasOfConnection(db);
72510  if( rc==SQLITE_NOMEM ){
72511    goto no_mem;
72512  }
72513  break;
72514}
72515
72516#if !defined(SQLITE_OMIT_ANALYZE)
72517/* Opcode: LoadAnalysis P1 * * * *
72518**
72519** Read the sqlite_stat1 table for database P1 and load the content
72520** of that table into the internal index hash table.  This will cause
72521** the analysis to be used when preparing all subsequent queries.
72522*/
72523case OP_LoadAnalysis: {
72524  assert( pOp->p1>=0 && pOp->p1<db->nDb );
72525  rc = sqlite3AnalysisLoad(db, pOp->p1);
72526  break;
72527}
72528#endif /* !defined(SQLITE_OMIT_ANALYZE) */
72529
72530/* Opcode: DropTable P1 * * P4 *
72531**
72532** Remove the internal (in-memory) data structures that describe
72533** the table named P4 in database P1.  This is called after a table
72534** is dropped in order to keep the internal representation of the
72535** schema consistent with what is on disk.
72536*/
72537case OP_DropTable: {
72538  sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
72539  break;
72540}
72541
72542/* Opcode: DropIndex P1 * * P4 *
72543**
72544** Remove the internal (in-memory) data structures that describe
72545** the index named P4 in database P1.  This is called after an index
72546** is dropped in order to keep the internal representation of the
72547** schema consistent with what is on disk.
72548*/
72549case OP_DropIndex: {
72550  sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
72551  break;
72552}
72553
72554/* Opcode: DropTrigger P1 * * P4 *
72555**
72556** Remove the internal (in-memory) data structures that describe
72557** the trigger named P4 in database P1.  This is called after a trigger
72558** is dropped in order to keep the internal representation of the
72559** schema consistent with what is on disk.
72560*/
72561case OP_DropTrigger: {
72562  sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
72563  break;
72564}
72565
72566
72567#ifndef SQLITE_OMIT_INTEGRITY_CHECK
72568/* Opcode: IntegrityCk P1 P2 P3 * P5
72569**
72570** Do an analysis of the currently open database.  Store in
72571** register P1 the text of an error message describing any problems.
72572** If no problems are found, store a NULL in register P1.
72573**
72574** The register P3 contains the maximum number of allowed errors.
72575** At most reg(P3) errors will be reported.
72576** In other words, the analysis stops as soon as reg(P1) errors are
72577** seen.  Reg(P1) is updated with the number of errors remaining.
72578**
72579** The root page numbers of all tables in the database are integer
72580** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
72581** total.
72582**
72583** If P5 is not zero, the check is done on the auxiliary database
72584** file, not the main database file.
72585**
72586** This opcode is used to implement the integrity_check pragma.
72587*/
72588case OP_IntegrityCk: {
72589  int nRoot;      /* Number of tables to check.  (Number of root pages.) */
72590  int *aRoot;     /* Array of rootpage numbers for tables to be checked */
72591  int j;          /* Loop counter */
72592  int nErr;       /* Number of errors reported */
72593  char *z;        /* Text of the error report */
72594  Mem *pnErr;     /* Register keeping track of errors remaining */
72595
72596  assert( p->bIsReader );
72597  nRoot = pOp->p2;
72598  assert( nRoot>0 );
72599  aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) );
72600  if( aRoot==0 ) goto no_mem;
72601  assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
72602  pnErr = &aMem[pOp->p3];
72603  assert( (pnErr->flags & MEM_Int)!=0 );
72604  assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
72605  pIn1 = &aMem[pOp->p1];
72606  for(j=0; j<nRoot; j++){
72607    aRoot[j] = (int)sqlite3VdbeIntValue(&pIn1[j]);
72608  }
72609  aRoot[j] = 0;
72610  assert( pOp->p5<db->nDb );
72611  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
72612  z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
72613                                 (int)pnErr->u.i, &nErr);
72614  sqlite3DbFree(db, aRoot);
72615  pnErr->u.i -= nErr;
72616  sqlite3VdbeMemSetNull(pIn1);
72617  if( nErr==0 ){
72618    assert( z==0 );
72619  }else if( z==0 ){
72620    goto no_mem;
72621  }else{
72622    sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
72623  }
72624  UPDATE_MAX_BLOBSIZE(pIn1);
72625  sqlite3VdbeChangeEncoding(pIn1, encoding);
72626  break;
72627}
72628#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
72629
72630/* Opcode: RowSetAdd P1 P2 * * *
72631** Synopsis:  rowset(P1)=r[P2]
72632**
72633** Insert the integer value held by register P2 into a boolean index
72634** held in register P1.
72635**
72636** An assertion fails if P2 is not an integer.
72637*/
72638case OP_RowSetAdd: {       /* in1, in2 */
72639  pIn1 = &aMem[pOp->p1];
72640  pIn2 = &aMem[pOp->p2];
72641  assert( (pIn2->flags & MEM_Int)!=0 );
72642  if( (pIn1->flags & MEM_RowSet)==0 ){
72643    sqlite3VdbeMemSetRowSet(pIn1);
72644    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
72645  }
72646  sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
72647  break;
72648}
72649
72650/* Opcode: RowSetRead P1 P2 P3 * *
72651** Synopsis:  r[P3]=rowset(P1)
72652**
72653** Extract the smallest value from boolean index P1 and put that value into
72654** register P3.  Or, if boolean index P1 is initially empty, leave P3
72655** unchanged and jump to instruction P2.
72656*/
72657case OP_RowSetRead: {       /* jump, in1, out3 */
72658  i64 val;
72659
72660  pIn1 = &aMem[pOp->p1];
72661  if( (pIn1->flags & MEM_RowSet)==0
72662   || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
72663  ){
72664    /* The boolean index is empty */
72665    sqlite3VdbeMemSetNull(pIn1);
72666    pc = pOp->p2 - 1;
72667    VdbeBranchTaken(1,2);
72668  }else{
72669    /* A value was pulled from the index */
72670    sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
72671    VdbeBranchTaken(0,2);
72672  }
72673  goto check_for_interrupt;
72674}
72675
72676/* Opcode: RowSetTest P1 P2 P3 P4
72677** Synopsis: if r[P3] in rowset(P1) goto P2
72678**
72679** Register P3 is assumed to hold a 64-bit integer value. If register P1
72680** contains a RowSet object and that RowSet object contains
72681** the value held in P3, jump to register P2. Otherwise, insert the
72682** integer in P3 into the RowSet and continue on to the
72683** next opcode.
72684**
72685** The RowSet object is optimized for the case where successive sets
72686** of integers, where each set contains no duplicates. Each set
72687** of values is identified by a unique P4 value. The first set
72688** must have P4==0, the final set P4=-1.  P4 must be either -1 or
72689** non-negative.  For non-negative values of P4 only the lower 4
72690** bits are significant.
72691**
72692** This allows optimizations: (a) when P4==0 there is no need to test
72693** the rowset object for P3, as it is guaranteed not to contain it,
72694** (b) when P4==-1 there is no need to insert the value, as it will
72695** never be tested for, and (c) when a value that is part of set X is
72696** inserted, there is no need to search to see if the same value was
72697** previously inserted as part of set X (only if it was previously
72698** inserted as part of some other set).
72699*/
72700case OP_RowSetTest: {                     /* jump, in1, in3 */
72701  int iSet;
72702  int exists;
72703
72704  pIn1 = &aMem[pOp->p1];
72705  pIn3 = &aMem[pOp->p3];
72706  iSet = pOp->p4.i;
72707  assert( pIn3->flags&MEM_Int );
72708
72709  /* If there is anything other than a rowset object in memory cell P1,
72710  ** delete it now and initialize P1 with an empty rowset
72711  */
72712  if( (pIn1->flags & MEM_RowSet)==0 ){
72713    sqlite3VdbeMemSetRowSet(pIn1);
72714    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
72715  }
72716
72717  assert( pOp->p4type==P4_INT32 );
72718  assert( iSet==-1 || iSet>=0 );
72719  if( iSet ){
72720    exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
72721    VdbeBranchTaken(exists!=0,2);
72722    if( exists ){
72723      pc = pOp->p2 - 1;
72724      break;
72725    }
72726  }
72727  if( iSet>=0 ){
72728    sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
72729  }
72730  break;
72731}
72732
72733
72734#ifndef SQLITE_OMIT_TRIGGER
72735
72736/* Opcode: Program P1 P2 P3 P4 P5
72737**
72738** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
72739**
72740** P1 contains the address of the memory cell that contains the first memory
72741** cell in an array of values used as arguments to the sub-program. P2
72742** contains the address to jump to if the sub-program throws an IGNORE
72743** exception using the RAISE() function. Register P3 contains the address
72744** of a memory cell in this (the parent) VM that is used to allocate the
72745** memory required by the sub-vdbe at runtime.
72746**
72747** P4 is a pointer to the VM containing the trigger program.
72748**
72749** If P5 is non-zero, then recursive program invocation is enabled.
72750*/
72751case OP_Program: {        /* jump */
72752  int nMem;               /* Number of memory registers for sub-program */
72753  int nByte;              /* Bytes of runtime space required for sub-program */
72754  Mem *pRt;               /* Register to allocate runtime space */
72755  Mem *pMem;              /* Used to iterate through memory cells */
72756  Mem *pEnd;              /* Last memory cell in new array */
72757  VdbeFrame *pFrame;      /* New vdbe frame to execute in */
72758  SubProgram *pProgram;   /* Sub-program to execute */
72759  void *t;                /* Token identifying trigger */
72760
72761  pProgram = pOp->p4.pProgram;
72762  pRt = &aMem[pOp->p3];
72763  assert( pProgram->nOp>0 );
72764
72765  /* If the p5 flag is clear, then recursive invocation of triggers is
72766  ** disabled for backwards compatibility (p5 is set if this sub-program
72767  ** is really a trigger, not a foreign key action, and the flag set
72768  ** and cleared by the "PRAGMA recursive_triggers" command is clear).
72769  **
72770  ** It is recursive invocation of triggers, at the SQL level, that is
72771  ** disabled. In some cases a single trigger may generate more than one
72772  ** SubProgram (if the trigger may be executed with more than one different
72773  ** ON CONFLICT algorithm). SubProgram structures associated with a
72774  ** single trigger all have the same value for the SubProgram.token
72775  ** variable.  */
72776  if( pOp->p5 ){
72777    t = pProgram->token;
72778    for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
72779    if( pFrame ) break;
72780  }
72781
72782  if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
72783    rc = SQLITE_ERROR;
72784    sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
72785    break;
72786  }
72787
72788  /* Register pRt is used to store the memory required to save the state
72789  ** of the current program, and the memory required at runtime to execute
72790  ** the trigger program. If this trigger has been fired before, then pRt
72791  ** is already allocated. Otherwise, it must be initialized.  */
72792  if( (pRt->flags&MEM_Frame)==0 ){
72793    /* SubProgram.nMem is set to the number of memory cells used by the
72794    ** program stored in SubProgram.aOp. As well as these, one memory
72795    ** cell is required for each cursor used by the program. Set local
72796    ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
72797    */
72798    nMem = pProgram->nMem + pProgram->nCsr;
72799    nByte = ROUND8(sizeof(VdbeFrame))
72800              + nMem * sizeof(Mem)
72801              + pProgram->nCsr * sizeof(VdbeCursor *)
72802              + pProgram->nOnce * sizeof(u8);
72803    pFrame = sqlite3DbMallocZero(db, nByte);
72804    if( !pFrame ){
72805      goto no_mem;
72806    }
72807    sqlite3VdbeMemRelease(pRt);
72808    pRt->flags = MEM_Frame;
72809    pRt->u.pFrame = pFrame;
72810
72811    pFrame->v = p;
72812    pFrame->nChildMem = nMem;
72813    pFrame->nChildCsr = pProgram->nCsr;
72814    pFrame->pc = pc;
72815    pFrame->aMem = p->aMem;
72816    pFrame->nMem = p->nMem;
72817    pFrame->apCsr = p->apCsr;
72818    pFrame->nCursor = p->nCursor;
72819    pFrame->aOp = p->aOp;
72820    pFrame->nOp = p->nOp;
72821    pFrame->token = pProgram->token;
72822    pFrame->aOnceFlag = p->aOnceFlag;
72823    pFrame->nOnceFlag = p->nOnceFlag;
72824
72825    pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
72826    for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
72827      pMem->flags = MEM_Undefined;
72828      pMem->db = db;
72829    }
72830  }else{
72831    pFrame = pRt->u.pFrame;
72832    assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem );
72833    assert( pProgram->nCsr==pFrame->nChildCsr );
72834    assert( pc==pFrame->pc );
72835  }
72836
72837  p->nFrame++;
72838  pFrame->pParent = p->pFrame;
72839  pFrame->lastRowid = lastRowid;
72840  pFrame->nChange = p->nChange;
72841  p->nChange = 0;
72842  p->pFrame = pFrame;
72843  p->aMem = aMem = &VdbeFrameMem(pFrame)[-1];
72844  p->nMem = pFrame->nChildMem;
72845  p->nCursor = (u16)pFrame->nChildCsr;
72846  p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
72847  p->aOp = aOp = pProgram->aOp;
72848  p->nOp = pProgram->nOp;
72849  p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
72850  p->nOnceFlag = pProgram->nOnce;
72851  pc = -1;
72852  memset(p->aOnceFlag, 0, p->nOnceFlag);
72853
72854  break;
72855}
72856
72857/* Opcode: Param P1 P2 * * *
72858**
72859** This opcode is only ever present in sub-programs called via the
72860** OP_Program instruction. Copy a value currently stored in a memory
72861** cell of the calling (parent) frame to cell P2 in the current frames
72862** address space. This is used by trigger programs to access the new.*
72863** and old.* values.
72864**
72865** The address of the cell in the parent frame is determined by adding
72866** the value of the P1 argument to the value of the P1 argument to the
72867** calling OP_Program instruction.
72868*/
72869case OP_Param: {           /* out2-prerelease */
72870  VdbeFrame *pFrame;
72871  Mem *pIn;
72872  pFrame = p->pFrame;
72873  pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
72874  sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
72875  break;
72876}
72877
72878#endif /* #ifndef SQLITE_OMIT_TRIGGER */
72879
72880#ifndef SQLITE_OMIT_FOREIGN_KEY
72881/* Opcode: FkCounter P1 P2 * * *
72882** Synopsis: fkctr[P1]+=P2
72883**
72884** Increment a "constraint counter" by P2 (P2 may be negative or positive).
72885** If P1 is non-zero, the database constraint counter is incremented
72886** (deferred foreign key constraints). Otherwise, if P1 is zero, the
72887** statement counter is incremented (immediate foreign key constraints).
72888*/
72889case OP_FkCounter: {
72890  if( db->flags & SQLITE_DeferFKs ){
72891    db->nDeferredImmCons += pOp->p2;
72892  }else if( pOp->p1 ){
72893    db->nDeferredCons += pOp->p2;
72894  }else{
72895    p->nFkConstraint += pOp->p2;
72896  }
72897  break;
72898}
72899
72900/* Opcode: FkIfZero P1 P2 * * *
72901** Synopsis: if fkctr[P1]==0 goto P2
72902**
72903** This opcode tests if a foreign key constraint-counter is currently zero.
72904** If so, jump to instruction P2. Otherwise, fall through to the next
72905** instruction.
72906**
72907** If P1 is non-zero, then the jump is taken if the database constraint-counter
72908** is zero (the one that counts deferred constraint violations). If P1 is
72909** zero, the jump is taken if the statement constraint-counter is zero
72910** (immediate foreign key constraint violations).
72911*/
72912case OP_FkIfZero: {         /* jump */
72913  if( pOp->p1 ){
72914    VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
72915    if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
72916  }else{
72917    VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
72918    if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
72919  }
72920  break;
72921}
72922#endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
72923
72924#ifndef SQLITE_OMIT_AUTOINCREMENT
72925/* Opcode: MemMax P1 P2 * * *
72926** Synopsis: r[P1]=max(r[P1],r[P2])
72927**
72928** P1 is a register in the root frame of this VM (the root frame is
72929** different from the current frame if this instruction is being executed
72930** within a sub-program). Set the value of register P1 to the maximum of
72931** its current value and the value in register P2.
72932**
72933** This instruction throws an error if the memory cell is not initially
72934** an integer.
72935*/
72936case OP_MemMax: {        /* in2 */
72937  VdbeFrame *pFrame;
72938  if( p->pFrame ){
72939    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
72940    pIn1 = &pFrame->aMem[pOp->p1];
72941  }else{
72942    pIn1 = &aMem[pOp->p1];
72943  }
72944  assert( memIsValid(pIn1) );
72945  sqlite3VdbeMemIntegerify(pIn1);
72946  pIn2 = &aMem[pOp->p2];
72947  sqlite3VdbeMemIntegerify(pIn2);
72948  if( pIn1->u.i<pIn2->u.i){
72949    pIn1->u.i = pIn2->u.i;
72950  }
72951  break;
72952}
72953#endif /* SQLITE_OMIT_AUTOINCREMENT */
72954
72955/* Opcode: IfPos P1 P2 * * *
72956** Synopsis: if r[P1]>0 goto P2
72957**
72958** If the value of register P1 is 1 or greater, jump to P2.
72959**
72960** It is illegal to use this instruction on a register that does
72961** not contain an integer.  An assertion fault will result if you try.
72962*/
72963case OP_IfPos: {        /* jump, in1 */
72964  pIn1 = &aMem[pOp->p1];
72965  assert( pIn1->flags&MEM_Int );
72966  VdbeBranchTaken( pIn1->u.i>0, 2);
72967  if( pIn1->u.i>0 ){
72968     pc = pOp->p2 - 1;
72969  }
72970  break;
72971}
72972
72973/* Opcode: IfNeg P1 P2 * * *
72974** Synopsis: if r[P1]<0 goto P2
72975**
72976** If the value of register P1 is less than zero, jump to P2.
72977**
72978** It is illegal to use this instruction on a register that does
72979** not contain an integer.  An assertion fault will result if you try.
72980*/
72981case OP_IfNeg: {        /* jump, in1 */
72982  pIn1 = &aMem[pOp->p1];
72983  assert( pIn1->flags&MEM_Int );
72984  VdbeBranchTaken(pIn1->u.i<0, 2);
72985  if( pIn1->u.i<0 ){
72986     pc = pOp->p2 - 1;
72987  }
72988  break;
72989}
72990
72991/* Opcode: IfZero P1 P2 P3 * *
72992** Synopsis: r[P1]+=P3, if r[P1]==0 goto P2
72993**
72994** The register P1 must contain an integer.  Add literal P3 to the
72995** value in register P1.  If the result is exactly 0, jump to P2.
72996**
72997** It is illegal to use this instruction on a register that does
72998** not contain an integer.  An assertion fault will result if you try.
72999*/
73000case OP_IfZero: {        /* jump, in1 */
73001  pIn1 = &aMem[pOp->p1];
73002  assert( pIn1->flags&MEM_Int );
73003  pIn1->u.i += pOp->p3;
73004  VdbeBranchTaken(pIn1->u.i==0, 2);
73005  if( pIn1->u.i==0 ){
73006     pc = pOp->p2 - 1;
73007  }
73008  break;
73009}
73010
73011/* Opcode: AggStep * P2 P3 P4 P5
73012** Synopsis: accum=r[P3] step(r[P2@P5])
73013**
73014** Execute the step function for an aggregate.  The
73015** function has P5 arguments.   P4 is a pointer to the FuncDef
73016** structure that specifies the function.  Use register
73017** P3 as the accumulator.
73018**
73019** The P5 arguments are taken from register P2 and its
73020** successors.
73021*/
73022case OP_AggStep: {
73023  int n;
73024  int i;
73025  Mem *pMem;
73026  Mem *pRec;
73027  sqlite3_context ctx;
73028  sqlite3_value **apVal;
73029
73030  n = pOp->p5;
73031  assert( n>=0 );
73032  pRec = &aMem[pOp->p2];
73033  apVal = p->apArg;
73034  assert( apVal || n==0 );
73035  for(i=0; i<n; i++, pRec++){
73036    assert( memIsValid(pRec) );
73037    apVal[i] = pRec;
73038    memAboutToChange(p, pRec);
73039  }
73040  ctx.pFunc = pOp->p4.pFunc;
73041  assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
73042  ctx.pMem = pMem = &aMem[pOp->p3];
73043  pMem->n++;
73044  ctx.s.flags = MEM_Null;
73045  ctx.s.z = 0;
73046  ctx.s.zMalloc = 0;
73047  ctx.s.xDel = 0;
73048  ctx.s.db = db;
73049  ctx.isError = 0;
73050  ctx.pColl = 0;
73051  ctx.skipFlag = 0;
73052  if( ctx.pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
73053    assert( pOp>p->aOp );
73054    assert( pOp[-1].p4type==P4_COLLSEQ );
73055    assert( pOp[-1].opcode==OP_CollSeq );
73056    ctx.pColl = pOp[-1].p4.pColl;
73057  }
73058  (ctx.pFunc->xStep)(&ctx, n, apVal); /* IMP: R-24505-23230 */
73059  if( ctx.isError ){
73060    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s));
73061    rc = ctx.isError;
73062  }
73063  if( ctx.skipFlag ){
73064    assert( pOp[-1].opcode==OP_CollSeq );
73065    i = pOp[-1].p1;
73066    if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
73067  }
73068
73069  sqlite3VdbeMemRelease(&ctx.s);
73070
73071  break;
73072}
73073
73074/* Opcode: AggFinal P1 P2 * P4 *
73075** Synopsis: accum=r[P1] N=P2
73076**
73077** Execute the finalizer function for an aggregate.  P1 is
73078** the memory location that is the accumulator for the aggregate.
73079**
73080** P2 is the number of arguments that the step function takes and
73081** P4 is a pointer to the FuncDef for this function.  The P2
73082** argument is not used by this opcode.  It is only there to disambiguate
73083** functions that can take varying numbers of arguments.  The
73084** P4 argument is only needed for the degenerate case where
73085** the step function was not previously called.
73086*/
73087case OP_AggFinal: {
73088  Mem *pMem;
73089  assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
73090  pMem = &aMem[pOp->p1];
73091  assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
73092  rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
73093  if( rc ){
73094    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(pMem));
73095  }
73096  sqlite3VdbeChangeEncoding(pMem, encoding);
73097  UPDATE_MAX_BLOBSIZE(pMem);
73098  if( sqlite3VdbeMemTooBig(pMem) ){
73099    goto too_big;
73100  }
73101  break;
73102}
73103
73104#ifndef SQLITE_OMIT_WAL
73105/* Opcode: Checkpoint P1 P2 P3 * *
73106**
73107** Checkpoint database P1. This is a no-op if P1 is not currently in
73108** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
73109** or RESTART.  Write 1 or 0 into mem[P3] if the checkpoint returns
73110** SQLITE_BUSY or not, respectively.  Write the number of pages in the
73111** WAL after the checkpoint into mem[P3+1] and the number of pages
73112** in the WAL that have been checkpointed after the checkpoint
73113** completes into mem[P3+2].  However on an error, mem[P3+1] and
73114** mem[P3+2] are initialized to -1.
73115*/
73116case OP_Checkpoint: {
73117  int i;                          /* Loop counter */
73118  int aRes[3];                    /* Results */
73119  Mem *pMem;                      /* Write results here */
73120
73121  assert( p->readOnly==0 );
73122  aRes[0] = 0;
73123  aRes[1] = aRes[2] = -1;
73124  assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
73125       || pOp->p2==SQLITE_CHECKPOINT_FULL
73126       || pOp->p2==SQLITE_CHECKPOINT_RESTART
73127  );
73128  rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
73129  if( rc==SQLITE_BUSY ){
73130    rc = SQLITE_OK;
73131    aRes[0] = 1;
73132  }
73133  for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
73134    sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
73135  }
73136  break;
73137};
73138#endif
73139
73140#ifndef SQLITE_OMIT_PRAGMA
73141/* Opcode: JournalMode P1 P2 P3 * *
73142**
73143** Change the journal mode of database P1 to P3. P3 must be one of the
73144** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
73145** modes (delete, truncate, persist, off and memory), this is a simple
73146** operation. No IO is required.
73147**
73148** If changing into or out of WAL mode the procedure is more complicated.
73149**
73150** Write a string containing the final journal-mode to register P2.
73151*/
73152case OP_JournalMode: {    /* out2-prerelease */
73153  Btree *pBt;                     /* Btree to change journal mode of */
73154  Pager *pPager;                  /* Pager associated with pBt */
73155  int eNew;                       /* New journal mode */
73156  int eOld;                       /* The old journal mode */
73157#ifndef SQLITE_OMIT_WAL
73158  const char *zFilename;          /* Name of database file for pPager */
73159#endif
73160
73161  eNew = pOp->p3;
73162  assert( eNew==PAGER_JOURNALMODE_DELETE
73163       || eNew==PAGER_JOURNALMODE_TRUNCATE
73164       || eNew==PAGER_JOURNALMODE_PERSIST
73165       || eNew==PAGER_JOURNALMODE_OFF
73166       || eNew==PAGER_JOURNALMODE_MEMORY
73167       || eNew==PAGER_JOURNALMODE_WAL
73168       || eNew==PAGER_JOURNALMODE_QUERY
73169  );
73170  assert( pOp->p1>=0 && pOp->p1<db->nDb );
73171  assert( p->readOnly==0 );
73172
73173  pBt = db->aDb[pOp->p1].pBt;
73174  pPager = sqlite3BtreePager(pBt);
73175  eOld = sqlite3PagerGetJournalMode(pPager);
73176  if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
73177  if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
73178
73179#ifndef SQLITE_OMIT_WAL
73180  zFilename = sqlite3PagerFilename(pPager, 1);
73181
73182  /* Do not allow a transition to journal_mode=WAL for a database
73183  ** in temporary storage or if the VFS does not support shared memory
73184  */
73185  if( eNew==PAGER_JOURNALMODE_WAL
73186   && (sqlite3Strlen30(zFilename)==0           /* Temp file */
73187       || !sqlite3PagerWalSupported(pPager))   /* No shared-memory support */
73188  ){
73189    eNew = eOld;
73190  }
73191
73192  if( (eNew!=eOld)
73193   && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
73194  ){
73195    if( !db->autoCommit || db->nVdbeRead>1 ){
73196      rc = SQLITE_ERROR;
73197      sqlite3SetString(&p->zErrMsg, db,
73198          "cannot change %s wal mode from within a transaction",
73199          (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
73200      );
73201      break;
73202    }else{
73203
73204      if( eOld==PAGER_JOURNALMODE_WAL ){
73205        /* If leaving WAL mode, close the log file. If successful, the call
73206        ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
73207        ** file. An EXCLUSIVE lock may still be held on the database file
73208        ** after a successful return.
73209        */
73210        rc = sqlite3PagerCloseWal(pPager);
73211        if( rc==SQLITE_OK ){
73212          sqlite3PagerSetJournalMode(pPager, eNew);
73213        }
73214      }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
73215        /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
73216        ** as an intermediate */
73217        sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
73218      }
73219
73220      /* Open a transaction on the database file. Regardless of the journal
73221      ** mode, this transaction always uses a rollback journal.
73222      */
73223      assert( sqlite3BtreeIsInTrans(pBt)==0 );
73224      if( rc==SQLITE_OK ){
73225        rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
73226      }
73227    }
73228  }
73229#endif /* ifndef SQLITE_OMIT_WAL */
73230
73231  if( rc ){
73232    eNew = eOld;
73233  }
73234  eNew = sqlite3PagerSetJournalMode(pPager, eNew);
73235
73236  pOut = &aMem[pOp->p2];
73237  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
73238  pOut->z = (char *)sqlite3JournalModename(eNew);
73239  pOut->n = sqlite3Strlen30(pOut->z);
73240  pOut->enc = SQLITE_UTF8;
73241  sqlite3VdbeChangeEncoding(pOut, encoding);
73242  break;
73243};
73244#endif /* SQLITE_OMIT_PRAGMA */
73245
73246#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
73247/* Opcode: Vacuum * * * * *
73248**
73249** Vacuum the entire database.  This opcode will cause other virtual
73250** machines to be created and run.  It may not be called from within
73251** a transaction.
73252*/
73253case OP_Vacuum: {
73254  assert( p->readOnly==0 );
73255  rc = sqlite3RunVacuum(&p->zErrMsg, db);
73256  break;
73257}
73258#endif
73259
73260#if !defined(SQLITE_OMIT_AUTOVACUUM)
73261/* Opcode: IncrVacuum P1 P2 * * *
73262**
73263** Perform a single step of the incremental vacuum procedure on
73264** the P1 database. If the vacuum has finished, jump to instruction
73265** P2. Otherwise, fall through to the next instruction.
73266*/
73267case OP_IncrVacuum: {        /* jump */
73268  Btree *pBt;
73269
73270  assert( pOp->p1>=0 && pOp->p1<db->nDb );
73271  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
73272  assert( p->readOnly==0 );
73273  pBt = db->aDb[pOp->p1].pBt;
73274  rc = sqlite3BtreeIncrVacuum(pBt);
73275  VdbeBranchTaken(rc==SQLITE_DONE,2);
73276  if( rc==SQLITE_DONE ){
73277    pc = pOp->p2 - 1;
73278    rc = SQLITE_OK;
73279  }
73280  break;
73281}
73282#endif
73283
73284/* Opcode: Expire P1 * * * *
73285**
73286** Cause precompiled statements to become expired. An expired statement
73287** fails with an error code of SQLITE_SCHEMA if it is ever executed
73288** (via sqlite3_step()).
73289**
73290** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
73291** then only the currently executing statement is affected.
73292*/
73293case OP_Expire: {
73294  if( !pOp->p1 ){
73295    sqlite3ExpirePreparedStatements(db);
73296  }else{
73297    p->expired = 1;
73298  }
73299  break;
73300}
73301
73302#ifndef SQLITE_OMIT_SHARED_CACHE
73303/* Opcode: TableLock P1 P2 P3 P4 *
73304** Synopsis: iDb=P1 root=P2 write=P3
73305**
73306** Obtain a lock on a particular table. This instruction is only used when
73307** the shared-cache feature is enabled.
73308**
73309** P1 is the index of the database in sqlite3.aDb[] of the database
73310** on which the lock is acquired.  A readlock is obtained if P3==0 or
73311** a write lock if P3==1.
73312**
73313** P2 contains the root-page of the table to lock.
73314**
73315** P4 contains a pointer to the name of the table being locked. This is only
73316** used to generate an error message if the lock cannot be obtained.
73317*/
73318case OP_TableLock: {
73319  u8 isWriteLock = (u8)pOp->p3;
73320  if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
73321    int p1 = pOp->p1;
73322    assert( p1>=0 && p1<db->nDb );
73323    assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
73324    assert( isWriteLock==0 || isWriteLock==1 );
73325    rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
73326    if( (rc&0xFF)==SQLITE_LOCKED ){
73327      const char *z = pOp->p4.z;
73328      sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
73329    }
73330  }
73331  break;
73332}
73333#endif /* SQLITE_OMIT_SHARED_CACHE */
73334
73335#ifndef SQLITE_OMIT_VIRTUALTABLE
73336/* Opcode: VBegin * * * P4 *
73337**
73338** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
73339** xBegin method for that table.
73340**
73341** Also, whether or not P4 is set, check that this is not being called from
73342** within a callback to a virtual table xSync() method. If it is, the error
73343** code will be set to SQLITE_LOCKED.
73344*/
73345case OP_VBegin: {
73346  VTable *pVTab;
73347  pVTab = pOp->p4.pVtab;
73348  rc = sqlite3VtabBegin(db, pVTab);
73349  if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
73350  break;
73351}
73352#endif /* SQLITE_OMIT_VIRTUALTABLE */
73353
73354#ifndef SQLITE_OMIT_VIRTUALTABLE
73355/* Opcode: VCreate P1 * * P4 *
73356**
73357** P4 is the name of a virtual table in database P1. Call the xCreate method
73358** for that table.
73359*/
73360case OP_VCreate: {
73361  rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
73362  break;
73363}
73364#endif /* SQLITE_OMIT_VIRTUALTABLE */
73365
73366#ifndef SQLITE_OMIT_VIRTUALTABLE
73367/* Opcode: VDestroy P1 * * P4 *
73368**
73369** P4 is the name of a virtual table in database P1.  Call the xDestroy method
73370** of that table.
73371*/
73372case OP_VDestroy: {
73373  p->inVtabMethod = 2;
73374  rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
73375  p->inVtabMethod = 0;
73376  break;
73377}
73378#endif /* SQLITE_OMIT_VIRTUALTABLE */
73379
73380#ifndef SQLITE_OMIT_VIRTUALTABLE
73381/* Opcode: VOpen P1 * * P4 *
73382**
73383** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
73384** P1 is a cursor number.  This opcode opens a cursor to the virtual
73385** table and stores that cursor in P1.
73386*/
73387case OP_VOpen: {
73388  VdbeCursor *pCur;
73389  sqlite3_vtab_cursor *pVtabCursor;
73390  sqlite3_vtab *pVtab;
73391  sqlite3_module *pModule;
73392
73393  assert( p->bIsReader );
73394  pCur = 0;
73395  pVtabCursor = 0;
73396  pVtab = pOp->p4.pVtab->pVtab;
73397  pModule = (sqlite3_module *)pVtab->pModule;
73398  assert(pVtab && pModule);
73399  rc = pModule->xOpen(pVtab, &pVtabCursor);
73400  sqlite3VtabImportErrmsg(p, pVtab);
73401  if( SQLITE_OK==rc ){
73402    /* Initialize sqlite3_vtab_cursor base class */
73403    pVtabCursor->pVtab = pVtab;
73404
73405    /* Initialize vdbe cursor object */
73406    pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
73407    if( pCur ){
73408      pCur->pVtabCursor = pVtabCursor;
73409    }else{
73410      db->mallocFailed = 1;
73411      pModule->xClose(pVtabCursor);
73412    }
73413  }
73414  break;
73415}
73416#endif /* SQLITE_OMIT_VIRTUALTABLE */
73417
73418#ifndef SQLITE_OMIT_VIRTUALTABLE
73419/* Opcode: VFilter P1 P2 P3 P4 *
73420** Synopsis: iplan=r[P3] zplan='P4'
73421**
73422** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
73423** the filtered result set is empty.
73424**
73425** P4 is either NULL or a string that was generated by the xBestIndex
73426** method of the module.  The interpretation of the P4 string is left
73427** to the module implementation.
73428**
73429** This opcode invokes the xFilter method on the virtual table specified
73430** by P1.  The integer query plan parameter to xFilter is stored in register
73431** P3. Register P3+1 stores the argc parameter to be passed to the
73432** xFilter method. Registers P3+2..P3+1+argc are the argc
73433** additional parameters which are passed to
73434** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
73435**
73436** A jump is made to P2 if the result set after filtering would be empty.
73437*/
73438case OP_VFilter: {   /* jump */
73439  int nArg;
73440  int iQuery;
73441  const sqlite3_module *pModule;
73442  Mem *pQuery;
73443  Mem *pArgc;
73444  sqlite3_vtab_cursor *pVtabCursor;
73445  sqlite3_vtab *pVtab;
73446  VdbeCursor *pCur;
73447  int res;
73448  int i;
73449  Mem **apArg;
73450
73451  pQuery = &aMem[pOp->p3];
73452  pArgc = &pQuery[1];
73453  pCur = p->apCsr[pOp->p1];
73454  assert( memIsValid(pQuery) );
73455  REGISTER_TRACE(pOp->p3, pQuery);
73456  assert( pCur->pVtabCursor );
73457  pVtabCursor = pCur->pVtabCursor;
73458  pVtab = pVtabCursor->pVtab;
73459  pModule = pVtab->pModule;
73460
73461  /* Grab the index number and argc parameters */
73462  assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
73463  nArg = (int)pArgc->u.i;
73464  iQuery = (int)pQuery->u.i;
73465
73466  /* Invoke the xFilter method */
73467  {
73468    res = 0;
73469    apArg = p->apArg;
73470    for(i = 0; i<nArg; i++){
73471      apArg[i] = &pArgc[i+1];
73472    }
73473
73474    p->inVtabMethod = 1;
73475    rc = pModule->xFilter(pVtabCursor, iQuery, pOp->p4.z, nArg, apArg);
73476    p->inVtabMethod = 0;
73477    sqlite3VtabImportErrmsg(p, pVtab);
73478    if( rc==SQLITE_OK ){
73479      res = pModule->xEof(pVtabCursor);
73480    }
73481    VdbeBranchTaken(res!=0,2);
73482    if( res ){
73483      pc = pOp->p2 - 1;
73484    }
73485  }
73486  pCur->nullRow = 0;
73487
73488  break;
73489}
73490#endif /* SQLITE_OMIT_VIRTUALTABLE */
73491
73492#ifndef SQLITE_OMIT_VIRTUALTABLE
73493/* Opcode: VColumn P1 P2 P3 * *
73494** Synopsis: r[P3]=vcolumn(P2)
73495**
73496** Store the value of the P2-th column of
73497** the row of the virtual-table that the
73498** P1 cursor is pointing to into register P3.
73499*/
73500case OP_VColumn: {
73501  sqlite3_vtab *pVtab;
73502  const sqlite3_module *pModule;
73503  Mem *pDest;
73504  sqlite3_context sContext;
73505
73506  VdbeCursor *pCur = p->apCsr[pOp->p1];
73507  assert( pCur->pVtabCursor );
73508  assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
73509  pDest = &aMem[pOp->p3];
73510  memAboutToChange(p, pDest);
73511  if( pCur->nullRow ){
73512    sqlite3VdbeMemSetNull(pDest);
73513    break;
73514  }
73515  pVtab = pCur->pVtabCursor->pVtab;
73516  pModule = pVtab->pModule;
73517  assert( pModule->xColumn );
73518  memset(&sContext, 0, sizeof(sContext));
73519
73520  /* The output cell may already have a buffer allocated. Move
73521  ** the current contents to sContext.s so in case the user-function
73522  ** can use the already allocated buffer instead of allocating a
73523  ** new one.
73524  */
73525  sqlite3VdbeMemMove(&sContext.s, pDest);
73526  MemSetTypeFlag(&sContext.s, MEM_Null);
73527
73528  rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
73529  sqlite3VtabImportErrmsg(p, pVtab);
73530  if( sContext.isError ){
73531    rc = sContext.isError;
73532  }
73533
73534  /* Copy the result of the function to the P3 register. We
73535  ** do this regardless of whether or not an error occurred to ensure any
73536  ** dynamic allocation in sContext.s (a Mem struct) is  released.
73537  */
73538  sqlite3VdbeChangeEncoding(&sContext.s, encoding);
73539  sqlite3VdbeMemMove(pDest, &sContext.s);
73540  REGISTER_TRACE(pOp->p3, pDest);
73541  UPDATE_MAX_BLOBSIZE(pDest);
73542
73543  if( sqlite3VdbeMemTooBig(pDest) ){
73544    goto too_big;
73545  }
73546  break;
73547}
73548#endif /* SQLITE_OMIT_VIRTUALTABLE */
73549
73550#ifndef SQLITE_OMIT_VIRTUALTABLE
73551/* Opcode: VNext P1 P2 * * *
73552**
73553** Advance virtual table P1 to the next row in its result set and
73554** jump to instruction P2.  Or, if the virtual table has reached
73555** the end of its result set, then fall through to the next instruction.
73556*/
73557case OP_VNext: {   /* jump */
73558  sqlite3_vtab *pVtab;
73559  const sqlite3_module *pModule;
73560  int res;
73561  VdbeCursor *pCur;
73562
73563  res = 0;
73564  pCur = p->apCsr[pOp->p1];
73565  assert( pCur->pVtabCursor );
73566  if( pCur->nullRow ){
73567    break;
73568  }
73569  pVtab = pCur->pVtabCursor->pVtab;
73570  pModule = pVtab->pModule;
73571  assert( pModule->xNext );
73572
73573  /* Invoke the xNext() method of the module. There is no way for the
73574  ** underlying implementation to return an error if one occurs during
73575  ** xNext(). Instead, if an error occurs, true is returned (indicating that
73576  ** data is available) and the error code returned when xColumn or
73577  ** some other method is next invoked on the save virtual table cursor.
73578  */
73579  p->inVtabMethod = 1;
73580  rc = pModule->xNext(pCur->pVtabCursor);
73581  p->inVtabMethod = 0;
73582  sqlite3VtabImportErrmsg(p, pVtab);
73583  if( rc==SQLITE_OK ){
73584    res = pModule->xEof(pCur->pVtabCursor);
73585  }
73586  VdbeBranchTaken(!res,2);
73587  if( !res ){
73588    /* If there is data, jump to P2 */
73589    pc = pOp->p2 - 1;
73590  }
73591  goto check_for_interrupt;
73592}
73593#endif /* SQLITE_OMIT_VIRTUALTABLE */
73594
73595#ifndef SQLITE_OMIT_VIRTUALTABLE
73596/* Opcode: VRename P1 * * P4 *
73597**
73598** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
73599** This opcode invokes the corresponding xRename method. The value
73600** in register P1 is passed as the zName argument to the xRename method.
73601*/
73602case OP_VRename: {
73603  sqlite3_vtab *pVtab;
73604  Mem *pName;
73605
73606  pVtab = pOp->p4.pVtab->pVtab;
73607  pName = &aMem[pOp->p1];
73608  assert( pVtab->pModule->xRename );
73609  assert( memIsValid(pName) );
73610  assert( p->readOnly==0 );
73611  REGISTER_TRACE(pOp->p1, pName);
73612  assert( pName->flags & MEM_Str );
73613  testcase( pName->enc==SQLITE_UTF8 );
73614  testcase( pName->enc==SQLITE_UTF16BE );
73615  testcase( pName->enc==SQLITE_UTF16LE );
73616  rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
73617  if( rc==SQLITE_OK ){
73618    rc = pVtab->pModule->xRename(pVtab, pName->z);
73619    sqlite3VtabImportErrmsg(p, pVtab);
73620    p->expired = 0;
73621  }
73622  break;
73623}
73624#endif
73625
73626#ifndef SQLITE_OMIT_VIRTUALTABLE
73627/* Opcode: VUpdate P1 P2 P3 P4 P5
73628** Synopsis: data=r[P3@P2]
73629**
73630** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
73631** This opcode invokes the corresponding xUpdate method. P2 values
73632** are contiguous memory cells starting at P3 to pass to the xUpdate
73633** invocation. The value in register (P3+P2-1) corresponds to the
73634** p2th element of the argv array passed to xUpdate.
73635**
73636** The xUpdate method will do a DELETE or an INSERT or both.
73637** The argv[0] element (which corresponds to memory cell P3)
73638** is the rowid of a row to delete.  If argv[0] is NULL then no
73639** deletion occurs.  The argv[1] element is the rowid of the new
73640** row.  This can be NULL to have the virtual table select the new
73641** rowid for itself.  The subsequent elements in the array are
73642** the values of columns in the new row.
73643**
73644** If P2==1 then no insert is performed.  argv[0] is the rowid of
73645** a row to delete.
73646**
73647** P1 is a boolean flag. If it is set to true and the xUpdate call
73648** is successful, then the value returned by sqlite3_last_insert_rowid()
73649** is set to the value of the rowid for the row just inserted.
73650**
73651** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
73652** apply in the case of a constraint failure on an insert or update.
73653*/
73654case OP_VUpdate: {
73655  sqlite3_vtab *pVtab;
73656  sqlite3_module *pModule;
73657  int nArg;
73658  int i;
73659  sqlite_int64 rowid;
73660  Mem **apArg;
73661  Mem *pX;
73662
73663  assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
73664       || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
73665  );
73666  assert( p->readOnly==0 );
73667  pVtab = pOp->p4.pVtab->pVtab;
73668  pModule = (sqlite3_module *)pVtab->pModule;
73669  nArg = pOp->p2;
73670  assert( pOp->p4type==P4_VTAB );
73671  if( ALWAYS(pModule->xUpdate) ){
73672    u8 vtabOnConflict = db->vtabOnConflict;
73673    apArg = p->apArg;
73674    pX = &aMem[pOp->p3];
73675    for(i=0; i<nArg; i++){
73676      assert( memIsValid(pX) );
73677      memAboutToChange(p, pX);
73678      apArg[i] = pX;
73679      pX++;
73680    }
73681    db->vtabOnConflict = pOp->p5;
73682    rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
73683    db->vtabOnConflict = vtabOnConflict;
73684    sqlite3VtabImportErrmsg(p, pVtab);
73685    if( rc==SQLITE_OK && pOp->p1 ){
73686      assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
73687      db->lastRowid = lastRowid = rowid;
73688    }
73689    if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
73690      if( pOp->p5==OE_Ignore ){
73691        rc = SQLITE_OK;
73692      }else{
73693        p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
73694      }
73695    }else{
73696      p->nChange++;
73697    }
73698  }
73699  break;
73700}
73701#endif /* SQLITE_OMIT_VIRTUALTABLE */
73702
73703#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
73704/* Opcode: Pagecount P1 P2 * * *
73705**
73706** Write the current number of pages in database P1 to memory cell P2.
73707*/
73708case OP_Pagecount: {            /* out2-prerelease */
73709  pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
73710  break;
73711}
73712#endif
73713
73714
73715#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
73716/* Opcode: MaxPgcnt P1 P2 P3 * *
73717**
73718** Try to set the maximum page count for database P1 to the value in P3.
73719** Do not let the maximum page count fall below the current page count and
73720** do not change the maximum page count value if P3==0.
73721**
73722** Store the maximum page count after the change in register P2.
73723*/
73724case OP_MaxPgcnt: {            /* out2-prerelease */
73725  unsigned int newMax;
73726  Btree *pBt;
73727
73728  pBt = db->aDb[pOp->p1].pBt;
73729  newMax = 0;
73730  if( pOp->p3 ){
73731    newMax = sqlite3BtreeLastPage(pBt);
73732    if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
73733  }
73734  pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
73735  break;
73736}
73737#endif
73738
73739
73740/* Opcode: Init * P2 * P4 *
73741** Synopsis:  Start at P2
73742**
73743** Programs contain a single instance of this opcode as the very first
73744** opcode.
73745**
73746** If tracing is enabled (by the sqlite3_trace()) interface, then
73747** the UTF-8 string contained in P4 is emitted on the trace callback.
73748** Or if P4 is blank, use the string returned by sqlite3_sql().
73749**
73750** If P2 is not zero, jump to instruction P2.
73751*/
73752case OP_Init: {          /* jump */
73753  char *zTrace;
73754  char *z;
73755
73756  if( pOp->p2 ){
73757    pc = pOp->p2 - 1;
73758  }
73759#ifndef SQLITE_OMIT_TRACE
73760  if( db->xTrace
73761   && !p->doingRerun
73762   && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
73763  ){
73764    z = sqlite3VdbeExpandSql(p, zTrace);
73765    db->xTrace(db->pTraceArg, z);
73766    sqlite3DbFree(db, z);
73767  }
73768#ifdef SQLITE_USE_FCNTL_TRACE
73769  zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
73770  if( zTrace ){
73771    int i;
73772    for(i=0; i<db->nDb; i++){
73773      if( (MASKBIT(i) & p->btreeMask)==0 ) continue;
73774      sqlite3_file_control(db, db->aDb[i].zName, SQLITE_FCNTL_TRACE, zTrace);
73775    }
73776  }
73777#endif /* SQLITE_USE_FCNTL_TRACE */
73778#ifdef SQLITE_DEBUG
73779  if( (db->flags & SQLITE_SqlTrace)!=0
73780   && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
73781  ){
73782    sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
73783  }
73784#endif /* SQLITE_DEBUG */
73785#endif /* SQLITE_OMIT_TRACE */
73786  break;
73787}
73788
73789
73790/* Opcode: Noop * * * * *
73791**
73792** Do nothing.  This instruction is often useful as a jump
73793** destination.
73794*/
73795/*
73796** The magic Explain opcode are only inserted when explain==2 (which
73797** is to say when the EXPLAIN QUERY PLAN syntax is used.)
73798** This opcode records information from the optimizer.  It is the
73799** the same as a no-op.  This opcodesnever appears in a real VM program.
73800*/
73801default: {          /* This is really OP_Noop and OP_Explain */
73802  assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
73803  break;
73804}
73805
73806/*****************************************************************************
73807** The cases of the switch statement above this line should all be indented
73808** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
73809** readability.  From this point on down, the normal indentation rules are
73810** restored.
73811*****************************************************************************/
73812    }
73813
73814#ifdef VDBE_PROFILE
73815    {
73816      u64 endTime = sqlite3Hwtime();
73817      if( endTime>start ) pOp->cycles += endTime - start;
73818      pOp->cnt++;
73819    }
73820#endif
73821
73822    /* The following code adds nothing to the actual functionality
73823    ** of the program.  It is only here for testing and debugging.
73824    ** On the other hand, it does burn CPU cycles every time through
73825    ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
73826    */
73827#ifndef NDEBUG
73828    assert( pc>=-1 && pc<p->nOp );
73829
73830#ifdef SQLITE_DEBUG
73831    if( db->flags & SQLITE_VdbeTrace ){
73832      if( rc!=0 ) printf("rc=%d\n",rc);
73833      if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
73834        registerTrace(pOp->p2, &aMem[pOp->p2]);
73835      }
73836      if( pOp->opflags & OPFLG_OUT3 ){
73837        registerTrace(pOp->p3, &aMem[pOp->p3]);
73838      }
73839    }
73840#endif  /* SQLITE_DEBUG */
73841#endif  /* NDEBUG */
73842  }  /* The end of the for(;;) loop the loops through opcodes */
73843
73844  /* If we reach this point, it means that execution is finished with
73845  ** an error of some kind.
73846  */
73847vdbe_error_halt:
73848  assert( rc );
73849  p->rc = rc;
73850  testcase( sqlite3GlobalConfig.xLog!=0 );
73851  sqlite3_log(rc, "statement aborts at %d: [%s] %s",
73852                   pc, p->zSql, p->zErrMsg);
73853  sqlite3VdbeHalt(p);
73854  if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
73855  rc = SQLITE_ERROR;
73856  if( resetSchemaOnFault>0 ){
73857    sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
73858  }
73859
73860  /* This is the only way out of this procedure.  We have to
73861  ** release the mutexes on btrees that were acquired at the
73862  ** top. */
73863vdbe_return:
73864  db->lastRowid = lastRowid;
73865  testcase( nVmStep>0 );
73866  p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
73867  sqlite3VdbeLeave(p);
73868  return rc;
73869
73870  /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
73871  ** is encountered.
73872  */
73873too_big:
73874  sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
73875  rc = SQLITE_TOOBIG;
73876  goto vdbe_error_halt;
73877
73878  /* Jump to here if a malloc() fails.
73879  */
73880no_mem:
73881  db->mallocFailed = 1;
73882  sqlite3SetString(&p->zErrMsg, db, "out of memory");
73883  rc = SQLITE_NOMEM;
73884  goto vdbe_error_halt;
73885
73886  /* Jump to here for any other kind of fatal error.  The "rc" variable
73887  ** should hold the error number.
73888  */
73889abort_due_to_error:
73890  assert( p->zErrMsg==0 );
73891  if( db->mallocFailed ) rc = SQLITE_NOMEM;
73892  if( rc!=SQLITE_IOERR_NOMEM ){
73893    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
73894  }
73895  goto vdbe_error_halt;
73896
73897  /* Jump to here if the sqlite3_interrupt() API sets the interrupt
73898  ** flag.
73899  */
73900abort_due_to_interrupt:
73901  assert( db->u1.isInterrupted );
73902  rc = SQLITE_INTERRUPT;
73903  p->rc = rc;
73904  sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
73905  goto vdbe_error_halt;
73906}
73907
73908
73909/************** End of vdbe.c ************************************************/
73910/************** Begin file vdbeblob.c ****************************************/
73911/*
73912** 2007 May 1
73913**
73914** The author disclaims copyright to this source code.  In place of
73915** a legal notice, here is a blessing:
73916**
73917**    May you do good and not evil.
73918**    May you find forgiveness for yourself and forgive others.
73919**    May you share freely, never taking more than you give.
73920**
73921*************************************************************************
73922**
73923** This file contains code used to implement incremental BLOB I/O.
73924*/
73925
73926
73927#ifndef SQLITE_OMIT_INCRBLOB
73928
73929/*
73930** Valid sqlite3_blob* handles point to Incrblob structures.
73931*/
73932typedef struct Incrblob Incrblob;
73933struct Incrblob {
73934  int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
73935  int nByte;              /* Size of open blob, in bytes */
73936  int iOffset;            /* Byte offset of blob in cursor data */
73937  int iCol;               /* Table column this handle is open on */
73938  BtCursor *pCsr;         /* Cursor pointing at blob row */
73939  sqlite3_stmt *pStmt;    /* Statement holding cursor open */
73940  sqlite3 *db;            /* The associated database */
73941};
73942
73943
73944/*
73945** This function is used by both blob_open() and blob_reopen(). It seeks
73946** the b-tree cursor associated with blob handle p to point to row iRow.
73947** If successful, SQLITE_OK is returned and subsequent calls to
73948** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
73949**
73950** If an error occurs, or if the specified row does not exist or does not
73951** contain a value of type TEXT or BLOB in the column nominated when the
73952** blob handle was opened, then an error code is returned and *pzErr may
73953** be set to point to a buffer containing an error message. It is the
73954** responsibility of the caller to free the error message buffer using
73955** sqlite3DbFree().
73956**
73957** If an error does occur, then the b-tree cursor is closed. All subsequent
73958** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
73959** immediately return SQLITE_ABORT.
73960*/
73961static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
73962  int rc;                         /* Error code */
73963  char *zErr = 0;                 /* Error message */
73964  Vdbe *v = (Vdbe *)p->pStmt;
73965
73966  /* Set the value of the SQL statements only variable to integer iRow.
73967  ** This is done directly instead of using sqlite3_bind_int64() to avoid
73968  ** triggering asserts related to mutexes.
73969  */
73970  assert( v->aVar[0].flags&MEM_Int );
73971  v->aVar[0].u.i = iRow;
73972
73973  rc = sqlite3_step(p->pStmt);
73974  if( rc==SQLITE_ROW ){
73975    VdbeCursor *pC = v->apCsr[0];
73976    u32 type = pC->aType[p->iCol];
73977    if( type<12 ){
73978      zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
73979          type==0?"null": type==7?"real": "integer"
73980      );
73981      rc = SQLITE_ERROR;
73982      sqlite3_finalize(p->pStmt);
73983      p->pStmt = 0;
73984    }else{
73985      p->iOffset = pC->aType[p->iCol + pC->nField];
73986      p->nByte = sqlite3VdbeSerialTypeLen(type);
73987      p->pCsr =  pC->pCursor;
73988      sqlite3BtreeIncrblobCursor(p->pCsr);
73989    }
73990  }
73991
73992  if( rc==SQLITE_ROW ){
73993    rc = SQLITE_OK;
73994  }else if( p->pStmt ){
73995    rc = sqlite3_finalize(p->pStmt);
73996    p->pStmt = 0;
73997    if( rc==SQLITE_OK ){
73998      zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
73999      rc = SQLITE_ERROR;
74000    }else{
74001      zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
74002    }
74003  }
74004
74005  assert( rc!=SQLITE_OK || zErr==0 );
74006  assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
74007
74008  *pzErr = zErr;
74009  return rc;
74010}
74011
74012/*
74013** Open a blob handle.
74014*/
74015SQLITE_API int sqlite3_blob_open(
74016  sqlite3* db,            /* The database connection */
74017  const char *zDb,        /* The attached database containing the blob */
74018  const char *zTable,     /* The table containing the blob */
74019  const char *zColumn,    /* The column containing the blob */
74020  sqlite_int64 iRow,      /* The row containing the glob */
74021  int flags,              /* True -> read/write access, false -> read-only */
74022  sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
74023){
74024  int nAttempt = 0;
74025  int iCol;               /* Index of zColumn in row-record */
74026
74027  /* This VDBE program seeks a btree cursor to the identified
74028  ** db/table/row entry. The reason for using a vdbe program instead
74029  ** of writing code to use the b-tree layer directly is that the
74030  ** vdbe program will take advantage of the various transaction,
74031  ** locking and error handling infrastructure built into the vdbe.
74032  **
74033  ** After seeking the cursor, the vdbe executes an OP_ResultRow.
74034  ** Code external to the Vdbe then "borrows" the b-tree cursor and
74035  ** uses it to implement the blob_read(), blob_write() and
74036  ** blob_bytes() functions.
74037  **
74038  ** The sqlite3_blob_close() function finalizes the vdbe program,
74039  ** which closes the b-tree cursor and (possibly) commits the
74040  ** transaction.
74041  */
74042  static const int iLn = VDBE_OFFSET_LINENO(4);
74043  static const VdbeOpList openBlob[] = {
74044    /* {OP_Transaction, 0, 0, 0},  // 0: Inserted separately */
74045    {OP_TableLock, 0, 0, 0},       /* 1: Acquire a read or write lock */
74046    /* One of the following two instructions is replaced by an OP_Noop. */
74047    {OP_OpenRead, 0, 0, 0},        /* 2: Open cursor 0 for reading */
74048    {OP_OpenWrite, 0, 0, 0},       /* 3: Open cursor 0 for read/write */
74049    {OP_Variable, 1, 1, 1},        /* 4: Push the rowid to the stack */
74050    {OP_NotExists, 0, 10, 1},      /* 5: Seek the cursor */
74051    {OP_Column, 0, 0, 1},          /* 6  */
74052    {OP_ResultRow, 1, 0, 0},       /* 7  */
74053    {OP_Goto, 0, 4, 0},            /* 8  */
74054    {OP_Close, 0, 0, 0},           /* 9  */
74055    {OP_Halt, 0, 0, 0},            /* 10 */
74056  };
74057
74058  int rc = SQLITE_OK;
74059  char *zErr = 0;
74060  Table *pTab;
74061  Parse *pParse = 0;
74062  Incrblob *pBlob = 0;
74063
74064  flags = !!flags;                /* flags = (flags ? 1 : 0); */
74065  *ppBlob = 0;
74066
74067  sqlite3_mutex_enter(db->mutex);
74068
74069  pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
74070  if( !pBlob ) goto blob_open_out;
74071  pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
74072  if( !pParse ) goto blob_open_out;
74073
74074  do {
74075    memset(pParse, 0, sizeof(Parse));
74076    pParse->db = db;
74077    sqlite3DbFree(db, zErr);
74078    zErr = 0;
74079
74080    sqlite3BtreeEnterAll(db);
74081    pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
74082    if( pTab && IsVirtual(pTab) ){
74083      pTab = 0;
74084      sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
74085    }
74086    if( pTab && !HasRowid(pTab) ){
74087      pTab = 0;
74088      sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable);
74089    }
74090#ifndef SQLITE_OMIT_VIEW
74091    if( pTab && pTab->pSelect ){
74092      pTab = 0;
74093      sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
74094    }
74095#endif
74096    if( !pTab ){
74097      if( pParse->zErrMsg ){
74098        sqlite3DbFree(db, zErr);
74099        zErr = pParse->zErrMsg;
74100        pParse->zErrMsg = 0;
74101      }
74102      rc = SQLITE_ERROR;
74103      sqlite3BtreeLeaveAll(db);
74104      goto blob_open_out;
74105    }
74106
74107    /* Now search pTab for the exact column. */
74108    for(iCol=0; iCol<pTab->nCol; iCol++) {
74109      if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
74110        break;
74111      }
74112    }
74113    if( iCol==pTab->nCol ){
74114      sqlite3DbFree(db, zErr);
74115      zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
74116      rc = SQLITE_ERROR;
74117      sqlite3BtreeLeaveAll(db);
74118      goto blob_open_out;
74119    }
74120
74121    /* If the value is being opened for writing, check that the
74122    ** column is not indexed, and that it is not part of a foreign key.
74123    ** It is against the rules to open a column to which either of these
74124    ** descriptions applies for writing.  */
74125    if( flags ){
74126      const char *zFault = 0;
74127      Index *pIdx;
74128#ifndef SQLITE_OMIT_FOREIGN_KEY
74129      if( db->flags&SQLITE_ForeignKeys ){
74130        /* Check that the column is not part of an FK child key definition. It
74131        ** is not necessary to check if it is part of a parent key, as parent
74132        ** key columns must be indexed. The check below will pick up this
74133        ** case.  */
74134        FKey *pFKey;
74135        for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
74136          int j;
74137          for(j=0; j<pFKey->nCol; j++){
74138            if( pFKey->aCol[j].iFrom==iCol ){
74139              zFault = "foreign key";
74140            }
74141          }
74142        }
74143      }
74144#endif
74145      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
74146        int j;
74147        for(j=0; j<pIdx->nKeyCol; j++){
74148          if( pIdx->aiColumn[j]==iCol ){
74149            zFault = "indexed";
74150          }
74151        }
74152      }
74153      if( zFault ){
74154        sqlite3DbFree(db, zErr);
74155        zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
74156        rc = SQLITE_ERROR;
74157        sqlite3BtreeLeaveAll(db);
74158        goto blob_open_out;
74159      }
74160    }
74161
74162    pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse);
74163    assert( pBlob->pStmt || db->mallocFailed );
74164    if( pBlob->pStmt ){
74165      Vdbe *v = (Vdbe *)pBlob->pStmt;
74166      int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
74167
74168
74169      sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, flags,
74170                           pTab->pSchema->schema_cookie,
74171                           pTab->pSchema->iGeneration);
74172      sqlite3VdbeChangeP5(v, 1);
74173      sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
74174
74175      /* Make sure a mutex is held on the table to be accessed */
74176      sqlite3VdbeUsesBtree(v, iDb);
74177
74178      /* Configure the OP_TableLock instruction */
74179#ifdef SQLITE_OMIT_SHARED_CACHE
74180      sqlite3VdbeChangeToNoop(v, 1);
74181#else
74182      sqlite3VdbeChangeP1(v, 1, iDb);
74183      sqlite3VdbeChangeP2(v, 1, pTab->tnum);
74184      sqlite3VdbeChangeP3(v, 1, flags);
74185      sqlite3VdbeChangeP4(v, 1, pTab->zName, P4_TRANSIENT);
74186#endif
74187
74188      /* Remove either the OP_OpenWrite or OpenRead. Set the P2
74189      ** parameter of the other to pTab->tnum.  */
74190      sqlite3VdbeChangeToNoop(v, 3 - flags);
74191      sqlite3VdbeChangeP2(v, 2 + flags, pTab->tnum);
74192      sqlite3VdbeChangeP3(v, 2 + flags, iDb);
74193
74194      /* Configure the number of columns. Configure the cursor to
74195      ** think that the table has one more column than it really
74196      ** does. An OP_Column to retrieve this imaginary column will
74197      ** always return an SQL NULL. This is useful because it means
74198      ** we can invoke OP_Column to fill in the vdbe cursors type
74199      ** and offset cache without causing any IO.
74200      */
74201      sqlite3VdbeChangeP4(v, 2+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
74202      sqlite3VdbeChangeP2(v, 6, pTab->nCol);
74203      if( !db->mallocFailed ){
74204        pParse->nVar = 1;
74205        pParse->nMem = 1;
74206        pParse->nTab = 1;
74207        sqlite3VdbeMakeReady(v, pParse);
74208      }
74209    }
74210
74211    pBlob->flags = flags;
74212    pBlob->iCol = iCol;
74213    pBlob->db = db;
74214    sqlite3BtreeLeaveAll(db);
74215    if( db->mallocFailed ){
74216      goto blob_open_out;
74217    }
74218    sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
74219    rc = blobSeekToRow(pBlob, iRow, &zErr);
74220  } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
74221
74222blob_open_out:
74223  if( rc==SQLITE_OK && db->mallocFailed==0 ){
74224    *ppBlob = (sqlite3_blob *)pBlob;
74225  }else{
74226    if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
74227    sqlite3DbFree(db, pBlob);
74228  }
74229  sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
74230  sqlite3DbFree(db, zErr);
74231  sqlite3ParserReset(pParse);
74232  sqlite3StackFree(db, pParse);
74233  rc = sqlite3ApiExit(db, rc);
74234  sqlite3_mutex_leave(db->mutex);
74235  return rc;
74236}
74237
74238/*
74239** Close a blob handle that was previously created using
74240** sqlite3_blob_open().
74241*/
74242SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
74243  Incrblob *p = (Incrblob *)pBlob;
74244  int rc;
74245  sqlite3 *db;
74246
74247  if( p ){
74248    db = p->db;
74249    sqlite3_mutex_enter(db->mutex);
74250    rc = sqlite3_finalize(p->pStmt);
74251    sqlite3DbFree(db, p);
74252    sqlite3_mutex_leave(db->mutex);
74253  }else{
74254    rc = SQLITE_OK;
74255  }
74256  return rc;
74257}
74258
74259/*
74260** Perform a read or write operation on a blob
74261*/
74262static int blobReadWrite(
74263  sqlite3_blob *pBlob,
74264  void *z,
74265  int n,
74266  int iOffset,
74267  int (*xCall)(BtCursor*, u32, u32, void*)
74268){
74269  int rc;
74270  Incrblob *p = (Incrblob *)pBlob;
74271  Vdbe *v;
74272  sqlite3 *db;
74273
74274  if( p==0 ) return SQLITE_MISUSE_BKPT;
74275  db = p->db;
74276  sqlite3_mutex_enter(db->mutex);
74277  v = (Vdbe*)p->pStmt;
74278
74279  if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
74280    /* Request is out of range. Return a transient error. */
74281    rc = SQLITE_ERROR;
74282    sqlite3Error(db, SQLITE_ERROR, 0);
74283  }else if( v==0 ){
74284    /* If there is no statement handle, then the blob-handle has
74285    ** already been invalidated. Return SQLITE_ABORT in this case.
74286    */
74287    rc = SQLITE_ABORT;
74288  }else{
74289    /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
74290    ** returned, clean-up the statement handle.
74291    */
74292    assert( db == v->db );
74293    sqlite3BtreeEnterCursor(p->pCsr);
74294    rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
74295    sqlite3BtreeLeaveCursor(p->pCsr);
74296    if( rc==SQLITE_ABORT ){
74297      sqlite3VdbeFinalize(v);
74298      p->pStmt = 0;
74299    }else{
74300      db->errCode = rc;
74301      v->rc = rc;
74302    }
74303  }
74304  rc = sqlite3ApiExit(db, rc);
74305  sqlite3_mutex_leave(db->mutex);
74306  return rc;
74307}
74308
74309/*
74310** Read data from a blob handle.
74311*/
74312SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
74313  return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
74314}
74315
74316/*
74317** Write data to a blob handle.
74318*/
74319SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
74320  return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
74321}
74322
74323/*
74324** Query a blob handle for the size of the data.
74325**
74326** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
74327** so no mutex is required for access.
74328*/
74329SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
74330  Incrblob *p = (Incrblob *)pBlob;
74331  return (p && p->pStmt) ? p->nByte : 0;
74332}
74333
74334/*
74335** Move an existing blob handle to point to a different row of the same
74336** database table.
74337**
74338** If an error occurs, or if the specified row does not exist or does not
74339** contain a blob or text value, then an error code is returned and the
74340** database handle error code and message set. If this happens, then all
74341** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
74342** immediately return SQLITE_ABORT.
74343*/
74344SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
74345  int rc;
74346  Incrblob *p = (Incrblob *)pBlob;
74347  sqlite3 *db;
74348
74349  if( p==0 ) return SQLITE_MISUSE_BKPT;
74350  db = p->db;
74351  sqlite3_mutex_enter(db->mutex);
74352
74353  if( p->pStmt==0 ){
74354    /* If there is no statement handle, then the blob-handle has
74355    ** already been invalidated. Return SQLITE_ABORT in this case.
74356    */
74357    rc = SQLITE_ABORT;
74358  }else{
74359    char *zErr;
74360    rc = blobSeekToRow(p, iRow, &zErr);
74361    if( rc!=SQLITE_OK ){
74362      sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
74363      sqlite3DbFree(db, zErr);
74364    }
74365    assert( rc!=SQLITE_SCHEMA );
74366  }
74367
74368  rc = sqlite3ApiExit(db, rc);
74369  assert( rc==SQLITE_OK || p->pStmt==0 );
74370  sqlite3_mutex_leave(db->mutex);
74371  return rc;
74372}
74373
74374#endif /* #ifndef SQLITE_OMIT_INCRBLOB */
74375
74376/************** End of vdbeblob.c ********************************************/
74377/************** Begin file vdbesort.c ****************************************/
74378/*
74379** 2011 July 9
74380**
74381** The author disclaims copyright to this source code.  In place of
74382** a legal notice, here is a blessing:
74383**
74384**    May you do good and not evil.
74385**    May you find forgiveness for yourself and forgive others.
74386**    May you share freely, never taking more than you give.
74387**
74388*************************************************************************
74389** This file contains code for the VdbeSorter object, used in concert with
74390** a VdbeCursor to sort large numbers of keys (as may be required, for
74391** example, by CREATE INDEX statements on tables too large to fit in main
74392** memory).
74393*/
74394
74395
74396
74397typedef struct VdbeSorterIter VdbeSorterIter;
74398typedef struct SorterRecord SorterRecord;
74399typedef struct FileWriter FileWriter;
74400
74401/*
74402** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES:
74403**
74404** As keys are added to the sorter, they are written to disk in a series
74405** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly
74406** the same as the cache-size allowed for temporary databases. In order
74407** to allow the caller to extract keys from the sorter in sorted order,
74408** all PMAs currently stored on disk must be merged together. This comment
74409** describes the data structure used to do so. The structure supports
74410** merging any number of arrays in a single pass with no redundant comparison
74411** operations.
74412**
74413** The aIter[] array contains an iterator for each of the PMAs being merged.
74414** An aIter[] iterator either points to a valid key or else is at EOF. For
74415** the purposes of the paragraphs below, we assume that the array is actually
74416** N elements in size, where N is the smallest power of 2 greater to or equal
74417** to the number of iterators being merged. The extra aIter[] elements are
74418** treated as if they are empty (always at EOF).
74419**
74420** The aTree[] array is also N elements in size. The value of N is stored in
74421** the VdbeSorter.nTree variable.
74422**
74423** The final (N/2) elements of aTree[] contain the results of comparing
74424** pairs of iterator keys together. Element i contains the result of
74425** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the
74426** aTree element is set to the index of it.
74427**
74428** For the purposes of this comparison, EOF is considered greater than any
74429** other key value. If the keys are equal (only possible with two EOF
74430** values), it doesn't matter which index is stored.
74431**
74432** The (N/4) elements of aTree[] that precede the final (N/2) described
74433** above contains the index of the smallest of each block of 4 iterators.
74434** And so on. So that aTree[1] contains the index of the iterator that
74435** currently points to the smallest key value. aTree[0] is unused.
74436**
74437** Example:
74438**
74439**     aIter[0] -> Banana
74440**     aIter[1] -> Feijoa
74441**     aIter[2] -> Elderberry
74442**     aIter[3] -> Currant
74443**     aIter[4] -> Grapefruit
74444**     aIter[5] -> Apple
74445**     aIter[6] -> Durian
74446**     aIter[7] -> EOF
74447**
74448**     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
74449**
74450** The current element is "Apple" (the value of the key indicated by
74451** iterator 5). When the Next() operation is invoked, iterator 5 will
74452** be advanced to the next key in its segment. Say the next key is
74453** "Eggplant":
74454**
74455**     aIter[5] -> Eggplant
74456**
74457** The contents of aTree[] are updated first by comparing the new iterator
74458** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator
74459** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
74460** The value of iterator 6 - "Durian" - is now smaller than that of iterator
74461** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
74462** so the value written into element 1 of the array is 0. As follows:
74463**
74464**     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
74465**
74466** In other words, each time we advance to the next sorter element, log2(N)
74467** key comparison operations are required, where N is the number of segments
74468** being merged (rounded up to the next power of 2).
74469*/
74470struct VdbeSorter {
74471  i64 iWriteOff;                  /* Current write offset within file pTemp1 */
74472  i64 iReadOff;                   /* Current read offset within file pTemp1 */
74473  int nInMemory;                  /* Current size of pRecord list as PMA */
74474  int nTree;                      /* Used size of aTree/aIter (power of 2) */
74475  int nPMA;                       /* Number of PMAs stored in pTemp1 */
74476  int mnPmaSize;                  /* Minimum PMA size, in bytes */
74477  int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
74478  VdbeSorterIter *aIter;          /* Array of iterators to merge */
74479  int *aTree;                     /* Current state of incremental merge */
74480  sqlite3_file *pTemp1;           /* PMA file 1 */
74481  SorterRecord *pRecord;          /* Head of in-memory record list */
74482  UnpackedRecord *pUnpacked;      /* Used to unpack keys */
74483};
74484
74485/*
74486** The following type is an iterator for a PMA. It caches the current key in
74487** variables nKey/aKey. If the iterator is at EOF, pFile==0.
74488*/
74489struct VdbeSorterIter {
74490  i64 iReadOff;                   /* Current read offset */
74491  i64 iEof;                       /* 1 byte past EOF for this iterator */
74492  int nAlloc;                     /* Bytes of space at aAlloc */
74493  int nKey;                       /* Number of bytes in key */
74494  sqlite3_file *pFile;            /* File iterator is reading from */
74495  u8 *aAlloc;                     /* Allocated space */
74496  u8 *aKey;                       /* Pointer to current key */
74497  u8 *aBuffer;                    /* Current read buffer */
74498  int nBuffer;                    /* Size of read buffer in bytes */
74499};
74500
74501/*
74502** An instance of this structure is used to organize the stream of records
74503** being written to files by the merge-sort code into aligned, page-sized
74504** blocks.  Doing all I/O in aligned page-sized blocks helps I/O to go
74505** faster on many operating systems.
74506*/
74507struct FileWriter {
74508  int eFWErr;                     /* Non-zero if in an error state */
74509  u8 *aBuffer;                    /* Pointer to write buffer */
74510  int nBuffer;                    /* Size of write buffer in bytes */
74511  int iBufStart;                  /* First byte of buffer to write */
74512  int iBufEnd;                    /* Last byte of buffer to write */
74513  i64 iWriteOff;                  /* Offset of start of buffer in file */
74514  sqlite3_file *pFile;            /* File to write to */
74515};
74516
74517/*
74518** A structure to store a single record. All in-memory records are connected
74519** together into a linked list headed at VdbeSorter.pRecord using the
74520** SorterRecord.pNext pointer.
74521*/
74522struct SorterRecord {
74523  void *pVal;
74524  int nVal;
74525  SorterRecord *pNext;
74526};
74527
74528/* Minimum allowable value for the VdbeSorter.nWorking variable */
74529#define SORTER_MIN_WORKING 10
74530
74531/* Maximum number of segments to merge in a single pass. */
74532#define SORTER_MAX_MERGE_COUNT 16
74533
74534/*
74535** Free all memory belonging to the VdbeSorterIter object passed as the second
74536** argument. All structure fields are set to zero before returning.
74537*/
74538static void vdbeSorterIterZero(sqlite3 *db, VdbeSorterIter *pIter){
74539  sqlite3DbFree(db, pIter->aAlloc);
74540  sqlite3DbFree(db, pIter->aBuffer);
74541  memset(pIter, 0, sizeof(VdbeSorterIter));
74542}
74543
74544/*
74545** Read nByte bytes of data from the stream of data iterated by object p.
74546** If successful, set *ppOut to point to a buffer containing the data
74547** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
74548** error code.
74549**
74550** The buffer indicated by *ppOut may only be considered valid until the
74551** next call to this function.
74552*/
74553static int vdbeSorterIterRead(
74554  sqlite3 *db,                    /* Database handle (for malloc) */
74555  VdbeSorterIter *p,              /* Iterator */
74556  int nByte,                      /* Bytes of data to read */
74557  u8 **ppOut                      /* OUT: Pointer to buffer containing data */
74558){
74559  int iBuf;                       /* Offset within buffer to read from */
74560  int nAvail;                     /* Bytes of data available in buffer */
74561  assert( p->aBuffer );
74562
74563  /* If there is no more data to be read from the buffer, read the next
74564  ** p->nBuffer bytes of data from the file into it. Or, if there are less
74565  ** than p->nBuffer bytes remaining in the PMA, read all remaining data.  */
74566  iBuf = p->iReadOff % p->nBuffer;
74567  if( iBuf==0 ){
74568    int nRead;                    /* Bytes to read from disk */
74569    int rc;                       /* sqlite3OsRead() return code */
74570
74571    /* Determine how many bytes of data to read. */
74572    if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
74573      nRead = p->nBuffer;
74574    }else{
74575      nRead = (int)(p->iEof - p->iReadOff);
74576    }
74577    assert( nRead>0 );
74578
74579    /* Read data from the file. Return early if an error occurs. */
74580    rc = sqlite3OsRead(p->pFile, p->aBuffer, nRead, p->iReadOff);
74581    assert( rc!=SQLITE_IOERR_SHORT_READ );
74582    if( rc!=SQLITE_OK ) return rc;
74583  }
74584  nAvail = p->nBuffer - iBuf;
74585
74586  if( nByte<=nAvail ){
74587    /* The requested data is available in the in-memory buffer. In this
74588    ** case there is no need to make a copy of the data, just return a
74589    ** pointer into the buffer to the caller.  */
74590    *ppOut = &p->aBuffer[iBuf];
74591    p->iReadOff += nByte;
74592  }else{
74593    /* The requested data is not all available in the in-memory buffer.
74594    ** In this case, allocate space at p->aAlloc[] to copy the requested
74595    ** range into. Then return a copy of pointer p->aAlloc to the caller.  */
74596    int nRem;                     /* Bytes remaining to copy */
74597
74598    /* Extend the p->aAlloc[] allocation if required. */
74599    if( p->nAlloc<nByte ){
74600      int nNew = p->nAlloc*2;
74601      while( nByte>nNew ) nNew = nNew*2;
74602      p->aAlloc = sqlite3DbReallocOrFree(db, p->aAlloc, nNew);
74603      if( !p->aAlloc ) return SQLITE_NOMEM;
74604      p->nAlloc = nNew;
74605    }
74606
74607    /* Copy as much data as is available in the buffer into the start of
74608    ** p->aAlloc[].  */
74609    memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
74610    p->iReadOff += nAvail;
74611    nRem = nByte - nAvail;
74612
74613    /* The following loop copies up to p->nBuffer bytes per iteration into
74614    ** the p->aAlloc[] buffer.  */
74615    while( nRem>0 ){
74616      int rc;                     /* vdbeSorterIterRead() return code */
74617      int nCopy;                  /* Number of bytes to copy */
74618      u8 *aNext;                  /* Pointer to buffer to copy data from */
74619
74620      nCopy = nRem;
74621      if( nRem>p->nBuffer ) nCopy = p->nBuffer;
74622      rc = vdbeSorterIterRead(db, p, nCopy, &aNext);
74623      if( rc!=SQLITE_OK ) return rc;
74624      assert( aNext!=p->aAlloc );
74625      memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
74626      nRem -= nCopy;
74627    }
74628
74629    *ppOut = p->aAlloc;
74630  }
74631
74632  return SQLITE_OK;
74633}
74634
74635/*
74636** Read a varint from the stream of data accessed by p. Set *pnOut to
74637** the value read.
74638*/
74639static int vdbeSorterIterVarint(sqlite3 *db, VdbeSorterIter *p, u64 *pnOut){
74640  int iBuf;
74641
74642  iBuf = p->iReadOff % p->nBuffer;
74643  if( iBuf && (p->nBuffer-iBuf)>=9 ){
74644    p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
74645  }else{
74646    u8 aVarint[16], *a;
74647    int i = 0, rc;
74648    do{
74649      rc = vdbeSorterIterRead(db, p, 1, &a);
74650      if( rc ) return rc;
74651      aVarint[(i++)&0xf] = a[0];
74652    }while( (a[0]&0x80)!=0 );
74653    sqlite3GetVarint(aVarint, pnOut);
74654  }
74655
74656  return SQLITE_OK;
74657}
74658
74659
74660/*
74661** Advance iterator pIter to the next key in its PMA. Return SQLITE_OK if
74662** no error occurs, or an SQLite error code if one does.
74663*/
74664static int vdbeSorterIterNext(
74665  sqlite3 *db,                    /* Database handle (for sqlite3DbMalloc() ) */
74666  VdbeSorterIter *pIter           /* Iterator to advance */
74667){
74668  int rc;                         /* Return Code */
74669  u64 nRec = 0;                   /* Size of record in bytes */
74670
74671  if( pIter->iReadOff>=pIter->iEof ){
74672    /* This is an EOF condition */
74673    vdbeSorterIterZero(db, pIter);
74674    return SQLITE_OK;
74675  }
74676
74677  rc = vdbeSorterIterVarint(db, pIter, &nRec);
74678  if( rc==SQLITE_OK ){
74679    pIter->nKey = (int)nRec;
74680    rc = vdbeSorterIterRead(db, pIter, (int)nRec, &pIter->aKey);
74681  }
74682
74683  return rc;
74684}
74685
74686/*
74687** Initialize iterator pIter to scan through the PMA stored in file pFile
74688** starting at offset iStart and ending at offset iEof-1. This function
74689** leaves the iterator pointing to the first key in the PMA (or EOF if the
74690** PMA is empty).
74691*/
74692static int vdbeSorterIterInit(
74693  sqlite3 *db,                    /* Database handle */
74694  const VdbeSorter *pSorter,      /* Sorter object */
74695  i64 iStart,                     /* Start offset in pFile */
74696  VdbeSorterIter *pIter,          /* Iterator to populate */
74697  i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
74698){
74699  int rc = SQLITE_OK;
74700  int nBuf;
74701
74702  nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
74703
74704  assert( pSorter->iWriteOff>iStart );
74705  assert( pIter->aAlloc==0 );
74706  assert( pIter->aBuffer==0 );
74707  pIter->pFile = pSorter->pTemp1;
74708  pIter->iReadOff = iStart;
74709  pIter->nAlloc = 128;
74710  pIter->aAlloc = (u8 *)sqlite3DbMallocRaw(db, pIter->nAlloc);
74711  pIter->nBuffer = nBuf;
74712  pIter->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
74713
74714  if( !pIter->aBuffer ){
74715    rc = SQLITE_NOMEM;
74716  }else{
74717    int iBuf;
74718
74719    iBuf = iStart % nBuf;
74720    if( iBuf ){
74721      int nRead = nBuf - iBuf;
74722      if( (iStart + nRead) > pSorter->iWriteOff ){
74723        nRead = (int)(pSorter->iWriteOff - iStart);
74724      }
74725      rc = sqlite3OsRead(
74726          pSorter->pTemp1, &pIter->aBuffer[iBuf], nRead, iStart
74727      );
74728    }
74729
74730    if( rc==SQLITE_OK ){
74731      u64 nByte;                       /* Size of PMA in bytes */
74732      pIter->iEof = pSorter->iWriteOff;
74733      rc = vdbeSorterIterVarint(db, pIter, &nByte);
74734      pIter->iEof = pIter->iReadOff + nByte;
74735      *pnByte += nByte;
74736    }
74737  }
74738
74739  if( rc==SQLITE_OK ){
74740    rc = vdbeSorterIterNext(db, pIter);
74741  }
74742  return rc;
74743}
74744
74745
74746/*
74747** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
74748** size nKey2 bytes).  Argument pKeyInfo supplies the collation functions
74749** used by the comparison. If an error occurs, return an SQLite error code.
74750** Otherwise, return SQLITE_OK and set *pRes to a negative, zero or positive
74751** value, depending on whether key1 is smaller, equal to or larger than key2.
74752**
74753** If the bOmitRowid argument is non-zero, assume both keys end in a rowid
74754** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid
74755** is true and key1 contains even a single NULL value, it is considered to
74756** be less than key2. Even if key2 also contains NULL values.
74757**
74758** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace
74759** has been allocated and contains an unpacked record that is used as key2.
74760*/
74761static void vdbeSorterCompare(
74762  const VdbeCursor *pCsr,         /* Cursor object (for pKeyInfo) */
74763  int nIgnore,                    /* Ignore the last nIgnore fields */
74764  const void *pKey1, int nKey1,   /* Left side of comparison */
74765  const void *pKey2, int nKey2,   /* Right side of comparison */
74766  int *pRes                       /* OUT: Result of comparison */
74767){
74768  KeyInfo *pKeyInfo = pCsr->pKeyInfo;
74769  VdbeSorter *pSorter = pCsr->pSorter;
74770  UnpackedRecord *r2 = pSorter->pUnpacked;
74771  int i;
74772
74773  if( pKey2 ){
74774    sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2);
74775  }
74776
74777  if( nIgnore ){
74778    r2->nField = pKeyInfo->nField - nIgnore;
74779    assert( r2->nField>0 );
74780    for(i=0; i<r2->nField; i++){
74781      if( r2->aMem[i].flags & MEM_Null ){
74782        *pRes = -1;
74783        return;
74784      }
74785    }
74786    assert( r2->default_rc==0 );
74787  }
74788
74789  *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2, 0);
74790}
74791
74792/*
74793** This function is called to compare two iterator keys when merging
74794** multiple b-tree segments. Parameter iOut is the index of the aTree[]
74795** value to recalculate.
74796*/
74797static int vdbeSorterDoCompare(const VdbeCursor *pCsr, int iOut){
74798  VdbeSorter *pSorter = pCsr->pSorter;
74799  int i1;
74800  int i2;
74801  int iRes;
74802  VdbeSorterIter *p1;
74803  VdbeSorterIter *p2;
74804
74805  assert( iOut<pSorter->nTree && iOut>0 );
74806
74807  if( iOut>=(pSorter->nTree/2) ){
74808    i1 = (iOut - pSorter->nTree/2) * 2;
74809    i2 = i1 + 1;
74810  }else{
74811    i1 = pSorter->aTree[iOut*2];
74812    i2 = pSorter->aTree[iOut*2+1];
74813  }
74814
74815  p1 = &pSorter->aIter[i1];
74816  p2 = &pSorter->aIter[i2];
74817
74818  if( p1->pFile==0 ){
74819    iRes = i2;
74820  }else if( p2->pFile==0 ){
74821    iRes = i1;
74822  }else{
74823    int res;
74824    assert( pCsr->pSorter->pUnpacked!=0 );  /* allocated in vdbeSorterMerge() */
74825    vdbeSorterCompare(
74826        pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res
74827    );
74828    if( res<=0 ){
74829      iRes = i1;
74830    }else{
74831      iRes = i2;
74832    }
74833  }
74834
74835  pSorter->aTree[iOut] = iRes;
74836  return SQLITE_OK;
74837}
74838
74839/*
74840** Initialize the temporary index cursor just opened as a sorter cursor.
74841*/
74842SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *db, VdbeCursor *pCsr){
74843  int pgsz;                       /* Page size of main database */
74844  int mxCache;                    /* Cache size */
74845  VdbeSorter *pSorter;            /* The new sorter */
74846  char *d;                        /* Dummy */
74847
74848  assert( pCsr->pKeyInfo && pCsr->pBt==0 );
74849  pCsr->pSorter = pSorter = sqlite3DbMallocZero(db, sizeof(VdbeSorter));
74850  if( pSorter==0 ){
74851    return SQLITE_NOMEM;
74852  }
74853
74854  pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d);
74855  if( pSorter->pUnpacked==0 ) return SQLITE_NOMEM;
74856  assert( pSorter->pUnpacked==(UnpackedRecord *)d );
74857
74858  if( !sqlite3TempInMemory(db) ){
74859    pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
74860    pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
74861    mxCache = db->aDb[0].pSchema->cache_size;
74862    if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
74863    pSorter->mxPmaSize = mxCache * pgsz;
74864  }
74865
74866  return SQLITE_OK;
74867}
74868
74869/*
74870** Free the list of sorted records starting at pRecord.
74871*/
74872static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
74873  SorterRecord *p;
74874  SorterRecord *pNext;
74875  for(p=pRecord; p; p=pNext){
74876    pNext = p->pNext;
74877    sqlite3DbFree(db, p);
74878  }
74879}
74880
74881/*
74882** Reset a sorting cursor back to its original empty state.
74883*/
74884SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
74885  if( pSorter->aIter ){
74886    int i;
74887    for(i=0; i<pSorter->nTree; i++){
74888      vdbeSorterIterZero(db, &pSorter->aIter[i]);
74889    }
74890    sqlite3DbFree(db, pSorter->aIter);
74891    pSorter->aIter = 0;
74892  }
74893  if( pSorter->pTemp1 ){
74894    sqlite3OsCloseFree(pSorter->pTemp1);
74895    pSorter->pTemp1 = 0;
74896  }
74897  vdbeSorterRecordFree(db, pSorter->pRecord);
74898  pSorter->pRecord = 0;
74899  pSorter->iWriteOff = 0;
74900  pSorter->iReadOff = 0;
74901  pSorter->nInMemory = 0;
74902  pSorter->nTree = 0;
74903  pSorter->nPMA = 0;
74904  pSorter->aTree = 0;
74905}
74906
74907
74908/*
74909** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
74910*/
74911SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
74912  VdbeSorter *pSorter = pCsr->pSorter;
74913  if( pSorter ){
74914    sqlite3VdbeSorterReset(db, pSorter);
74915    sqlite3DbFree(db, pSorter->pUnpacked);
74916    sqlite3DbFree(db, pSorter);
74917    pCsr->pSorter = 0;
74918  }
74919}
74920
74921/*
74922** Allocate space for a file-handle and open a temporary file. If successful,
74923** set *ppFile to point to the malloc'd file-handle and return SQLITE_OK.
74924** Otherwise, set *ppFile to 0 and return an SQLite error code.
74925*/
74926static int vdbeSorterOpenTempFile(sqlite3 *db, sqlite3_file **ppFile){
74927  int dummy;
74928  return sqlite3OsOpenMalloc(db->pVfs, 0, ppFile,
74929      SQLITE_OPEN_TEMP_JOURNAL |
74930      SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |
74931      SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &dummy
74932  );
74933}
74934
74935/*
74936** Merge the two sorted lists p1 and p2 into a single list.
74937** Set *ppOut to the head of the new list.
74938*/
74939static void vdbeSorterMerge(
74940  const VdbeCursor *pCsr,         /* For pKeyInfo */
74941  SorterRecord *p1,               /* First list to merge */
74942  SorterRecord *p2,               /* Second list to merge */
74943  SorterRecord **ppOut            /* OUT: Head of merged list */
74944){
74945  SorterRecord *pFinal = 0;
74946  SorterRecord **pp = &pFinal;
74947  void *pVal2 = p2 ? p2->pVal : 0;
74948
74949  while( p1 && p2 ){
74950    int res;
74951    vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res);
74952    if( res<=0 ){
74953      *pp = p1;
74954      pp = &p1->pNext;
74955      p1 = p1->pNext;
74956      pVal2 = 0;
74957    }else{
74958      *pp = p2;
74959       pp = &p2->pNext;
74960      p2 = p2->pNext;
74961      if( p2==0 ) break;
74962      pVal2 = p2->pVal;
74963    }
74964  }
74965  *pp = p1 ? p1 : p2;
74966  *ppOut = pFinal;
74967}
74968
74969/*
74970** Sort the linked list of records headed at pCsr->pRecord. Return SQLITE_OK
74971** if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if an error
74972** occurs.
74973*/
74974static int vdbeSorterSort(const VdbeCursor *pCsr){
74975  int i;
74976  SorterRecord **aSlot;
74977  SorterRecord *p;
74978  VdbeSorter *pSorter = pCsr->pSorter;
74979
74980  aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
74981  if( !aSlot ){
74982    return SQLITE_NOMEM;
74983  }
74984
74985  p = pSorter->pRecord;
74986  while( p ){
74987    SorterRecord *pNext = p->pNext;
74988    p->pNext = 0;
74989    for(i=0; aSlot[i]; i++){
74990      vdbeSorterMerge(pCsr, p, aSlot[i], &p);
74991      aSlot[i] = 0;
74992    }
74993    aSlot[i] = p;
74994    p = pNext;
74995  }
74996
74997  p = 0;
74998  for(i=0; i<64; i++){
74999    vdbeSorterMerge(pCsr, p, aSlot[i], &p);
75000  }
75001  pSorter->pRecord = p;
75002
75003  sqlite3_free(aSlot);
75004  return SQLITE_OK;
75005}
75006
75007/*
75008** Initialize a file-writer object.
75009*/
75010static void fileWriterInit(
75011  sqlite3 *db,                    /* Database (for malloc) */
75012  sqlite3_file *pFile,            /* File to write to */
75013  FileWriter *p,                  /* Object to populate */
75014  i64 iStart                      /* Offset of pFile to begin writing at */
75015){
75016  int nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
75017
75018  memset(p, 0, sizeof(FileWriter));
75019  p->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
75020  if( !p->aBuffer ){
75021    p->eFWErr = SQLITE_NOMEM;
75022  }else{
75023    p->iBufEnd = p->iBufStart = (iStart % nBuf);
75024    p->iWriteOff = iStart - p->iBufStart;
75025    p->nBuffer = nBuf;
75026    p->pFile = pFile;
75027  }
75028}
75029
75030/*
75031** Write nData bytes of data to the file-write object. Return SQLITE_OK
75032** if successful, or an SQLite error code if an error occurs.
75033*/
75034static void fileWriterWrite(FileWriter *p, u8 *pData, int nData){
75035  int nRem = nData;
75036  while( nRem>0 && p->eFWErr==0 ){
75037    int nCopy = nRem;
75038    if( nCopy>(p->nBuffer - p->iBufEnd) ){
75039      nCopy = p->nBuffer - p->iBufEnd;
75040    }
75041
75042    memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
75043    p->iBufEnd += nCopy;
75044    if( p->iBufEnd==p->nBuffer ){
75045      p->eFWErr = sqlite3OsWrite(p->pFile,
75046          &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
75047          p->iWriteOff + p->iBufStart
75048      );
75049      p->iBufStart = p->iBufEnd = 0;
75050      p->iWriteOff += p->nBuffer;
75051    }
75052    assert( p->iBufEnd<p->nBuffer );
75053
75054    nRem -= nCopy;
75055  }
75056}
75057
75058/*
75059** Flush any buffered data to disk and clean up the file-writer object.
75060** The results of using the file-writer after this call are undefined.
75061** Return SQLITE_OK if flushing the buffered data succeeds or is not
75062** required. Otherwise, return an SQLite error code.
75063**
75064** Before returning, set *piEof to the offset immediately following the
75065** last byte written to the file.
75066*/
75067static int fileWriterFinish(sqlite3 *db, FileWriter *p, i64 *piEof){
75068  int rc;
75069  if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
75070    p->eFWErr = sqlite3OsWrite(p->pFile,
75071        &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
75072        p->iWriteOff + p->iBufStart
75073    );
75074  }
75075  *piEof = (p->iWriteOff + p->iBufEnd);
75076  sqlite3DbFree(db, p->aBuffer);
75077  rc = p->eFWErr;
75078  memset(p, 0, sizeof(FileWriter));
75079  return rc;
75080}
75081
75082/*
75083** Write value iVal encoded as a varint to the file-write object. Return
75084** SQLITE_OK if successful, or an SQLite error code if an error occurs.
75085*/
75086static void fileWriterWriteVarint(FileWriter *p, u64 iVal){
75087  int nByte;
75088  u8 aByte[10];
75089  nByte = sqlite3PutVarint(aByte, iVal);
75090  fileWriterWrite(p, aByte, nByte);
75091}
75092
75093/*
75094** Write the current contents of the in-memory linked-list to a PMA. Return
75095** SQLITE_OK if successful, or an SQLite error code otherwise.
75096**
75097** The format of a PMA is:
75098**
75099**     * A varint. This varint contains the total number of bytes of content
75100**       in the PMA (not including the varint itself).
75101**
75102**     * One or more records packed end-to-end in order of ascending keys.
75103**       Each record consists of a varint followed by a blob of data (the
75104**       key). The varint is the number of bytes in the blob of data.
75105*/
75106static int vdbeSorterListToPMA(sqlite3 *db, const VdbeCursor *pCsr){
75107  int rc = SQLITE_OK;             /* Return code */
75108  VdbeSorter *pSorter = pCsr->pSorter;
75109  FileWriter writer;
75110
75111  memset(&writer, 0, sizeof(FileWriter));
75112
75113  if( pSorter->nInMemory==0 ){
75114    assert( pSorter->pRecord==0 );
75115    return rc;
75116  }
75117
75118  rc = vdbeSorterSort(pCsr);
75119
75120  /* If the first temporary PMA file has not been opened, open it now. */
75121  if( rc==SQLITE_OK && pSorter->pTemp1==0 ){
75122    rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1);
75123    assert( rc!=SQLITE_OK || pSorter->pTemp1 );
75124    assert( pSorter->iWriteOff==0 );
75125    assert( pSorter->nPMA==0 );
75126  }
75127
75128  if( rc==SQLITE_OK ){
75129    SorterRecord *p;
75130    SorterRecord *pNext = 0;
75131
75132    fileWriterInit(db, pSorter->pTemp1, &writer, pSorter->iWriteOff);
75133    pSorter->nPMA++;
75134    fileWriterWriteVarint(&writer, pSorter->nInMemory);
75135    for(p=pSorter->pRecord; p; p=pNext){
75136      pNext = p->pNext;
75137      fileWriterWriteVarint(&writer, p->nVal);
75138      fileWriterWrite(&writer, p->pVal, p->nVal);
75139      sqlite3DbFree(db, p);
75140    }
75141    pSorter->pRecord = p;
75142    rc = fileWriterFinish(db, &writer, &pSorter->iWriteOff);
75143  }
75144
75145  return rc;
75146}
75147
75148/*
75149** Add a record to the sorter.
75150*/
75151SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
75152  sqlite3 *db,                    /* Database handle */
75153  const VdbeCursor *pCsr,               /* Sorter cursor */
75154  Mem *pVal                       /* Memory cell containing record */
75155){
75156  VdbeSorter *pSorter = pCsr->pSorter;
75157  int rc = SQLITE_OK;             /* Return Code */
75158  SorterRecord *pNew;             /* New list element */
75159
75160  assert( pSorter );
75161  pSorter->nInMemory += sqlite3VarintLen(pVal->n) + pVal->n;
75162
75163  pNew = (SorterRecord *)sqlite3DbMallocRaw(db, pVal->n + sizeof(SorterRecord));
75164  if( pNew==0 ){
75165    rc = SQLITE_NOMEM;
75166  }else{
75167    pNew->pVal = (void *)&pNew[1];
75168    memcpy(pNew->pVal, pVal->z, pVal->n);
75169    pNew->nVal = pVal->n;
75170    pNew->pNext = pSorter->pRecord;
75171    pSorter->pRecord = pNew;
75172  }
75173
75174  /* See if the contents of the sorter should now be written out. They
75175  ** are written out when either of the following are true:
75176  **
75177  **   * The total memory allocated for the in-memory list is greater
75178  **     than (page-size * cache-size), or
75179  **
75180  **   * The total memory allocated for the in-memory list is greater
75181  **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
75182  */
75183  if( rc==SQLITE_OK && pSorter->mxPmaSize>0 && (
75184        (pSorter->nInMemory>pSorter->mxPmaSize)
75185     || (pSorter->nInMemory>pSorter->mnPmaSize && sqlite3HeapNearlyFull())
75186  )){
75187#ifdef SQLITE_DEBUG
75188    i64 nExpect = pSorter->iWriteOff
75189                + sqlite3VarintLen(pSorter->nInMemory)
75190                + pSorter->nInMemory;
75191#endif
75192    rc = vdbeSorterListToPMA(db, pCsr);
75193    pSorter->nInMemory = 0;
75194    assert( rc!=SQLITE_OK || (nExpect==pSorter->iWriteOff) );
75195  }
75196
75197  return rc;
75198}
75199
75200/*
75201** Helper function for sqlite3VdbeSorterRewind().
75202*/
75203static int vdbeSorterInitMerge(
75204  sqlite3 *db,                    /* Database handle */
75205  const VdbeCursor *pCsr,         /* Cursor handle for this sorter */
75206  i64 *pnByte                     /* Sum of bytes in all opened PMAs */
75207){
75208  VdbeSorter *pSorter = pCsr->pSorter;
75209  int rc = SQLITE_OK;             /* Return code */
75210  int i;                          /* Used to iterator through aIter[] */
75211  i64 nByte = 0;                  /* Total bytes in all opened PMAs */
75212
75213  /* Initialize the iterators. */
75214  for(i=0; i<SORTER_MAX_MERGE_COUNT; i++){
75215    VdbeSorterIter *pIter = &pSorter->aIter[i];
75216    rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte);
75217    pSorter->iReadOff = pIter->iEof;
75218    assert( rc!=SQLITE_OK || pSorter->iReadOff<=pSorter->iWriteOff );
75219    if( rc!=SQLITE_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break;
75220  }
75221
75222  /* Initialize the aTree[] array. */
75223  for(i=pSorter->nTree-1; rc==SQLITE_OK && i>0; i--){
75224    rc = vdbeSorterDoCompare(pCsr, i);
75225  }
75226
75227  *pnByte = nByte;
75228  return rc;
75229}
75230
75231/*
75232** Once the sorter has been populated, this function is called to prepare
75233** for iterating through its contents in sorted order.
75234*/
75235SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
75236  VdbeSorter *pSorter = pCsr->pSorter;
75237  int rc;                         /* Return code */
75238  sqlite3_file *pTemp2 = 0;       /* Second temp file to use */
75239  i64 iWrite2 = 0;                /* Write offset for pTemp2 */
75240  int nIter;                      /* Number of iterators used */
75241  int nByte;                      /* Bytes of space required for aIter/aTree */
75242  int N = 2;                      /* Power of 2 >= nIter */
75243
75244  assert( pSorter );
75245
75246  /* If no data has been written to disk, then do not do so now. Instead,
75247  ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
75248  ** from the in-memory list.  */
75249  if( pSorter->nPMA==0 ){
75250    *pbEof = !pSorter->pRecord;
75251    assert( pSorter->aTree==0 );
75252    return vdbeSorterSort(pCsr);
75253  }
75254
75255  /* Write the current in-memory list to a PMA. */
75256  rc = vdbeSorterListToPMA(db, pCsr);
75257  if( rc!=SQLITE_OK ) return rc;
75258
75259  /* Allocate space for aIter[] and aTree[]. */
75260  nIter = pSorter->nPMA;
75261  if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT;
75262  assert( nIter>0 );
75263  while( N<nIter ) N += N;
75264  nByte = N * (sizeof(int) + sizeof(VdbeSorterIter));
75265  pSorter->aIter = (VdbeSorterIter *)sqlite3DbMallocZero(db, nByte);
75266  if( !pSorter->aIter ) return SQLITE_NOMEM;
75267  pSorter->aTree = (int *)&pSorter->aIter[N];
75268  pSorter->nTree = N;
75269
75270  do {
75271    int iNew;                     /* Index of new, merged, PMA */
75272
75273    for(iNew=0;
75274        rc==SQLITE_OK && iNew*SORTER_MAX_MERGE_COUNT<pSorter->nPMA;
75275        iNew++
75276    ){
75277      int rc2;                    /* Return code from fileWriterFinish() */
75278      FileWriter writer;          /* Object used to write to disk */
75279      i64 nWrite;                 /* Number of bytes in new PMA */
75280
75281      memset(&writer, 0, sizeof(FileWriter));
75282
75283      /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1,
75284      ** initialize an iterator for each of them and break out of the loop.
75285      ** These iterators will be incrementally merged as the VDBE layer calls
75286      ** sqlite3VdbeSorterNext().
75287      **
75288      ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs,
75289      ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs
75290      ** are merged into a single PMA that is written to file pTemp2.
75291      */
75292      rc = vdbeSorterInitMerge(db, pCsr, &nWrite);
75293      assert( rc!=SQLITE_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile );
75294      if( rc!=SQLITE_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
75295        break;
75296      }
75297
75298      /* Open the second temp file, if it is not already open. */
75299      if( pTemp2==0 ){
75300        assert( iWrite2==0 );
75301        rc = vdbeSorterOpenTempFile(db, &pTemp2);
75302      }
75303
75304      if( rc==SQLITE_OK ){
75305        int bEof = 0;
75306        fileWriterInit(db, pTemp2, &writer, iWrite2);
75307        fileWriterWriteVarint(&writer, nWrite);
75308        while( rc==SQLITE_OK && bEof==0 ){
75309          VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ];
75310          assert( pIter->pFile );
75311
75312          fileWriterWriteVarint(&writer, pIter->nKey);
75313          fileWriterWrite(&writer, pIter->aKey, pIter->nKey);
75314          rc = sqlite3VdbeSorterNext(db, pCsr, &bEof);
75315        }
75316        rc2 = fileWriterFinish(db, &writer, &iWrite2);
75317        if( rc==SQLITE_OK ) rc = rc2;
75318      }
75319    }
75320
75321    if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
75322      break;
75323    }else{
75324      sqlite3_file *pTmp = pSorter->pTemp1;
75325      pSorter->nPMA = iNew;
75326      pSorter->pTemp1 = pTemp2;
75327      pTemp2 = pTmp;
75328      pSorter->iWriteOff = iWrite2;
75329      pSorter->iReadOff = 0;
75330      iWrite2 = 0;
75331    }
75332  }while( rc==SQLITE_OK );
75333
75334  if( pTemp2 ){
75335    sqlite3OsCloseFree(pTemp2);
75336  }
75337  *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
75338  return rc;
75339}
75340
75341/*
75342** Advance to the next element in the sorter.
75343*/
75344SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
75345  VdbeSorter *pSorter = pCsr->pSorter;
75346  int rc;                         /* Return code */
75347
75348  if( pSorter->aTree ){
75349    int iPrev = pSorter->aTree[1];/* Index of iterator to advance */
75350    rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]);
75351    if( rc==SQLITE_OK ){
75352      int i;                      /* Index of aTree[] to recalculate */
75353      VdbeSorterIter *pIter1;     /* First iterator to compare */
75354      VdbeSorterIter *pIter2;     /* Second iterator to compare */
75355      u8 *pKey2;                  /* To pIter2->aKey, or 0 if record cached */
75356
75357      /* Find the first two iterators to compare. The one that was just
75358      ** advanced (iPrev) and the one next to it in the array.  */
75359      pIter1 = &pSorter->aIter[(iPrev & 0xFFFE)];
75360      pIter2 = &pSorter->aIter[(iPrev | 0x0001)];
75361      pKey2 = pIter2->aKey;
75362
75363      for(i=(pSorter->nTree+iPrev)/2; i>0; i=i/2){
75364        /* Compare pIter1 and pIter2. Store the result in variable iRes. */
75365        int iRes;
75366        if( pIter1->pFile==0 ){
75367          iRes = +1;
75368        }else if( pIter2->pFile==0 ){
75369          iRes = -1;
75370        }else{
75371          vdbeSorterCompare(pCsr, 0,
75372              pIter1->aKey, pIter1->nKey, pKey2, pIter2->nKey, &iRes
75373          );
75374        }
75375
75376        /* If pIter1 contained the smaller value, set aTree[i] to its index.
75377        ** Then set pIter2 to the next iterator to compare to pIter1. In this
75378        ** case there is no cache of pIter2 in pSorter->pUnpacked, so set
75379        ** pKey2 to point to the record belonging to pIter2.
75380        **
75381        ** Alternatively, if pIter2 contains the smaller of the two values,
75382        ** set aTree[i] to its index and update pIter1. If vdbeSorterCompare()
75383        ** was actually called above, then pSorter->pUnpacked now contains
75384        ** a value equivalent to pIter2. So set pKey2 to NULL to prevent
75385        ** vdbeSorterCompare() from decoding pIter2 again.  */
75386        if( iRes<=0 ){
75387          pSorter->aTree[i] = (int)(pIter1 - pSorter->aIter);
75388          pIter2 = &pSorter->aIter[ pSorter->aTree[i ^ 0x0001] ];
75389          pKey2 = pIter2->aKey;
75390        }else{
75391          if( pIter1->pFile ) pKey2 = 0;
75392          pSorter->aTree[i] = (int)(pIter2 - pSorter->aIter);
75393          pIter1 = &pSorter->aIter[ pSorter->aTree[i ^ 0x0001] ];
75394        }
75395
75396      }
75397      *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
75398    }
75399  }else{
75400    SorterRecord *pFree = pSorter->pRecord;
75401    pSorter->pRecord = pFree->pNext;
75402    pFree->pNext = 0;
75403    vdbeSorterRecordFree(db, pFree);
75404    *pbEof = !pSorter->pRecord;
75405    rc = SQLITE_OK;
75406  }
75407  return rc;
75408}
75409
75410/*
75411** Return a pointer to a buffer owned by the sorter that contains the
75412** current key.
75413*/
75414static void *vdbeSorterRowkey(
75415  const VdbeSorter *pSorter,      /* Sorter object */
75416  int *pnKey                      /* OUT: Size of current key in bytes */
75417){
75418  void *pKey;
75419  if( pSorter->aTree ){
75420    VdbeSorterIter *pIter;
75421    pIter = &pSorter->aIter[ pSorter->aTree[1] ];
75422    *pnKey = pIter->nKey;
75423    pKey = pIter->aKey;
75424  }else{
75425    *pnKey = pSorter->pRecord->nVal;
75426    pKey = pSorter->pRecord->pVal;
75427  }
75428  return pKey;
75429}
75430
75431/*
75432** Copy the current sorter key into the memory cell pOut.
75433*/
75434SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
75435  VdbeSorter *pSorter = pCsr->pSorter;
75436  void *pKey; int nKey;           /* Sorter key to copy into pOut */
75437
75438  pKey = vdbeSorterRowkey(pSorter, &nKey);
75439  if( sqlite3VdbeMemGrow(pOut, nKey, 0) ){
75440    return SQLITE_NOMEM;
75441  }
75442  pOut->n = nKey;
75443  MemSetTypeFlag(pOut, MEM_Blob);
75444  memcpy(pOut->z, pKey, nKey);
75445
75446  return SQLITE_OK;
75447}
75448
75449/*
75450** Compare the key in memory cell pVal with the key that the sorter cursor
75451** passed as the first argument currently points to. For the purposes of
75452** the comparison, ignore the rowid field at the end of each record.
75453**
75454** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
75455** Otherwise, set *pRes to a negative, zero or positive value if the
75456** key in pVal is smaller than, equal to or larger than the current sorter
75457** key.
75458*/
75459SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
75460  const VdbeCursor *pCsr,         /* Sorter cursor */
75461  Mem *pVal,                      /* Value to compare to current sorter key */
75462  int nIgnore,                    /* Ignore this many fields at the end */
75463  int *pRes                       /* OUT: Result of comparison */
75464){
75465  VdbeSorter *pSorter = pCsr->pSorter;
75466  void *pKey; int nKey;           /* Sorter key to compare pVal with */
75467
75468  pKey = vdbeSorterRowkey(pSorter, &nKey);
75469  vdbeSorterCompare(pCsr, nIgnore, pVal->z, pVal->n, pKey, nKey, pRes);
75470  return SQLITE_OK;
75471}
75472
75473/************** End of vdbesort.c ********************************************/
75474/************** Begin file journal.c *****************************************/
75475/*
75476** 2007 August 22
75477**
75478** The author disclaims copyright to this source code.  In place of
75479** a legal notice, here is a blessing:
75480**
75481**    May you do good and not evil.
75482**    May you find forgiveness for yourself and forgive others.
75483**    May you share freely, never taking more than you give.
75484**
75485*************************************************************************
75486**
75487** This file implements a special kind of sqlite3_file object used
75488** by SQLite to create journal files if the atomic-write optimization
75489** is enabled.
75490**
75491** The distinctive characteristic of this sqlite3_file is that the
75492** actual on disk file is created lazily. When the file is created,
75493** the caller specifies a buffer size for an in-memory buffer to
75494** be used to service read() and write() requests. The actual file
75495** on disk is not created or populated until either:
75496**
75497**   1) The in-memory representation grows too large for the allocated
75498**      buffer, or
75499**   2) The sqlite3JournalCreate() function is called.
75500*/
75501#ifdef SQLITE_ENABLE_ATOMIC_WRITE
75502
75503
75504/*
75505** A JournalFile object is a subclass of sqlite3_file used by
75506** as an open file handle for journal files.
75507*/
75508struct JournalFile {
75509  sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
75510  int nBuf;                       /* Size of zBuf[] in bytes */
75511  char *zBuf;                     /* Space to buffer journal writes */
75512  int iSize;                      /* Amount of zBuf[] currently used */
75513  int flags;                      /* xOpen flags */
75514  sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
75515  sqlite3_file *pReal;            /* The "real" underlying file descriptor */
75516  const char *zJournal;           /* Name of the journal file */
75517};
75518typedef struct JournalFile JournalFile;
75519
75520/*
75521** If it does not already exists, create and populate the on-disk file
75522** for JournalFile p.
75523*/
75524static int createFile(JournalFile *p){
75525  int rc = SQLITE_OK;
75526  if( !p->pReal ){
75527    sqlite3_file *pReal = (sqlite3_file *)&p[1];
75528    rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
75529    if( rc==SQLITE_OK ){
75530      p->pReal = pReal;
75531      if( p->iSize>0 ){
75532        assert(p->iSize<=p->nBuf);
75533        rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
75534      }
75535      if( rc!=SQLITE_OK ){
75536        /* If an error occurred while writing to the file, close it before
75537        ** returning. This way, SQLite uses the in-memory journal data to
75538        ** roll back changes made to the internal page-cache before this
75539        ** function was called.  */
75540        sqlite3OsClose(pReal);
75541        p->pReal = 0;
75542      }
75543    }
75544  }
75545  return rc;
75546}
75547
75548/*
75549** Close the file.
75550*/
75551static int jrnlClose(sqlite3_file *pJfd){
75552  JournalFile *p = (JournalFile *)pJfd;
75553  if( p->pReal ){
75554    sqlite3OsClose(p->pReal);
75555  }
75556  sqlite3_free(p->zBuf);
75557  return SQLITE_OK;
75558}
75559
75560/*
75561** Read data from the file.
75562*/
75563static int jrnlRead(
75564  sqlite3_file *pJfd,    /* The journal file from which to read */
75565  void *zBuf,            /* Put the results here */
75566  int iAmt,              /* Number of bytes to read */
75567  sqlite_int64 iOfst     /* Begin reading at this offset */
75568){
75569  int rc = SQLITE_OK;
75570  JournalFile *p = (JournalFile *)pJfd;
75571  if( p->pReal ){
75572    rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
75573  }else if( (iAmt+iOfst)>p->iSize ){
75574    rc = SQLITE_IOERR_SHORT_READ;
75575  }else{
75576    memcpy(zBuf, &p->zBuf[iOfst], iAmt);
75577  }
75578  return rc;
75579}
75580
75581/*
75582** Write data to the file.
75583*/
75584static int jrnlWrite(
75585  sqlite3_file *pJfd,    /* The journal file into which to write */
75586  const void *zBuf,      /* Take data to be written from here */
75587  int iAmt,              /* Number of bytes to write */
75588  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
75589){
75590  int rc = SQLITE_OK;
75591  JournalFile *p = (JournalFile *)pJfd;
75592  if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
75593    rc = createFile(p);
75594  }
75595  if( rc==SQLITE_OK ){
75596    if( p->pReal ){
75597      rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
75598    }else{
75599      memcpy(&p->zBuf[iOfst], zBuf, iAmt);
75600      if( p->iSize<(iOfst+iAmt) ){
75601        p->iSize = (iOfst+iAmt);
75602      }
75603    }
75604  }
75605  return rc;
75606}
75607
75608/*
75609** Truncate the file.
75610*/
75611static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
75612  int rc = SQLITE_OK;
75613  JournalFile *p = (JournalFile *)pJfd;
75614  if( p->pReal ){
75615    rc = sqlite3OsTruncate(p->pReal, size);
75616  }else if( size<p->iSize ){
75617    p->iSize = size;
75618  }
75619  return rc;
75620}
75621
75622/*
75623** Sync the file.
75624*/
75625static int jrnlSync(sqlite3_file *pJfd, int flags){
75626  int rc;
75627  JournalFile *p = (JournalFile *)pJfd;
75628  if( p->pReal ){
75629    rc = sqlite3OsSync(p->pReal, flags);
75630  }else{
75631    rc = SQLITE_OK;
75632  }
75633  return rc;
75634}
75635
75636/*
75637** Query the size of the file in bytes.
75638*/
75639static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
75640  int rc = SQLITE_OK;
75641  JournalFile *p = (JournalFile *)pJfd;
75642  if( p->pReal ){
75643    rc = sqlite3OsFileSize(p->pReal, pSize);
75644  }else{
75645    *pSize = (sqlite_int64) p->iSize;
75646  }
75647  return rc;
75648}
75649
75650/*
75651** Table of methods for JournalFile sqlite3_file object.
75652*/
75653static struct sqlite3_io_methods JournalFileMethods = {
75654  1,             /* iVersion */
75655  jrnlClose,     /* xClose */
75656  jrnlRead,      /* xRead */
75657  jrnlWrite,     /* xWrite */
75658  jrnlTruncate,  /* xTruncate */
75659  jrnlSync,      /* xSync */
75660  jrnlFileSize,  /* xFileSize */
75661  0,             /* xLock */
75662  0,             /* xUnlock */
75663  0,             /* xCheckReservedLock */
75664  0,             /* xFileControl */
75665  0,             /* xSectorSize */
75666  0,             /* xDeviceCharacteristics */
75667  0,             /* xShmMap */
75668  0,             /* xShmLock */
75669  0,             /* xShmBarrier */
75670  0              /* xShmUnmap */
75671};
75672
75673/*
75674** Open a journal file.
75675*/
75676SQLITE_PRIVATE int sqlite3JournalOpen(
75677  sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
75678  const char *zName,         /* Name of the journal file */
75679  sqlite3_file *pJfd,        /* Preallocated, blank file handle */
75680  int flags,                 /* Opening flags */
75681  int nBuf                   /* Bytes buffered before opening the file */
75682){
75683  JournalFile *p = (JournalFile *)pJfd;
75684  memset(p, 0, sqlite3JournalSize(pVfs));
75685  if( nBuf>0 ){
75686    p->zBuf = sqlite3MallocZero(nBuf);
75687    if( !p->zBuf ){
75688      return SQLITE_NOMEM;
75689    }
75690  }else{
75691    return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
75692  }
75693  p->pMethod = &JournalFileMethods;
75694  p->nBuf = nBuf;
75695  p->flags = flags;
75696  p->zJournal = zName;
75697  p->pVfs = pVfs;
75698  return SQLITE_OK;
75699}
75700
75701/*
75702** If the argument p points to a JournalFile structure, and the underlying
75703** file has not yet been created, create it now.
75704*/
75705SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
75706  if( p->pMethods!=&JournalFileMethods ){
75707    return SQLITE_OK;
75708  }
75709  return createFile((JournalFile *)p);
75710}
75711
75712/*
75713** The file-handle passed as the only argument is guaranteed to be an open
75714** file. It may or may not be of class JournalFile. If the file is a
75715** JournalFile, and the underlying file on disk has not yet been opened,
75716** return 0. Otherwise, return 1.
75717*/
75718SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
75719  return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
75720}
75721
75722/*
75723** Return the number of bytes required to store a JournalFile that uses vfs
75724** pVfs to create the underlying on-disk files.
75725*/
75726SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
75727  return (pVfs->szOsFile+sizeof(JournalFile));
75728}
75729#endif
75730
75731/************** End of journal.c *********************************************/
75732/************** Begin file memjournal.c **************************************/
75733/*
75734** 2008 October 7
75735**
75736** The author disclaims copyright to this source code.  In place of
75737** a legal notice, here is a blessing:
75738**
75739**    May you do good and not evil.
75740**    May you find forgiveness for yourself and forgive others.
75741**    May you share freely, never taking more than you give.
75742**
75743*************************************************************************
75744**
75745** This file contains code use to implement an in-memory rollback journal.
75746** The in-memory rollback journal is used to journal transactions for
75747** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
75748*/
75749
75750/* Forward references to internal structures */
75751typedef struct MemJournal MemJournal;
75752typedef struct FilePoint FilePoint;
75753typedef struct FileChunk FileChunk;
75754
75755/* Space to hold the rollback journal is allocated in increments of
75756** this many bytes.
75757**
75758** The size chosen is a little less than a power of two.  That way,
75759** the FileChunk object will have a size that almost exactly fills
75760** a power-of-two allocation.  This mimimizes wasted space in power-of-two
75761** memory allocators.
75762*/
75763#define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
75764
75765/*
75766** The rollback journal is composed of a linked list of these structures.
75767*/
75768struct FileChunk {
75769  FileChunk *pNext;               /* Next chunk in the journal */
75770  u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
75771};
75772
75773/*
75774** An instance of this object serves as a cursor into the rollback journal.
75775** The cursor can be either for reading or writing.
75776*/
75777struct FilePoint {
75778  sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
75779  FileChunk *pChunk;              /* Specific chunk into which cursor points */
75780};
75781
75782/*
75783** This subclass is a subclass of sqlite3_file.  Each open memory-journal
75784** is an instance of this class.
75785*/
75786struct MemJournal {
75787  sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
75788  FileChunk *pFirst;              /* Head of in-memory chunk-list */
75789  FilePoint endpoint;             /* Pointer to the end of the file */
75790  FilePoint readpoint;            /* Pointer to the end of the last xRead() */
75791};
75792
75793/*
75794** Read data from the in-memory journal file.  This is the implementation
75795** of the sqlite3_vfs.xRead method.
75796*/
75797static int memjrnlRead(
75798  sqlite3_file *pJfd,    /* The journal file from which to read */
75799  void *zBuf,            /* Put the results here */
75800  int iAmt,              /* Number of bytes to read */
75801  sqlite_int64 iOfst     /* Begin reading at this offset */
75802){
75803  MemJournal *p = (MemJournal *)pJfd;
75804  u8 *zOut = zBuf;
75805  int nRead = iAmt;
75806  int iChunkOffset;
75807  FileChunk *pChunk;
75808
75809  /* SQLite never tries to read past the end of a rollback journal file */
75810  assert( iOfst+iAmt<=p->endpoint.iOffset );
75811
75812  if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
75813    sqlite3_int64 iOff = 0;
75814    for(pChunk=p->pFirst;
75815        ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
75816        pChunk=pChunk->pNext
75817    ){
75818      iOff += JOURNAL_CHUNKSIZE;
75819    }
75820  }else{
75821    pChunk = p->readpoint.pChunk;
75822  }
75823
75824  iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
75825  do {
75826    int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
75827    int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
75828    memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
75829    zOut += nCopy;
75830    nRead -= iSpace;
75831    iChunkOffset = 0;
75832  } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
75833  p->readpoint.iOffset = iOfst+iAmt;
75834  p->readpoint.pChunk = pChunk;
75835
75836  return SQLITE_OK;
75837}
75838
75839/*
75840** Write data to the file.
75841*/
75842static int memjrnlWrite(
75843  sqlite3_file *pJfd,    /* The journal file into which to write */
75844  const void *zBuf,      /* Take data to be written from here */
75845  int iAmt,              /* Number of bytes to write */
75846  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
75847){
75848  MemJournal *p = (MemJournal *)pJfd;
75849  int nWrite = iAmt;
75850  u8 *zWrite = (u8 *)zBuf;
75851
75852  /* An in-memory journal file should only ever be appended to. Random
75853  ** access writes are not required by sqlite.
75854  */
75855  assert( iOfst==p->endpoint.iOffset );
75856  UNUSED_PARAMETER(iOfst);
75857
75858  while( nWrite>0 ){
75859    FileChunk *pChunk = p->endpoint.pChunk;
75860    int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
75861    int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
75862
75863    if( iChunkOffset==0 ){
75864      /* New chunk is required to extend the file. */
75865      FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
75866      if( !pNew ){
75867        return SQLITE_IOERR_NOMEM;
75868      }
75869      pNew->pNext = 0;
75870      if( pChunk ){
75871        assert( p->pFirst );
75872        pChunk->pNext = pNew;
75873      }else{
75874        assert( !p->pFirst );
75875        p->pFirst = pNew;
75876      }
75877      p->endpoint.pChunk = pNew;
75878    }
75879
75880    memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
75881    zWrite += iSpace;
75882    nWrite -= iSpace;
75883    p->endpoint.iOffset += iSpace;
75884  }
75885
75886  return SQLITE_OK;
75887}
75888
75889/*
75890** Truncate the file.
75891*/
75892static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
75893  MemJournal *p = (MemJournal *)pJfd;
75894  FileChunk *pChunk;
75895  assert(size==0);
75896  UNUSED_PARAMETER(size);
75897  pChunk = p->pFirst;
75898  while( pChunk ){
75899    FileChunk *pTmp = pChunk;
75900    pChunk = pChunk->pNext;
75901    sqlite3_free(pTmp);
75902  }
75903  sqlite3MemJournalOpen(pJfd);
75904  return SQLITE_OK;
75905}
75906
75907/*
75908** Close the file.
75909*/
75910static int memjrnlClose(sqlite3_file *pJfd){
75911  memjrnlTruncate(pJfd, 0);
75912  return SQLITE_OK;
75913}
75914
75915
75916/*
75917** Sync the file.
75918**
75919** Syncing an in-memory journal is a no-op.  And, in fact, this routine
75920** is never called in a working implementation.  This implementation
75921** exists purely as a contingency, in case some malfunction in some other
75922** part of SQLite causes Sync to be called by mistake.
75923*/
75924static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
75925  UNUSED_PARAMETER2(NotUsed, NotUsed2);
75926  return SQLITE_OK;
75927}
75928
75929/*
75930** Query the size of the file in bytes.
75931*/
75932static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
75933  MemJournal *p = (MemJournal *)pJfd;
75934  *pSize = (sqlite_int64) p->endpoint.iOffset;
75935  return SQLITE_OK;
75936}
75937
75938/*
75939** Table of methods for MemJournal sqlite3_file object.
75940*/
75941static const struct sqlite3_io_methods MemJournalMethods = {
75942  1,                /* iVersion */
75943  memjrnlClose,     /* xClose */
75944  memjrnlRead,      /* xRead */
75945  memjrnlWrite,     /* xWrite */
75946  memjrnlTruncate,  /* xTruncate */
75947  memjrnlSync,      /* xSync */
75948  memjrnlFileSize,  /* xFileSize */
75949  0,                /* xLock */
75950  0,                /* xUnlock */
75951  0,                /* xCheckReservedLock */
75952  0,                /* xFileControl */
75953  0,                /* xSectorSize */
75954  0,                /* xDeviceCharacteristics */
75955  0,                /* xShmMap */
75956  0,                /* xShmLock */
75957  0,                /* xShmBarrier */
75958  0,                /* xShmUnmap */
75959  0,                /* xFetch */
75960  0                 /* xUnfetch */
75961};
75962
75963/*
75964** Open a journal file.
75965*/
75966SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
75967  MemJournal *p = (MemJournal *)pJfd;
75968  assert( EIGHT_BYTE_ALIGNMENT(p) );
75969  memset(p, 0, sqlite3MemJournalSize());
75970  p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
75971}
75972
75973/*
75974** Return true if the file-handle passed as an argument is
75975** an in-memory journal
75976*/
75977SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
75978  return pJfd->pMethods==&MemJournalMethods;
75979}
75980
75981/*
75982** Return the number of bytes required to store a MemJournal file descriptor.
75983*/
75984SQLITE_PRIVATE int sqlite3MemJournalSize(void){
75985  return sizeof(MemJournal);
75986}
75987
75988/************** End of memjournal.c ******************************************/
75989/************** Begin file walker.c ******************************************/
75990/*
75991** 2008 August 16
75992**
75993** The author disclaims copyright to this source code.  In place of
75994** a legal notice, here is a blessing:
75995**
75996**    May you do good and not evil.
75997**    May you find forgiveness for yourself and forgive others.
75998**    May you share freely, never taking more than you give.
75999**
76000*************************************************************************
76001** This file contains routines used for walking the parser tree for
76002** an SQL statement.
76003*/
76004/* #include <stdlib.h> */
76005/* #include <string.h> */
76006
76007
76008/*
76009** Walk an expression tree.  Invoke the callback once for each node
76010** of the expression, while decending.  (In other words, the callback
76011** is invoked before visiting children.)
76012**
76013** The return value from the callback should be one of the WRC_*
76014** constants to specify how to proceed with the walk.
76015**
76016**    WRC_Continue      Continue descending down the tree.
76017**
76018**    WRC_Prune         Do not descend into child nodes.  But allow
76019**                      the walk to continue with sibling nodes.
76020**
76021**    WRC_Abort         Do no more callbacks.  Unwind the stack and
76022**                      return the top-level walk call.
76023**
76024** The return value from this routine is WRC_Abort to abandon the tree walk
76025** and WRC_Continue to continue.
76026*/
76027SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
76028  int rc;
76029  if( pExpr==0 ) return WRC_Continue;
76030  testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
76031  testcase( ExprHasProperty(pExpr, EP_Reduced) );
76032  rc = pWalker->xExprCallback(pWalker, pExpr);
76033  if( rc==WRC_Continue
76034              && !ExprHasProperty(pExpr,EP_TokenOnly) ){
76035    if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
76036    if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
76037    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
76038      if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
76039    }else{
76040      if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
76041    }
76042  }
76043  return rc & WRC_Abort;
76044}
76045
76046/*
76047** Call sqlite3WalkExpr() for every expression in list p or until
76048** an abort request is seen.
76049*/
76050SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
76051  int i;
76052  struct ExprList_item *pItem;
76053  if( p ){
76054    for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
76055      if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
76056    }
76057  }
76058  return WRC_Continue;
76059}
76060
76061/*
76062** Walk all expressions associated with SELECT statement p.  Do
76063** not invoke the SELECT callback on p, but do (of course) invoke
76064** any expr callbacks and SELECT callbacks that come from subqueries.
76065** Return WRC_Abort or WRC_Continue.
76066*/
76067SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
76068  if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
76069  if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
76070  if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
76071  if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
76072  if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
76073  if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
76074  if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
76075  return WRC_Continue;
76076}
76077
76078/*
76079** Walk the parse trees associated with all subqueries in the
76080** FROM clause of SELECT statement p.  Do not invoke the select
76081** callback on p, but do invoke it on each FROM clause subquery
76082** and on any subqueries further down in the tree.  Return
76083** WRC_Abort or WRC_Continue;
76084*/
76085SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
76086  SrcList *pSrc;
76087  int i;
76088  struct SrcList_item *pItem;
76089
76090  pSrc = p->pSrc;
76091  if( ALWAYS(pSrc) ){
76092    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
76093      if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
76094        return WRC_Abort;
76095      }
76096    }
76097  }
76098  return WRC_Continue;
76099}
76100
76101/*
76102** Call sqlite3WalkExpr() for every expression in Select statement p.
76103** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
76104** on the compound select chain, p->pPrior.
76105**
76106** If it is not NULL, the xSelectCallback() callback is invoked before
76107** the walk of the expressions and FROM clause. The xSelectCallback2()
76108** method, if it is not NULL, is invoked following the walk of the
76109** expressions and FROM clause.
76110**
76111** Return WRC_Continue under normal conditions.  Return WRC_Abort if
76112** there is an abort request.
76113**
76114** If the Walker does not have an xSelectCallback() then this routine
76115** is a no-op returning WRC_Continue.
76116*/
76117SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
76118  int rc;
76119  if( p==0 || (pWalker->xSelectCallback==0 && pWalker->xSelectCallback2==0) ){
76120    return WRC_Continue;
76121  }
76122  rc = WRC_Continue;
76123  pWalker->walkerDepth++;
76124  while( p ){
76125    if( pWalker->xSelectCallback ){
76126       rc = pWalker->xSelectCallback(pWalker, p);
76127       if( rc ) break;
76128    }
76129    if( sqlite3WalkSelectExpr(pWalker, p)
76130     || sqlite3WalkSelectFrom(pWalker, p)
76131    ){
76132      pWalker->walkerDepth--;
76133      return WRC_Abort;
76134    }
76135    if( pWalker->xSelectCallback2 ){
76136      pWalker->xSelectCallback2(pWalker, p);
76137    }
76138    p = p->pPrior;
76139  }
76140  pWalker->walkerDepth--;
76141  return rc & WRC_Abort;
76142}
76143
76144/************** End of walker.c **********************************************/
76145/************** Begin file resolve.c *****************************************/
76146/*
76147** 2008 August 18
76148**
76149** The author disclaims copyright to this source code.  In place of
76150** a legal notice, here is a blessing:
76151**
76152**    May you do good and not evil.
76153**    May you find forgiveness for yourself and forgive others.
76154**    May you share freely, never taking more than you give.
76155**
76156*************************************************************************
76157**
76158** This file contains routines used for walking the parser tree and
76159** resolve all identifiers by associating them with a particular
76160** table and column.
76161*/
76162/* #include <stdlib.h> */
76163/* #include <string.h> */
76164
76165/*
76166** Walk the expression tree pExpr and increase the aggregate function
76167** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
76168** This needs to occur when copying a TK_AGG_FUNCTION node from an
76169** outer query into an inner subquery.
76170**
76171** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
76172** is a helper function - a callback for the tree walker.
76173*/
76174static int incrAggDepth(Walker *pWalker, Expr *pExpr){
76175  if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i;
76176  return WRC_Continue;
76177}
76178static void incrAggFunctionDepth(Expr *pExpr, int N){
76179  if( N>0 ){
76180    Walker w;
76181    memset(&w, 0, sizeof(w));
76182    w.xExprCallback = incrAggDepth;
76183    w.u.i = N;
76184    sqlite3WalkExpr(&w, pExpr);
76185  }
76186}
76187
76188/*
76189** Turn the pExpr expression into an alias for the iCol-th column of the
76190** result set in pEList.
76191**
76192** If the result set column is a simple column reference, then this routine
76193** makes an exact copy.  But for any other kind of expression, this
76194** routine make a copy of the result set column as the argument to the
76195** TK_AS operator.  The TK_AS operator causes the expression to be
76196** evaluated just once and then reused for each alias.
76197**
76198** The reason for suppressing the TK_AS term when the expression is a simple
76199** column reference is so that the column reference will be recognized as
76200** usable by indices within the WHERE clause processing logic.
76201**
76202** The TK_AS operator is inhibited if zType[0]=='G'.  This means
76203** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
76204**
76205**     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
76206**
76207** Is equivalent to:
76208**
76209**     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
76210**
76211** The result of random()%5 in the GROUP BY clause is probably different
76212** from the result in the result-set.  On the other hand Standard SQL does
76213** not allow the GROUP BY clause to contain references to result-set columns.
76214** So this should never come up in well-formed queries.
76215**
76216** If the reference is followed by a COLLATE operator, then make sure
76217** the COLLATE operator is preserved.  For example:
76218**
76219**     SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
76220**
76221** Should be transformed into:
76222**
76223**     SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
76224**
76225** The nSubquery parameter specifies how many levels of subquery the
76226** alias is removed from the original expression.  The usually value is
76227** zero but it might be more if the alias is contained within a subquery
76228** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION
76229** structures must be increased by the nSubquery amount.
76230*/
76231static void resolveAlias(
76232  Parse *pParse,         /* Parsing context */
76233  ExprList *pEList,      /* A result set */
76234  int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
76235  Expr *pExpr,           /* Transform this into an alias to the result set */
76236  const char *zType,     /* "GROUP" or "ORDER" or "" */
76237  int nSubquery          /* Number of subqueries that the label is moving */
76238){
76239  Expr *pOrig;           /* The iCol-th column of the result set */
76240  Expr *pDup;            /* Copy of pOrig */
76241  sqlite3 *db;           /* The database connection */
76242
76243  assert( iCol>=0 && iCol<pEList->nExpr );
76244  pOrig = pEList->a[iCol].pExpr;
76245  assert( pOrig!=0 );
76246  assert( pOrig->flags & EP_Resolved );
76247  db = pParse->db;
76248  pDup = sqlite3ExprDup(db, pOrig, 0);
76249  if( pDup==0 ) return;
76250  if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
76251    incrAggFunctionDepth(pDup, nSubquery);
76252    pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
76253    if( pDup==0 ) return;
76254    ExprSetProperty(pDup, EP_Skip);
76255    if( pEList->a[iCol].u.x.iAlias==0 ){
76256      pEList->a[iCol].u.x.iAlias = (u16)(++pParse->nAlias);
76257    }
76258    pDup->iTable = pEList->a[iCol].u.x.iAlias;
76259  }
76260  if( pExpr->op==TK_COLLATE ){
76261    pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
76262  }
76263
76264  /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
76265  ** prevents ExprDelete() from deleting the Expr structure itself,
76266  ** allowing it to be repopulated by the memcpy() on the following line.
76267  ** The pExpr->u.zToken might point into memory that will be freed by the
76268  ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
76269  ** make a copy of the token before doing the sqlite3DbFree().
76270  */
76271  ExprSetProperty(pExpr, EP_Static);
76272  sqlite3ExprDelete(db, pExpr);
76273  memcpy(pExpr, pDup, sizeof(*pExpr));
76274  if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
76275    assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
76276    pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
76277    pExpr->flags |= EP_MemToken;
76278  }
76279  sqlite3DbFree(db, pDup);
76280}
76281
76282
76283/*
76284** Return TRUE if the name zCol occurs anywhere in the USING clause.
76285**
76286** Return FALSE if the USING clause is NULL or if it does not contain
76287** zCol.
76288*/
76289static int nameInUsingClause(IdList *pUsing, const char *zCol){
76290  if( pUsing ){
76291    int k;
76292    for(k=0; k<pUsing->nId; k++){
76293      if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
76294    }
76295  }
76296  return 0;
76297}
76298
76299/*
76300** Subqueries stores the original database, table and column names for their
76301** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
76302** Check to see if the zSpan given to this routine matches the zDb, zTab,
76303** and zCol.  If any of zDb, zTab, and zCol are NULL then those fields will
76304** match anything.
76305*/
76306SQLITE_PRIVATE int sqlite3MatchSpanName(
76307  const char *zSpan,
76308  const char *zCol,
76309  const char *zTab,
76310  const char *zDb
76311){
76312  int n;
76313  for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
76314  if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
76315    return 0;
76316  }
76317  zSpan += n+1;
76318  for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
76319  if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
76320    return 0;
76321  }
76322  zSpan += n+1;
76323  if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
76324    return 0;
76325  }
76326  return 1;
76327}
76328
76329/*
76330** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
76331** that name in the set of source tables in pSrcList and make the pExpr
76332** expression node refer back to that source column.  The following changes
76333** are made to pExpr:
76334**
76335**    pExpr->iDb           Set the index in db->aDb[] of the database X
76336**                         (even if X is implied).
76337**    pExpr->iTable        Set to the cursor number for the table obtained
76338**                         from pSrcList.
76339**    pExpr->pTab          Points to the Table structure of X.Y (even if
76340**                         X and/or Y are implied.)
76341**    pExpr->iColumn       Set to the column number within the table.
76342**    pExpr->op            Set to TK_COLUMN.
76343**    pExpr->pLeft         Any expression this points to is deleted
76344**    pExpr->pRight        Any expression this points to is deleted.
76345**
76346** The zDb variable is the name of the database (the "X").  This value may be
76347** NULL meaning that name is of the form Y.Z or Z.  Any available database
76348** can be used.  The zTable variable is the name of the table (the "Y").  This
76349** value can be NULL if zDb is also NULL.  If zTable is NULL it
76350** means that the form of the name is Z and that columns from any table
76351** can be used.
76352**
76353** If the name cannot be resolved unambiguously, leave an error message
76354** in pParse and return WRC_Abort.  Return WRC_Prune on success.
76355*/
76356static int lookupName(
76357  Parse *pParse,       /* The parsing context */
76358  const char *zDb,     /* Name of the database containing table, or NULL */
76359  const char *zTab,    /* Name of table containing column, or NULL */
76360  const char *zCol,    /* Name of the column. */
76361  NameContext *pNC,    /* The name context used to resolve the name */
76362  Expr *pExpr          /* Make this EXPR node point to the selected column */
76363){
76364  int i, j;                         /* Loop counters */
76365  int cnt = 0;                      /* Number of matching column names */
76366  int cntTab = 0;                   /* Number of matching table names */
76367  int nSubquery = 0;                /* How many levels of subquery */
76368  sqlite3 *db = pParse->db;         /* The database connection */
76369  struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
76370  struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
76371  NameContext *pTopNC = pNC;        /* First namecontext in the list */
76372  Schema *pSchema = 0;              /* Schema of the expression */
76373  int isTrigger = 0;                /* True if resolved to a trigger column */
76374  Table *pTab = 0;                  /* Table hold the row */
76375  Column *pCol;                     /* A column of pTab */
76376
76377  assert( pNC );     /* the name context cannot be NULL. */
76378  assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
76379  assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
76380
76381  /* Initialize the node to no-match */
76382  pExpr->iTable = -1;
76383  pExpr->pTab = 0;
76384  ExprSetVVAProperty(pExpr, EP_NoReduce);
76385
76386  /* Translate the schema name in zDb into a pointer to the corresponding
76387  ** schema.  If not found, pSchema will remain NULL and nothing will match
76388  ** resulting in an appropriate error message toward the end of this routine
76389  */
76390  if( zDb ){
76391    testcase( pNC->ncFlags & NC_PartIdx );
76392    testcase( pNC->ncFlags & NC_IsCheck );
76393    if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
76394      /* Silently ignore database qualifiers inside CHECK constraints and partial
76395      ** indices.  Do not raise errors because that might break legacy and
76396      ** because it does not hurt anything to just ignore the database name. */
76397      zDb = 0;
76398    }else{
76399      for(i=0; i<db->nDb; i++){
76400        assert( db->aDb[i].zName );
76401        if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
76402          pSchema = db->aDb[i].pSchema;
76403          break;
76404        }
76405      }
76406    }
76407  }
76408
76409  /* Start at the inner-most context and move outward until a match is found */
76410  while( pNC && cnt==0 ){
76411    ExprList *pEList;
76412    SrcList *pSrcList = pNC->pSrcList;
76413
76414    if( pSrcList ){
76415      for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
76416        pTab = pItem->pTab;
76417        assert( pTab!=0 && pTab->zName!=0 );
76418        assert( pTab->nCol>0 );
76419        if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
76420          int hit = 0;
76421          pEList = pItem->pSelect->pEList;
76422          for(j=0; j<pEList->nExpr; j++){
76423            if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
76424              cnt++;
76425              cntTab = 2;
76426              pMatch = pItem;
76427              pExpr->iColumn = j;
76428              hit = 1;
76429            }
76430          }
76431          if( hit || zTab==0 ) continue;
76432        }
76433        if( zDb && pTab->pSchema!=pSchema ){
76434          continue;
76435        }
76436        if( zTab ){
76437          const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
76438          assert( zTabName!=0 );
76439          if( sqlite3StrICmp(zTabName, zTab)!=0 ){
76440            continue;
76441          }
76442        }
76443        if( 0==(cntTab++) ){
76444          pMatch = pItem;
76445        }
76446        for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
76447          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
76448            /* If there has been exactly one prior match and this match
76449            ** is for the right-hand table of a NATURAL JOIN or is in a
76450            ** USING clause, then skip this match.
76451            */
76452            if( cnt==1 ){
76453              if( pItem->jointype & JT_NATURAL ) continue;
76454              if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
76455            }
76456            cnt++;
76457            pMatch = pItem;
76458            /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
76459            pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
76460            break;
76461          }
76462        }
76463      }
76464      if( pMatch ){
76465        pExpr->iTable = pMatch->iCursor;
76466        pExpr->pTab = pMatch->pTab;
76467        pSchema = pExpr->pTab->pSchema;
76468      }
76469    } /* if( pSrcList ) */
76470
76471#ifndef SQLITE_OMIT_TRIGGER
76472    /* If we have not already resolved the name, then maybe
76473    ** it is a new.* or old.* trigger argument reference
76474    */
76475    if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
76476      int op = pParse->eTriggerOp;
76477      assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
76478      if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
76479        pExpr->iTable = 1;
76480        pTab = pParse->pTriggerTab;
76481      }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
76482        pExpr->iTable = 0;
76483        pTab = pParse->pTriggerTab;
76484      }else{
76485        pTab = 0;
76486      }
76487
76488      if( pTab ){
76489        int iCol;
76490        pSchema = pTab->pSchema;
76491        cntTab++;
76492        for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
76493          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
76494            if( iCol==pTab->iPKey ){
76495              iCol = -1;
76496            }
76497            break;
76498          }
76499        }
76500        if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && HasRowid(pTab) ){
76501          /* IMP: R-24309-18625 */
76502          /* IMP: R-44911-55124 */
76503          iCol = -1;
76504        }
76505        if( iCol<pTab->nCol ){
76506          cnt++;
76507          if( iCol<0 ){
76508            pExpr->affinity = SQLITE_AFF_INTEGER;
76509          }else if( pExpr->iTable==0 ){
76510            testcase( iCol==31 );
76511            testcase( iCol==32 );
76512            pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
76513          }else{
76514            testcase( iCol==31 );
76515            testcase( iCol==32 );
76516            pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
76517          }
76518          pExpr->iColumn = (i16)iCol;
76519          pExpr->pTab = pTab;
76520          isTrigger = 1;
76521        }
76522      }
76523    }
76524#endif /* !defined(SQLITE_OMIT_TRIGGER) */
76525
76526    /*
76527    ** Perhaps the name is a reference to the ROWID
76528    */
76529    if( cnt==0 && cntTab==1 && pMatch && sqlite3IsRowid(zCol)
76530     && HasRowid(pMatch->pTab) ){
76531      cnt = 1;
76532      pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
76533      pExpr->affinity = SQLITE_AFF_INTEGER;
76534    }
76535
76536    /*
76537    ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
76538    ** might refer to an result-set alias.  This happens, for example, when
76539    ** we are resolving names in the WHERE clause of the following command:
76540    **
76541    **     SELECT a+b AS x FROM table WHERE x<10;
76542    **
76543    ** In cases like this, replace pExpr with a copy of the expression that
76544    ** forms the result set entry ("a+b" in the example) and return immediately.
76545    ** Note that the expression in the result set should have already been
76546    ** resolved by the time the WHERE clause is resolved.
76547    **
76548    ** The ability to use an output result-set column in the WHERE, GROUP BY,
76549    ** or HAVING clauses, or as part of a larger expression in the ORDRE BY
76550    ** clause is not standard SQL.  This is a (goofy) SQLite extension, that
76551    ** is supported for backwards compatibility only.  TO DO: Issue a warning
76552    ** on sqlite3_log() whenever the capability is used.
76553    */
76554    if( (pEList = pNC->pEList)!=0
76555     && zTab==0
76556     && cnt==0
76557    ){
76558      for(j=0; j<pEList->nExpr; j++){
76559        char *zAs = pEList->a[j].zName;
76560        if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
76561          Expr *pOrig;
76562          assert( pExpr->pLeft==0 && pExpr->pRight==0 );
76563          assert( pExpr->x.pList==0 );
76564          assert( pExpr->x.pSelect==0 );
76565          pOrig = pEList->a[j].pExpr;
76566          if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
76567            sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
76568            return WRC_Abort;
76569          }
76570          resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
76571          cnt = 1;
76572          pMatch = 0;
76573          assert( zTab==0 && zDb==0 );
76574          goto lookupname_end;
76575        }
76576      }
76577    }
76578
76579    /* Advance to the next name context.  The loop will exit when either
76580    ** we have a match (cnt>0) or when we run out of name contexts.
76581    */
76582    if( cnt==0 ){
76583      pNC = pNC->pNext;
76584      nSubquery++;
76585    }
76586  }
76587
76588  /*
76589  ** If X and Y are NULL (in other words if only the column name Z is
76590  ** supplied) and the value of Z is enclosed in double-quotes, then
76591  ** Z is a string literal if it doesn't match any column names.  In that
76592  ** case, we need to return right away and not make any changes to
76593  ** pExpr.
76594  **
76595  ** Because no reference was made to outer contexts, the pNC->nRef
76596  ** fields are not changed in any context.
76597  */
76598  if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
76599    pExpr->op = TK_STRING;
76600    pExpr->pTab = 0;
76601    return WRC_Prune;
76602  }
76603
76604  /*
76605  ** cnt==0 means there was not match.  cnt>1 means there were two or
76606  ** more matches.  Either way, we have an error.
76607  */
76608  if( cnt!=1 ){
76609    const char *zErr;
76610    zErr = cnt==0 ? "no such column" : "ambiguous column name";
76611    if( zDb ){
76612      sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
76613    }else if( zTab ){
76614      sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
76615    }else{
76616      sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
76617    }
76618    pParse->checkSchema = 1;
76619    pTopNC->nErr++;
76620  }
76621
76622  /* If a column from a table in pSrcList is referenced, then record
76623  ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
76624  ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
76625  ** column number is greater than the number of bits in the bitmask
76626  ** then set the high-order bit of the bitmask.
76627  */
76628  if( pExpr->iColumn>=0 && pMatch!=0 ){
76629    int n = pExpr->iColumn;
76630    testcase( n==BMS-1 );
76631    if( n>=BMS ){
76632      n = BMS-1;
76633    }
76634    assert( pMatch->iCursor==pExpr->iTable );
76635    pMatch->colUsed |= ((Bitmask)1)<<n;
76636  }
76637
76638  /* Clean up and return
76639  */
76640  sqlite3ExprDelete(db, pExpr->pLeft);
76641  pExpr->pLeft = 0;
76642  sqlite3ExprDelete(db, pExpr->pRight);
76643  pExpr->pRight = 0;
76644  pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
76645lookupname_end:
76646  if( cnt==1 ){
76647    assert( pNC!=0 );
76648    if( pExpr->op!=TK_AS ){
76649      sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
76650    }
76651    /* Increment the nRef value on all name contexts from TopNC up to
76652    ** the point where the name matched. */
76653    for(;;){
76654      assert( pTopNC!=0 );
76655      pTopNC->nRef++;
76656      if( pTopNC==pNC ) break;
76657      pTopNC = pTopNC->pNext;
76658    }
76659    return WRC_Prune;
76660  } else {
76661    return WRC_Abort;
76662  }
76663}
76664
76665/*
76666** Allocate and return a pointer to an expression to load the column iCol
76667** from datasource iSrc in SrcList pSrc.
76668*/
76669SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
76670  Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
76671  if( p ){
76672    struct SrcList_item *pItem = &pSrc->a[iSrc];
76673    p->pTab = pItem->pTab;
76674    p->iTable = pItem->iCursor;
76675    if( p->pTab->iPKey==iCol ){
76676      p->iColumn = -1;
76677    }else{
76678      p->iColumn = (ynVar)iCol;
76679      testcase( iCol==BMS );
76680      testcase( iCol==BMS-1 );
76681      pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
76682    }
76683    ExprSetProperty(p, EP_Resolved);
76684  }
76685  return p;
76686}
76687
76688/*
76689** Report an error that an expression is not valid for a partial index WHERE
76690** clause.
76691*/
76692static void notValidPartIdxWhere(
76693  Parse *pParse,       /* Leave error message here */
76694  NameContext *pNC,    /* The name context */
76695  const char *zMsg     /* Type of error */
76696){
76697  if( (pNC->ncFlags & NC_PartIdx)!=0 ){
76698    sqlite3ErrorMsg(pParse, "%s prohibited in partial index WHERE clauses",
76699                    zMsg);
76700  }
76701}
76702
76703#ifndef SQLITE_OMIT_CHECK
76704/*
76705** Report an error that an expression is not valid for a CHECK constraint.
76706*/
76707static void notValidCheckConstraint(
76708  Parse *pParse,       /* Leave error message here */
76709  NameContext *pNC,    /* The name context */
76710  const char *zMsg     /* Type of error */
76711){
76712  if( (pNC->ncFlags & NC_IsCheck)!=0 ){
76713    sqlite3ErrorMsg(pParse,"%s prohibited in CHECK constraints", zMsg);
76714  }
76715}
76716#else
76717# define notValidCheckConstraint(P,N,M)
76718#endif
76719
76720/*
76721** Expression p should encode a floating point value between 1.0 and 0.0.
76722** Return 1024 times this value.  Or return -1 if p is not a floating point
76723** value between 1.0 and 0.0.
76724*/
76725static int exprProbability(Expr *p){
76726  double r = -1.0;
76727  if( p->op!=TK_FLOAT ) return -1;
76728  sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
76729  assert( r>=0.0 );
76730  if( r>1.0 ) return -1;
76731  return (int)(r*1000.0);
76732}
76733
76734/*
76735** This routine is callback for sqlite3WalkExpr().
76736**
76737** Resolve symbolic names into TK_COLUMN operators for the current
76738** node in the expression tree.  Return 0 to continue the search down
76739** the tree or 2 to abort the tree walk.
76740**
76741** This routine also does error checking and name resolution for
76742** function names.  The operator for aggregate functions is changed
76743** to TK_AGG_FUNCTION.
76744*/
76745static int resolveExprStep(Walker *pWalker, Expr *pExpr){
76746  NameContext *pNC;
76747  Parse *pParse;
76748
76749  pNC = pWalker->u.pNC;
76750  assert( pNC!=0 );
76751  pParse = pNC->pParse;
76752  assert( pParse==pWalker->pParse );
76753
76754  if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
76755  ExprSetProperty(pExpr, EP_Resolved);
76756#ifndef NDEBUG
76757  if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
76758    SrcList *pSrcList = pNC->pSrcList;
76759    int i;
76760    for(i=0; i<pNC->pSrcList->nSrc; i++){
76761      assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
76762    }
76763  }
76764#endif
76765  switch( pExpr->op ){
76766
76767#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
76768    /* The special operator TK_ROW means use the rowid for the first
76769    ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
76770    ** clause processing on UPDATE and DELETE statements.
76771    */
76772    case TK_ROW: {
76773      SrcList *pSrcList = pNC->pSrcList;
76774      struct SrcList_item *pItem;
76775      assert( pSrcList && pSrcList->nSrc==1 );
76776      pItem = pSrcList->a;
76777      pExpr->op = TK_COLUMN;
76778      pExpr->pTab = pItem->pTab;
76779      pExpr->iTable = pItem->iCursor;
76780      pExpr->iColumn = -1;
76781      pExpr->affinity = SQLITE_AFF_INTEGER;
76782      break;
76783    }
76784#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
76785
76786    /* A lone identifier is the name of a column.
76787    */
76788    case TK_ID: {
76789      return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
76790    }
76791
76792    /* A table name and column name:     ID.ID
76793    ** Or a database, table and column:  ID.ID.ID
76794    */
76795    case TK_DOT: {
76796      const char *zColumn;
76797      const char *zTable;
76798      const char *zDb;
76799      Expr *pRight;
76800
76801      /* if( pSrcList==0 ) break; */
76802      pRight = pExpr->pRight;
76803      if( pRight->op==TK_ID ){
76804        zDb = 0;
76805        zTable = pExpr->pLeft->u.zToken;
76806        zColumn = pRight->u.zToken;
76807      }else{
76808        assert( pRight->op==TK_DOT );
76809        zDb = pExpr->pLeft->u.zToken;
76810        zTable = pRight->pLeft->u.zToken;
76811        zColumn = pRight->pRight->u.zToken;
76812      }
76813      return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
76814    }
76815
76816    /* Resolve function names
76817    */
76818    case TK_FUNCTION: {
76819      ExprList *pList = pExpr->x.pList;    /* The argument list */
76820      int n = pList ? pList->nExpr : 0;    /* Number of arguments */
76821      int no_such_func = 0;       /* True if no such function exists */
76822      int wrong_num_args = 0;     /* True if wrong number of arguments */
76823      int is_agg = 0;             /* True if is an aggregate function */
76824      int auth;                   /* Authorization to use the function */
76825      int nId;                    /* Number of characters in function name */
76826      const char *zId;            /* The function name. */
76827      FuncDef *pDef;              /* Information about the function */
76828      u8 enc = ENC(pParse->db);   /* The database encoding */
76829
76830      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
76831      notValidPartIdxWhere(pParse, pNC, "functions");
76832      zId = pExpr->u.zToken;
76833      nId = sqlite3Strlen30(zId);
76834      pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
76835      if( pDef==0 ){
76836        pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
76837        if( pDef==0 ){
76838          no_such_func = 1;
76839        }else{
76840          wrong_num_args = 1;
76841        }
76842      }else{
76843        is_agg = pDef->xFunc==0;
76844        if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
76845          ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
76846          if( n==2 ){
76847            pExpr->iTable = exprProbability(pList->a[1].pExpr);
76848            if( pExpr->iTable<0 ){
76849              sqlite3ErrorMsg(pParse, "second argument to likelihood() must be a "
76850                                      "constant between 0.0 and 1.0");
76851              pNC->nErr++;
76852            }
76853          }else{
76854            /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is equivalent to
76855            ** likelihood(X, 0.0625).
76856            ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is short-hand for
76857            ** likelihood(X,0.0625). */
76858            pExpr->iTable = 62;  /* TUNING:  Default 2nd arg to unlikely() is 0.0625 */
76859          }
76860        }
76861      }
76862#ifndef SQLITE_OMIT_AUTHORIZATION
76863      if( pDef ){
76864        auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
76865        if( auth!=SQLITE_OK ){
76866          if( auth==SQLITE_DENY ){
76867            sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
76868                                    pDef->zName);
76869            pNC->nErr++;
76870          }
76871          pExpr->op = TK_NULL;
76872          return WRC_Prune;
76873        }
76874        if( pDef->funcFlags & SQLITE_FUNC_CONSTANT ) ExprSetProperty(pExpr,EP_Constant);
76875      }
76876#endif
76877      if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
76878        sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
76879        pNC->nErr++;
76880        is_agg = 0;
76881      }else if( no_such_func && pParse->db->init.busy==0 ){
76882        sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
76883        pNC->nErr++;
76884      }else if( wrong_num_args ){
76885        sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
76886             nId, zId);
76887        pNC->nErr++;
76888      }
76889      if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
76890      sqlite3WalkExprList(pWalker, pList);
76891      if( is_agg ){
76892        NameContext *pNC2 = pNC;
76893        pExpr->op = TK_AGG_FUNCTION;
76894        pExpr->op2 = 0;
76895        while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
76896          pExpr->op2++;
76897          pNC2 = pNC2->pNext;
76898        }
76899        if( pNC2 ) pNC2->ncFlags |= NC_HasAgg;
76900        pNC->ncFlags |= NC_AllowAgg;
76901      }
76902      /* FIX ME:  Compute pExpr->affinity based on the expected return
76903      ** type of the function
76904      */
76905      return WRC_Prune;
76906    }
76907#ifndef SQLITE_OMIT_SUBQUERY
76908    case TK_SELECT:
76909    case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
76910#endif
76911    case TK_IN: {
76912      testcase( pExpr->op==TK_IN );
76913      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
76914        int nRef = pNC->nRef;
76915        notValidCheckConstraint(pParse, pNC, "subqueries");
76916        notValidPartIdxWhere(pParse, pNC, "subqueries");
76917        sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
76918        assert( pNC->nRef>=nRef );
76919        if( nRef!=pNC->nRef ){
76920          ExprSetProperty(pExpr, EP_VarSelect);
76921        }
76922      }
76923      break;
76924    }
76925    case TK_VARIABLE: {
76926      notValidCheckConstraint(pParse, pNC, "parameters");
76927      notValidPartIdxWhere(pParse, pNC, "parameters");
76928      break;
76929    }
76930  }
76931  return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
76932}
76933
76934/*
76935** pEList is a list of expressions which are really the result set of the
76936** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
76937** This routine checks to see if pE is a simple identifier which corresponds
76938** to the AS-name of one of the terms of the expression list.  If it is,
76939** this routine return an integer between 1 and N where N is the number of
76940** elements in pEList, corresponding to the matching entry.  If there is
76941** no match, or if pE is not a simple identifier, then this routine
76942** return 0.
76943**
76944** pEList has been resolved.  pE has not.
76945*/
76946static int resolveAsName(
76947  Parse *pParse,     /* Parsing context for error messages */
76948  ExprList *pEList,  /* List of expressions to scan */
76949  Expr *pE           /* Expression we are trying to match */
76950){
76951  int i;             /* Loop counter */
76952
76953  UNUSED_PARAMETER(pParse);
76954
76955  if( pE->op==TK_ID ){
76956    char *zCol = pE->u.zToken;
76957    for(i=0; i<pEList->nExpr; i++){
76958      char *zAs = pEList->a[i].zName;
76959      if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
76960        return i+1;
76961      }
76962    }
76963  }
76964  return 0;
76965}
76966
76967/*
76968** pE is a pointer to an expression which is a single term in the
76969** ORDER BY of a compound SELECT.  The expression has not been
76970** name resolved.
76971**
76972** At the point this routine is called, we already know that the
76973** ORDER BY term is not an integer index into the result set.  That
76974** case is handled by the calling routine.
76975**
76976** Attempt to match pE against result set columns in the left-most
76977** SELECT statement.  Return the index i of the matching column,
76978** as an indication to the caller that it should sort by the i-th column.
76979** The left-most column is 1.  In other words, the value returned is the
76980** same integer value that would be used in the SQL statement to indicate
76981** the column.
76982**
76983** If there is no match, return 0.  Return -1 if an error occurs.
76984*/
76985static int resolveOrderByTermToExprList(
76986  Parse *pParse,     /* Parsing context for error messages */
76987  Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
76988  Expr *pE           /* The specific ORDER BY term */
76989){
76990  int i;             /* Loop counter */
76991  ExprList *pEList;  /* The columns of the result set */
76992  NameContext nc;    /* Name context for resolving pE */
76993  sqlite3 *db;       /* Database connection */
76994  int rc;            /* Return code from subprocedures */
76995  u8 savedSuppErr;   /* Saved value of db->suppressErr */
76996
76997  assert( sqlite3ExprIsInteger(pE, &i)==0 );
76998  pEList = pSelect->pEList;
76999
77000  /* Resolve all names in the ORDER BY term expression
77001  */
77002  memset(&nc, 0, sizeof(nc));
77003  nc.pParse = pParse;
77004  nc.pSrcList = pSelect->pSrc;
77005  nc.pEList = pEList;
77006  nc.ncFlags = NC_AllowAgg;
77007  nc.nErr = 0;
77008  db = pParse->db;
77009  savedSuppErr = db->suppressErr;
77010  db->suppressErr = 1;
77011  rc = sqlite3ResolveExprNames(&nc, pE);
77012  db->suppressErr = savedSuppErr;
77013  if( rc ) return 0;
77014
77015  /* Try to match the ORDER BY expression against an expression
77016  ** in the result set.  Return an 1-based index of the matching
77017  ** result-set entry.
77018  */
77019  for(i=0; i<pEList->nExpr; i++){
77020    if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
77021      return i+1;
77022    }
77023  }
77024
77025  /* If no match, return 0. */
77026  return 0;
77027}
77028
77029/*
77030** Generate an ORDER BY or GROUP BY term out-of-range error.
77031*/
77032static void resolveOutOfRangeError(
77033  Parse *pParse,         /* The error context into which to write the error */
77034  const char *zType,     /* "ORDER" or "GROUP" */
77035  int i,                 /* The index (1-based) of the term out of range */
77036  int mx                 /* Largest permissible value of i */
77037){
77038  sqlite3ErrorMsg(pParse,
77039    "%r %s BY term out of range - should be "
77040    "between 1 and %d", i, zType, mx);
77041}
77042
77043/*
77044** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
77045** each term of the ORDER BY clause is a constant integer between 1
77046** and N where N is the number of columns in the compound SELECT.
77047**
77048** ORDER BY terms that are already an integer between 1 and N are
77049** unmodified.  ORDER BY terms that are integers outside the range of
77050** 1 through N generate an error.  ORDER BY terms that are expressions
77051** are matched against result set expressions of compound SELECT
77052** beginning with the left-most SELECT and working toward the right.
77053** At the first match, the ORDER BY expression is transformed into
77054** the integer column number.
77055**
77056** Return the number of errors seen.
77057*/
77058static int resolveCompoundOrderBy(
77059  Parse *pParse,        /* Parsing context.  Leave error messages here */
77060  Select *pSelect       /* The SELECT statement containing the ORDER BY */
77061){
77062  int i;
77063  ExprList *pOrderBy;
77064  ExprList *pEList;
77065  sqlite3 *db;
77066  int moreToDo = 1;
77067
77068  pOrderBy = pSelect->pOrderBy;
77069  if( pOrderBy==0 ) return 0;
77070  db = pParse->db;
77071#if SQLITE_MAX_COLUMN
77072  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
77073    sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
77074    return 1;
77075  }
77076#endif
77077  for(i=0; i<pOrderBy->nExpr; i++){
77078    pOrderBy->a[i].done = 0;
77079  }
77080  pSelect->pNext = 0;
77081  while( pSelect->pPrior ){
77082    pSelect->pPrior->pNext = pSelect;
77083    pSelect = pSelect->pPrior;
77084  }
77085  while( pSelect && moreToDo ){
77086    struct ExprList_item *pItem;
77087    moreToDo = 0;
77088    pEList = pSelect->pEList;
77089    assert( pEList!=0 );
77090    for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
77091      int iCol = -1;
77092      Expr *pE, *pDup;
77093      if( pItem->done ) continue;
77094      pE = sqlite3ExprSkipCollate(pItem->pExpr);
77095      if( sqlite3ExprIsInteger(pE, &iCol) ){
77096        if( iCol<=0 || iCol>pEList->nExpr ){
77097          resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
77098          return 1;
77099        }
77100      }else{
77101        iCol = resolveAsName(pParse, pEList, pE);
77102        if( iCol==0 ){
77103          pDup = sqlite3ExprDup(db, pE, 0);
77104          if( !db->mallocFailed ){
77105            assert(pDup);
77106            iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
77107          }
77108          sqlite3ExprDelete(db, pDup);
77109        }
77110      }
77111      if( iCol>0 ){
77112        /* Convert the ORDER BY term into an integer column number iCol,
77113        ** taking care to preserve the COLLATE clause if it exists */
77114        Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
77115        if( pNew==0 ) return 1;
77116        pNew->flags |= EP_IntValue;
77117        pNew->u.iValue = iCol;
77118        if( pItem->pExpr==pE ){
77119          pItem->pExpr = pNew;
77120        }else{
77121          assert( pItem->pExpr->op==TK_COLLATE );
77122          assert( pItem->pExpr->pLeft==pE );
77123          pItem->pExpr->pLeft = pNew;
77124        }
77125        sqlite3ExprDelete(db, pE);
77126        pItem->u.x.iOrderByCol = (u16)iCol;
77127        pItem->done = 1;
77128      }else{
77129        moreToDo = 1;
77130      }
77131    }
77132    pSelect = pSelect->pNext;
77133  }
77134  for(i=0; i<pOrderBy->nExpr; i++){
77135    if( pOrderBy->a[i].done==0 ){
77136      sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
77137            "column in the result set", i+1);
77138      return 1;
77139    }
77140  }
77141  return 0;
77142}
77143
77144/*
77145** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
77146** the SELECT statement pSelect.  If any term is reference to a
77147** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
77148** field) then convert that term into a copy of the corresponding result set
77149** column.
77150**
77151** If any errors are detected, add an error message to pParse and
77152** return non-zero.  Return zero if no errors are seen.
77153*/
77154SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
77155  Parse *pParse,        /* Parsing context.  Leave error messages here */
77156  Select *pSelect,      /* The SELECT statement containing the clause */
77157  ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
77158  const char *zType     /* "ORDER" or "GROUP" */
77159){
77160  int i;
77161  sqlite3 *db = pParse->db;
77162  ExprList *pEList;
77163  struct ExprList_item *pItem;
77164
77165  if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
77166#if SQLITE_MAX_COLUMN
77167  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
77168    sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
77169    return 1;
77170  }
77171#endif
77172  pEList = pSelect->pEList;
77173  assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
77174  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
77175    if( pItem->u.x.iOrderByCol ){
77176      if( pItem->u.x.iOrderByCol>pEList->nExpr ){
77177        resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
77178        return 1;
77179      }
77180      resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr, zType,0);
77181    }
77182  }
77183  return 0;
77184}
77185
77186/*
77187** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
77188** The Name context of the SELECT statement is pNC.  zType is either
77189** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
77190**
77191** This routine resolves each term of the clause into an expression.
77192** If the order-by term is an integer I between 1 and N (where N is the
77193** number of columns in the result set of the SELECT) then the expression
77194** in the resolution is a copy of the I-th result-set expression.  If
77195** the order-by term is an identifier that corresponds to the AS-name of
77196** a result-set expression, then the term resolves to a copy of the
77197** result-set expression.  Otherwise, the expression is resolved in
77198** the usual way - using sqlite3ResolveExprNames().
77199**
77200** This routine returns the number of errors.  If errors occur, then
77201** an appropriate error message might be left in pParse.  (OOM errors
77202** excepted.)
77203*/
77204static int resolveOrderGroupBy(
77205  NameContext *pNC,     /* The name context of the SELECT statement */
77206  Select *pSelect,      /* The SELECT statement holding pOrderBy */
77207  ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
77208  const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
77209){
77210  int i, j;                      /* Loop counters */
77211  int iCol;                      /* Column number */
77212  struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
77213  Parse *pParse;                 /* Parsing context */
77214  int nResult;                   /* Number of terms in the result set */
77215
77216  if( pOrderBy==0 ) return 0;
77217  nResult = pSelect->pEList->nExpr;
77218  pParse = pNC->pParse;
77219  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
77220    Expr *pE = pItem->pExpr;
77221    Expr *pE2 = sqlite3ExprSkipCollate(pE);
77222    if( zType[0]!='G' ){
77223      iCol = resolveAsName(pParse, pSelect->pEList, pE2);
77224      if( iCol>0 ){
77225        /* If an AS-name match is found, mark this ORDER BY column as being
77226        ** a copy of the iCol-th result-set column.  The subsequent call to
77227        ** sqlite3ResolveOrderGroupBy() will convert the expression to a
77228        ** copy of the iCol-th result-set expression. */
77229        pItem->u.x.iOrderByCol = (u16)iCol;
77230        continue;
77231      }
77232    }
77233    if( sqlite3ExprIsInteger(pE2, &iCol) ){
77234      /* The ORDER BY term is an integer constant.  Again, set the column
77235      ** number so that sqlite3ResolveOrderGroupBy() will convert the
77236      ** order-by term to a copy of the result-set expression */
77237      if( iCol<1 || iCol>0xffff ){
77238        resolveOutOfRangeError(pParse, zType, i+1, nResult);
77239        return 1;
77240      }
77241      pItem->u.x.iOrderByCol = (u16)iCol;
77242      continue;
77243    }
77244
77245    /* Otherwise, treat the ORDER BY term as an ordinary expression */
77246    pItem->u.x.iOrderByCol = 0;
77247    if( sqlite3ResolveExprNames(pNC, pE) ){
77248      return 1;
77249    }
77250    for(j=0; j<pSelect->pEList->nExpr; j++){
77251      if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
77252        pItem->u.x.iOrderByCol = j+1;
77253      }
77254    }
77255  }
77256  return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
77257}
77258
77259/*
77260** Resolve names in the SELECT statement p and all of its descendents.
77261*/
77262static int resolveSelectStep(Walker *pWalker, Select *p){
77263  NameContext *pOuterNC;  /* Context that contains this SELECT */
77264  NameContext sNC;        /* Name context of this SELECT */
77265  int isCompound;         /* True if p is a compound select */
77266  int nCompound;          /* Number of compound terms processed so far */
77267  Parse *pParse;          /* Parsing context */
77268  ExprList *pEList;       /* Result set expression list */
77269  int i;                  /* Loop counter */
77270  ExprList *pGroupBy;     /* The GROUP BY clause */
77271  Select *pLeftmost;      /* Left-most of SELECT of a compound */
77272  sqlite3 *db;            /* Database connection */
77273
77274
77275  assert( p!=0 );
77276  if( p->selFlags & SF_Resolved ){
77277    return WRC_Prune;
77278  }
77279  pOuterNC = pWalker->u.pNC;
77280  pParse = pWalker->pParse;
77281  db = pParse->db;
77282
77283  /* Normally sqlite3SelectExpand() will be called first and will have
77284  ** already expanded this SELECT.  However, if this is a subquery within
77285  ** an expression, sqlite3ResolveExprNames() will be called without a
77286  ** prior call to sqlite3SelectExpand().  When that happens, let
77287  ** sqlite3SelectPrep() do all of the processing for this SELECT.
77288  ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
77289  ** this routine in the correct order.
77290  */
77291  if( (p->selFlags & SF_Expanded)==0 ){
77292    sqlite3SelectPrep(pParse, p, pOuterNC);
77293    return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
77294  }
77295
77296  isCompound = p->pPrior!=0;
77297  nCompound = 0;
77298  pLeftmost = p;
77299  while( p ){
77300    assert( (p->selFlags & SF_Expanded)!=0 );
77301    assert( (p->selFlags & SF_Resolved)==0 );
77302    p->selFlags |= SF_Resolved;
77303
77304    /* Resolve the expressions in the LIMIT and OFFSET clauses. These
77305    ** are not allowed to refer to any names, so pass an empty NameContext.
77306    */
77307    memset(&sNC, 0, sizeof(sNC));
77308    sNC.pParse = pParse;
77309    if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
77310        sqlite3ResolveExprNames(&sNC, p->pOffset) ){
77311      return WRC_Abort;
77312    }
77313
77314    /* Recursively resolve names in all subqueries
77315    */
77316    for(i=0; i<p->pSrc->nSrc; i++){
77317      struct SrcList_item *pItem = &p->pSrc->a[i];
77318      if( pItem->pSelect ){
77319        NameContext *pNC;         /* Used to iterate name contexts */
77320        int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
77321        const char *zSavedContext = pParse->zAuthContext;
77322
77323        /* Count the total number of references to pOuterNC and all of its
77324        ** parent contexts. After resolving references to expressions in
77325        ** pItem->pSelect, check if this value has changed. If so, then
77326        ** SELECT statement pItem->pSelect must be correlated. Set the
77327        ** pItem->isCorrelated flag if this is the case. */
77328        for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
77329
77330        if( pItem->zName ) pParse->zAuthContext = pItem->zName;
77331        sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
77332        pParse->zAuthContext = zSavedContext;
77333        if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
77334
77335        for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
77336        assert( pItem->isCorrelated==0 && nRef<=0 );
77337        pItem->isCorrelated = (nRef!=0);
77338      }
77339    }
77340
77341    /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
77342    ** resolve the result-set expression list.
77343    */
77344    sNC.ncFlags = NC_AllowAgg;
77345    sNC.pSrcList = p->pSrc;
77346    sNC.pNext = pOuterNC;
77347
77348    /* Resolve names in the result set. */
77349    pEList = p->pEList;
77350    assert( pEList!=0 );
77351    for(i=0; i<pEList->nExpr; i++){
77352      Expr *pX = pEList->a[i].pExpr;
77353      if( sqlite3ResolveExprNames(&sNC, pX) ){
77354        return WRC_Abort;
77355      }
77356    }
77357
77358    /* If there are no aggregate functions in the result-set, and no GROUP BY
77359    ** expression, do not allow aggregates in any of the other expressions.
77360    */
77361    assert( (p->selFlags & SF_Aggregate)==0 );
77362    pGroupBy = p->pGroupBy;
77363    if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
77364      p->selFlags |= SF_Aggregate;
77365    }else{
77366      sNC.ncFlags &= ~NC_AllowAgg;
77367    }
77368
77369    /* If a HAVING clause is present, then there must be a GROUP BY clause.
77370    */
77371    if( p->pHaving && !pGroupBy ){
77372      sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
77373      return WRC_Abort;
77374    }
77375
77376    /* Add the output column list to the name-context before parsing the
77377    ** other expressions in the SELECT statement. This is so that
77378    ** expressions in the WHERE clause (etc.) can refer to expressions by
77379    ** aliases in the result set.
77380    **
77381    ** Minor point: If this is the case, then the expression will be
77382    ** re-evaluated for each reference to it.
77383    */
77384    sNC.pEList = p->pEList;
77385    if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
77386    if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
77387
77388    /* The ORDER BY and GROUP BY clauses may not refer to terms in
77389    ** outer queries
77390    */
77391    sNC.pNext = 0;
77392    sNC.ncFlags |= NC_AllowAgg;
77393
77394    /* Process the ORDER BY clause for singleton SELECT statements.
77395    ** The ORDER BY clause for compounds SELECT statements is handled
77396    ** below, after all of the result-sets for all of the elements of
77397    ** the compound have been resolved.
77398    */
77399    if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
77400      return WRC_Abort;
77401    }
77402    if( db->mallocFailed ){
77403      return WRC_Abort;
77404    }
77405
77406    /* Resolve the GROUP BY clause.  At the same time, make sure
77407    ** the GROUP BY clause does not contain aggregate functions.
77408    */
77409    if( pGroupBy ){
77410      struct ExprList_item *pItem;
77411
77412      if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
77413        return WRC_Abort;
77414      }
77415      for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
77416        if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
77417          sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
77418              "the GROUP BY clause");
77419          return WRC_Abort;
77420        }
77421      }
77422    }
77423
77424    /* Advance to the next term of the compound
77425    */
77426    p = p->pPrior;
77427    nCompound++;
77428  }
77429
77430  /* Resolve the ORDER BY on a compound SELECT after all terms of
77431  ** the compound have been resolved.
77432  */
77433  if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
77434    return WRC_Abort;
77435  }
77436
77437  return WRC_Prune;
77438}
77439
77440/*
77441** This routine walks an expression tree and resolves references to
77442** table columns and result-set columns.  At the same time, do error
77443** checking on function usage and set a flag if any aggregate functions
77444** are seen.
77445**
77446** To resolve table columns references we look for nodes (or subtrees) of the
77447** form X.Y.Z or Y.Z or just Z where
77448**
77449**      X:   The name of a database.  Ex:  "main" or "temp" or
77450**           the symbolic name assigned to an ATTACH-ed database.
77451**
77452**      Y:   The name of a table in a FROM clause.  Or in a trigger
77453**           one of the special names "old" or "new".
77454**
77455**      Z:   The name of a column in table Y.
77456**
77457** The node at the root of the subtree is modified as follows:
77458**
77459**    Expr.op        Changed to TK_COLUMN
77460**    Expr.pTab      Points to the Table object for X.Y
77461**    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
77462**    Expr.iTable    The VDBE cursor number for X.Y
77463**
77464**
77465** To resolve result-set references, look for expression nodes of the
77466** form Z (with no X and Y prefix) where the Z matches the right-hand
77467** size of an AS clause in the result-set of a SELECT.  The Z expression
77468** is replaced by a copy of the left-hand side of the result-set expression.
77469** Table-name and function resolution occurs on the substituted expression
77470** tree.  For example, in:
77471**
77472**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
77473**
77474** The "x" term of the order by is replaced by "a+b" to render:
77475**
77476**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
77477**
77478** Function calls are checked to make sure that the function is
77479** defined and that the correct number of arguments are specified.
77480** If the function is an aggregate function, then the NC_HasAgg flag is
77481** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
77482** If an expression contains aggregate functions then the EP_Agg
77483** property on the expression is set.
77484**
77485** An error message is left in pParse if anything is amiss.  The number
77486** if errors is returned.
77487*/
77488SQLITE_PRIVATE int sqlite3ResolveExprNames(
77489  NameContext *pNC,       /* Namespace to resolve expressions in. */
77490  Expr *pExpr             /* The expression to be analyzed. */
77491){
77492  u8 savedHasAgg;
77493  Walker w;
77494
77495  if( pExpr==0 ) return 0;
77496#if SQLITE_MAX_EXPR_DEPTH>0
77497  {
77498    Parse *pParse = pNC->pParse;
77499    if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
77500      return 1;
77501    }
77502    pParse->nHeight += pExpr->nHeight;
77503  }
77504#endif
77505  savedHasAgg = pNC->ncFlags & NC_HasAgg;
77506  pNC->ncFlags &= ~NC_HasAgg;
77507  memset(&w, 0, sizeof(w));
77508  w.xExprCallback = resolveExprStep;
77509  w.xSelectCallback = resolveSelectStep;
77510  w.pParse = pNC->pParse;
77511  w.u.pNC = pNC;
77512  sqlite3WalkExpr(&w, pExpr);
77513#if SQLITE_MAX_EXPR_DEPTH>0
77514  pNC->pParse->nHeight -= pExpr->nHeight;
77515#endif
77516  if( pNC->nErr>0 || w.pParse->nErr>0 ){
77517    ExprSetProperty(pExpr, EP_Error);
77518  }
77519  if( pNC->ncFlags & NC_HasAgg ){
77520    ExprSetProperty(pExpr, EP_Agg);
77521  }else if( savedHasAgg ){
77522    pNC->ncFlags |= NC_HasAgg;
77523  }
77524  return ExprHasProperty(pExpr, EP_Error);
77525}
77526
77527
77528/*
77529** Resolve all names in all expressions of a SELECT and in all
77530** decendents of the SELECT, including compounds off of p->pPrior,
77531** subqueries in expressions, and subqueries used as FROM clause
77532** terms.
77533**
77534** See sqlite3ResolveExprNames() for a description of the kinds of
77535** transformations that occur.
77536**
77537** All SELECT statements should have been expanded using
77538** sqlite3SelectExpand() prior to invoking this routine.
77539*/
77540SQLITE_PRIVATE void sqlite3ResolveSelectNames(
77541  Parse *pParse,         /* The parser context */
77542  Select *p,             /* The SELECT statement being coded. */
77543  NameContext *pOuterNC  /* Name context for parent SELECT statement */
77544){
77545  Walker w;
77546
77547  assert( p!=0 );
77548  memset(&w, 0, sizeof(w));
77549  w.xExprCallback = resolveExprStep;
77550  w.xSelectCallback = resolveSelectStep;
77551  w.pParse = pParse;
77552  w.u.pNC = pOuterNC;
77553  sqlite3WalkSelect(&w, p);
77554}
77555
77556/*
77557** Resolve names in expressions that can only reference a single table:
77558**
77559**    *   CHECK constraints
77560**    *   WHERE clauses on partial indices
77561**
77562** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
77563** is set to -1 and the Expr.iColumn value is set to the column number.
77564**
77565** Any errors cause an error message to be set in pParse.
77566*/
77567SQLITE_PRIVATE void sqlite3ResolveSelfReference(
77568  Parse *pParse,      /* Parsing context */
77569  Table *pTab,        /* The table being referenced */
77570  int type,           /* NC_IsCheck or NC_PartIdx */
77571  Expr *pExpr,        /* Expression to resolve.  May be NULL. */
77572  ExprList *pList     /* Expression list to resolve.  May be NUL. */
77573){
77574  SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
77575  NameContext sNC;                /* Name context for pParse->pNewTable */
77576  int i;                          /* Loop counter */
77577
77578  assert( type==NC_IsCheck || type==NC_PartIdx );
77579  memset(&sNC, 0, sizeof(sNC));
77580  memset(&sSrc, 0, sizeof(sSrc));
77581  sSrc.nSrc = 1;
77582  sSrc.a[0].zName = pTab->zName;
77583  sSrc.a[0].pTab = pTab;
77584  sSrc.a[0].iCursor = -1;
77585  sNC.pParse = pParse;
77586  sNC.pSrcList = &sSrc;
77587  sNC.ncFlags = type;
77588  if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
77589  if( pList ){
77590    for(i=0; i<pList->nExpr; i++){
77591      if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
77592        return;
77593      }
77594    }
77595  }
77596}
77597
77598/************** End of resolve.c *********************************************/
77599/************** Begin file expr.c ********************************************/
77600/*
77601** 2001 September 15
77602**
77603** The author disclaims copyright to this source code.  In place of
77604** a legal notice, here is a blessing:
77605**
77606**    May you do good and not evil.
77607**    May you find forgiveness for yourself and forgive others.
77608**    May you share freely, never taking more than you give.
77609**
77610*************************************************************************
77611** This file contains routines used for analyzing expressions and
77612** for generating VDBE code that evaluates expressions in SQLite.
77613*/
77614
77615/*
77616** Return the 'affinity' of the expression pExpr if any.
77617**
77618** If pExpr is a column, a reference to a column via an 'AS' alias,
77619** or a sub-select with a column as the return value, then the
77620** affinity of that column is returned. Otherwise, 0x00 is returned,
77621** indicating no affinity for the expression.
77622**
77623** i.e. the WHERE clause expresssions in the following statements all
77624** have an affinity:
77625**
77626** CREATE TABLE t1(a);
77627** SELECT * FROM t1 WHERE a;
77628** SELECT a AS b FROM t1 WHERE b;
77629** SELECT * FROM t1 WHERE (select a from t1);
77630*/
77631SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
77632  int op;
77633  pExpr = sqlite3ExprSkipCollate(pExpr);
77634  if( pExpr->flags & EP_Generic ) return SQLITE_AFF_NONE;
77635  op = pExpr->op;
77636  if( op==TK_SELECT ){
77637    assert( pExpr->flags&EP_xIsSelect );
77638    return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
77639  }
77640#ifndef SQLITE_OMIT_CAST
77641  if( op==TK_CAST ){
77642    assert( !ExprHasProperty(pExpr, EP_IntValue) );
77643    return sqlite3AffinityType(pExpr->u.zToken, 0);
77644  }
77645#endif
77646  if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
77647   && pExpr->pTab!=0
77648  ){
77649    /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
77650    ** a TK_COLUMN but was previously evaluated and cached in a register */
77651    int j = pExpr->iColumn;
77652    if( j<0 ) return SQLITE_AFF_INTEGER;
77653    assert( pExpr->pTab && j<pExpr->pTab->nCol );
77654    return pExpr->pTab->aCol[j].affinity;
77655  }
77656  return pExpr->affinity;
77657}
77658
77659/*
77660** Set the collating sequence for expression pExpr to be the collating
77661** sequence named by pToken.   Return a pointer to a new Expr node that
77662** implements the COLLATE operator.
77663**
77664** If a memory allocation error occurs, that fact is recorded in pParse->db
77665** and the pExpr parameter is returned unchanged.
77666*/
77667SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
77668  Parse *pParse,           /* Parsing context */
77669  Expr *pExpr,             /* Add the "COLLATE" clause to this expression */
77670  const Token *pCollName   /* Name of collating sequence */
77671){
77672  if( pCollName->n>0 ){
77673    Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, 1);
77674    if( pNew ){
77675      pNew->pLeft = pExpr;
77676      pNew->flags |= EP_Collate|EP_Skip;
77677      pExpr = pNew;
77678    }
77679  }
77680  return pExpr;
77681}
77682SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
77683  Token s;
77684  assert( zC!=0 );
77685  s.z = zC;
77686  s.n = sqlite3Strlen30(s.z);
77687  return sqlite3ExprAddCollateToken(pParse, pExpr, &s);
77688}
77689
77690/*
77691** Skip over any TK_COLLATE or TK_AS operators and any unlikely()
77692** or likelihood() function at the root of an expression.
77693*/
77694SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
77695  while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
77696    if( ExprHasProperty(pExpr, EP_Unlikely) ){
77697      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
77698      assert( pExpr->x.pList->nExpr>0 );
77699      assert( pExpr->op==TK_FUNCTION );
77700      pExpr = pExpr->x.pList->a[0].pExpr;
77701    }else{
77702      assert( pExpr->op==TK_COLLATE || pExpr->op==TK_AS );
77703      pExpr = pExpr->pLeft;
77704    }
77705  }
77706  return pExpr;
77707}
77708
77709/*
77710** Return the collation sequence for the expression pExpr. If
77711** there is no defined collating sequence, return NULL.
77712**
77713** The collating sequence might be determined by a COLLATE operator
77714** or by the presence of a column with a defined collating sequence.
77715** COLLATE operators take first precedence.  Left operands take
77716** precedence over right operands.
77717*/
77718SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
77719  sqlite3 *db = pParse->db;
77720  CollSeq *pColl = 0;
77721  Expr *p = pExpr;
77722  while( p ){
77723    int op = p->op;
77724    if( p->flags & EP_Generic ) break;
77725    if( op==TK_CAST || op==TK_UPLUS ){
77726      p = p->pLeft;
77727      continue;
77728    }
77729    if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
77730      pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
77731      break;
77732    }
77733    if( p->pTab!=0
77734     && (op==TK_AGG_COLUMN || op==TK_COLUMN
77735          || op==TK_REGISTER || op==TK_TRIGGER)
77736    ){
77737      /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
77738      ** a TK_COLUMN but was previously evaluated and cached in a register */
77739      int j = p->iColumn;
77740      if( j>=0 ){
77741        const char *zColl = p->pTab->aCol[j].zColl;
77742        pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
77743      }
77744      break;
77745    }
77746    if( p->flags & EP_Collate ){
77747      if( ALWAYS(p->pLeft) && (p->pLeft->flags & EP_Collate)!=0 ){
77748        p = p->pLeft;
77749      }else{
77750        p = p->pRight;
77751      }
77752    }else{
77753      break;
77754    }
77755  }
77756  if( sqlite3CheckCollSeq(pParse, pColl) ){
77757    pColl = 0;
77758  }
77759  return pColl;
77760}
77761
77762/*
77763** pExpr is an operand of a comparison operator.  aff2 is the
77764** type affinity of the other operand.  This routine returns the
77765** type affinity that should be used for the comparison operator.
77766*/
77767SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
77768  char aff1 = sqlite3ExprAffinity(pExpr);
77769  if( aff1 && aff2 ){
77770    /* Both sides of the comparison are columns. If one has numeric
77771    ** affinity, use that. Otherwise use no affinity.
77772    */
77773    if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
77774      return SQLITE_AFF_NUMERIC;
77775    }else{
77776      return SQLITE_AFF_NONE;
77777    }
77778  }else if( !aff1 && !aff2 ){
77779    /* Neither side of the comparison is a column.  Compare the
77780    ** results directly.
77781    */
77782    return SQLITE_AFF_NONE;
77783  }else{
77784    /* One side is a column, the other is not. Use the columns affinity. */
77785    assert( aff1==0 || aff2==0 );
77786    return (aff1 + aff2);
77787  }
77788}
77789
77790/*
77791** pExpr is a comparison operator.  Return the type affinity that should
77792** be applied to both operands prior to doing the comparison.
77793*/
77794static char comparisonAffinity(Expr *pExpr){
77795  char aff;
77796  assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
77797          pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
77798          pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
77799  assert( pExpr->pLeft );
77800  aff = sqlite3ExprAffinity(pExpr->pLeft);
77801  if( pExpr->pRight ){
77802    aff = sqlite3CompareAffinity(pExpr->pRight, aff);
77803  }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
77804    aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
77805  }else if( !aff ){
77806    aff = SQLITE_AFF_NONE;
77807  }
77808  return aff;
77809}
77810
77811/*
77812** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
77813** idx_affinity is the affinity of an indexed column. Return true
77814** if the index with affinity idx_affinity may be used to implement
77815** the comparison in pExpr.
77816*/
77817SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
77818  char aff = comparisonAffinity(pExpr);
77819  switch( aff ){
77820    case SQLITE_AFF_NONE:
77821      return 1;
77822    case SQLITE_AFF_TEXT:
77823      return idx_affinity==SQLITE_AFF_TEXT;
77824    default:
77825      return sqlite3IsNumericAffinity(idx_affinity);
77826  }
77827}
77828
77829/*
77830** Return the P5 value that should be used for a binary comparison
77831** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
77832*/
77833static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
77834  u8 aff = (char)sqlite3ExprAffinity(pExpr2);
77835  aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
77836  return aff;
77837}
77838
77839/*
77840** Return a pointer to the collation sequence that should be used by
77841** a binary comparison operator comparing pLeft and pRight.
77842**
77843** If the left hand expression has a collating sequence type, then it is
77844** used. Otherwise the collation sequence for the right hand expression
77845** is used, or the default (BINARY) if neither expression has a collating
77846** type.
77847**
77848** Argument pRight (but not pLeft) may be a null pointer. In this case,
77849** it is not considered.
77850*/
77851SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
77852  Parse *pParse,
77853  Expr *pLeft,
77854  Expr *pRight
77855){
77856  CollSeq *pColl;
77857  assert( pLeft );
77858  if( pLeft->flags & EP_Collate ){
77859    pColl = sqlite3ExprCollSeq(pParse, pLeft);
77860  }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
77861    pColl = sqlite3ExprCollSeq(pParse, pRight);
77862  }else{
77863    pColl = sqlite3ExprCollSeq(pParse, pLeft);
77864    if( !pColl ){
77865      pColl = sqlite3ExprCollSeq(pParse, pRight);
77866    }
77867  }
77868  return pColl;
77869}
77870
77871/*
77872** Generate code for a comparison operator.
77873*/
77874static int codeCompare(
77875  Parse *pParse,    /* The parsing (and code generating) context */
77876  Expr *pLeft,      /* The left operand */
77877  Expr *pRight,     /* The right operand */
77878  int opcode,       /* The comparison opcode */
77879  int in1, int in2, /* Register holding operands */
77880  int dest,         /* Jump here if true.  */
77881  int jumpIfNull    /* If true, jump if either operand is NULL */
77882){
77883  int p5;
77884  int addr;
77885  CollSeq *p4;
77886
77887  p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
77888  p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
77889  addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
77890                           (void*)p4, P4_COLLSEQ);
77891  sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
77892  return addr;
77893}
77894
77895#if SQLITE_MAX_EXPR_DEPTH>0
77896/*
77897** Check that argument nHeight is less than or equal to the maximum
77898** expression depth allowed. If it is not, leave an error message in
77899** pParse.
77900*/
77901SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
77902  int rc = SQLITE_OK;
77903  int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
77904  if( nHeight>mxHeight ){
77905    sqlite3ErrorMsg(pParse,
77906       "Expression tree is too large (maximum depth %d)", mxHeight
77907    );
77908    rc = SQLITE_ERROR;
77909  }
77910  return rc;
77911}
77912
77913/* The following three functions, heightOfExpr(), heightOfExprList()
77914** and heightOfSelect(), are used to determine the maximum height
77915** of any expression tree referenced by the structure passed as the
77916** first argument.
77917**
77918** If this maximum height is greater than the current value pointed
77919** to by pnHeight, the second parameter, then set *pnHeight to that
77920** value.
77921*/
77922static void heightOfExpr(Expr *p, int *pnHeight){
77923  if( p ){
77924    if( p->nHeight>*pnHeight ){
77925      *pnHeight = p->nHeight;
77926    }
77927  }
77928}
77929static void heightOfExprList(ExprList *p, int *pnHeight){
77930  if( p ){
77931    int i;
77932    for(i=0; i<p->nExpr; i++){
77933      heightOfExpr(p->a[i].pExpr, pnHeight);
77934    }
77935  }
77936}
77937static void heightOfSelect(Select *p, int *pnHeight){
77938  if( p ){
77939    heightOfExpr(p->pWhere, pnHeight);
77940    heightOfExpr(p->pHaving, pnHeight);
77941    heightOfExpr(p->pLimit, pnHeight);
77942    heightOfExpr(p->pOffset, pnHeight);
77943    heightOfExprList(p->pEList, pnHeight);
77944    heightOfExprList(p->pGroupBy, pnHeight);
77945    heightOfExprList(p->pOrderBy, pnHeight);
77946    heightOfSelect(p->pPrior, pnHeight);
77947  }
77948}
77949
77950/*
77951** Set the Expr.nHeight variable in the structure passed as an
77952** argument. An expression with no children, Expr.pList or
77953** Expr.pSelect member has a height of 1. Any other expression
77954** has a height equal to the maximum height of any other
77955** referenced Expr plus one.
77956*/
77957static void exprSetHeight(Expr *p){
77958  int nHeight = 0;
77959  heightOfExpr(p->pLeft, &nHeight);
77960  heightOfExpr(p->pRight, &nHeight);
77961  if( ExprHasProperty(p, EP_xIsSelect) ){
77962    heightOfSelect(p->x.pSelect, &nHeight);
77963  }else{
77964    heightOfExprList(p->x.pList, &nHeight);
77965  }
77966  p->nHeight = nHeight + 1;
77967}
77968
77969/*
77970** Set the Expr.nHeight variable using the exprSetHeight() function. If
77971** the height is greater than the maximum allowed expression depth,
77972** leave an error in pParse.
77973*/
77974SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
77975  exprSetHeight(p);
77976  sqlite3ExprCheckHeight(pParse, p->nHeight);
77977}
77978
77979/*
77980** Return the maximum height of any expression tree referenced
77981** by the select statement passed as an argument.
77982*/
77983SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
77984  int nHeight = 0;
77985  heightOfSelect(p, &nHeight);
77986  return nHeight;
77987}
77988#else
77989  #define exprSetHeight(y)
77990#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
77991
77992/*
77993** This routine is the core allocator for Expr nodes.
77994**
77995** Construct a new expression node and return a pointer to it.  Memory
77996** for this node and for the pToken argument is a single allocation
77997** obtained from sqlite3DbMalloc().  The calling function
77998** is responsible for making sure the node eventually gets freed.
77999**
78000** If dequote is true, then the token (if it exists) is dequoted.
78001** If dequote is false, no dequoting is performance.  The deQuote
78002** parameter is ignored if pToken is NULL or if the token does not
78003** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
78004** then the EP_DblQuoted flag is set on the expression node.
78005**
78006** Special case:  If op==TK_INTEGER and pToken points to a string that
78007** can be translated into a 32-bit integer, then the token is not
78008** stored in u.zToken.  Instead, the integer values is written
78009** into u.iValue and the EP_IntValue flag is set.  No extra storage
78010** is allocated to hold the integer text and the dequote flag is ignored.
78011*/
78012SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
78013  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
78014  int op,                 /* Expression opcode */
78015  const Token *pToken,    /* Token argument.  Might be NULL */
78016  int dequote             /* True to dequote */
78017){
78018  Expr *pNew;
78019  int nExtra = 0;
78020  int iValue = 0;
78021
78022  if( pToken ){
78023    if( op!=TK_INTEGER || pToken->z==0
78024          || sqlite3GetInt32(pToken->z, &iValue)==0 ){
78025      nExtra = pToken->n+1;
78026      assert( iValue>=0 );
78027    }
78028  }
78029  pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
78030  if( pNew ){
78031    pNew->op = (u8)op;
78032    pNew->iAgg = -1;
78033    if( pToken ){
78034      if( nExtra==0 ){
78035        pNew->flags |= EP_IntValue;
78036        pNew->u.iValue = iValue;
78037      }else{
78038        int c;
78039        pNew->u.zToken = (char*)&pNew[1];
78040        assert( pToken->z!=0 || pToken->n==0 );
78041        if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
78042        pNew->u.zToken[pToken->n] = 0;
78043        if( dequote && nExtra>=3
78044             && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
78045          sqlite3Dequote(pNew->u.zToken);
78046          if( c=='"' ) pNew->flags |= EP_DblQuoted;
78047        }
78048      }
78049    }
78050#if SQLITE_MAX_EXPR_DEPTH>0
78051    pNew->nHeight = 1;
78052#endif
78053  }
78054  return pNew;
78055}
78056
78057/*
78058** Allocate a new expression node from a zero-terminated token that has
78059** already been dequoted.
78060*/
78061SQLITE_PRIVATE Expr *sqlite3Expr(
78062  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
78063  int op,                 /* Expression opcode */
78064  const char *zToken      /* Token argument.  Might be NULL */
78065){
78066  Token x;
78067  x.z = zToken;
78068  x.n = zToken ? sqlite3Strlen30(zToken) : 0;
78069  return sqlite3ExprAlloc(db, op, &x, 0);
78070}
78071
78072/*
78073** Attach subtrees pLeft and pRight to the Expr node pRoot.
78074**
78075** If pRoot==NULL that means that a memory allocation error has occurred.
78076** In that case, delete the subtrees pLeft and pRight.
78077*/
78078SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
78079  sqlite3 *db,
78080  Expr *pRoot,
78081  Expr *pLeft,
78082  Expr *pRight
78083){
78084  if( pRoot==0 ){
78085    assert( db->mallocFailed );
78086    sqlite3ExprDelete(db, pLeft);
78087    sqlite3ExprDelete(db, pRight);
78088  }else{
78089    if( pRight ){
78090      pRoot->pRight = pRight;
78091      pRoot->flags |= EP_Collate & pRight->flags;
78092    }
78093    if( pLeft ){
78094      pRoot->pLeft = pLeft;
78095      pRoot->flags |= EP_Collate & pLeft->flags;
78096    }
78097    exprSetHeight(pRoot);
78098  }
78099}
78100
78101/*
78102** Allocate a Expr node which joins as many as two subtrees.
78103**
78104** One or both of the subtrees can be NULL.  Return a pointer to the new
78105** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
78106** free the subtrees and return NULL.
78107*/
78108SQLITE_PRIVATE Expr *sqlite3PExpr(
78109  Parse *pParse,          /* Parsing context */
78110  int op,                 /* Expression opcode */
78111  Expr *pLeft,            /* Left operand */
78112  Expr *pRight,           /* Right operand */
78113  const Token *pToken     /* Argument token */
78114){
78115  Expr *p;
78116  if( op==TK_AND && pLeft && pRight ){
78117    /* Take advantage of short-circuit false optimization for AND */
78118    p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
78119  }else{
78120    p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
78121    sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
78122  }
78123  if( p ) {
78124    sqlite3ExprCheckHeight(pParse, p->nHeight);
78125  }
78126  return p;
78127}
78128
78129/*
78130** If the expression is always either TRUE or FALSE (respectively),
78131** then return 1.  If one cannot determine the truth value of the
78132** expression at compile-time return 0.
78133**
78134** This is an optimization.  If is OK to return 0 here even if
78135** the expression really is always false or false (a false negative).
78136** But it is a bug to return 1 if the expression might have different
78137** boolean values in different circumstances (a false positive.)
78138**
78139** Note that if the expression is part of conditional for a
78140** LEFT JOIN, then we cannot determine at compile-time whether or not
78141** is it true or false, so always return 0.
78142*/
78143static int exprAlwaysTrue(Expr *p){
78144  int v = 0;
78145  if( ExprHasProperty(p, EP_FromJoin) ) return 0;
78146  if( !sqlite3ExprIsInteger(p, &v) ) return 0;
78147  return v!=0;
78148}
78149static int exprAlwaysFalse(Expr *p){
78150  int v = 0;
78151  if( ExprHasProperty(p, EP_FromJoin) ) return 0;
78152  if( !sqlite3ExprIsInteger(p, &v) ) return 0;
78153  return v==0;
78154}
78155
78156/*
78157** Join two expressions using an AND operator.  If either expression is
78158** NULL, then just return the other expression.
78159**
78160** If one side or the other of the AND is known to be false, then instead
78161** of returning an AND expression, just return a constant expression with
78162** a value of false.
78163*/
78164SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
78165  if( pLeft==0 ){
78166    return pRight;
78167  }else if( pRight==0 ){
78168    return pLeft;
78169  }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
78170    sqlite3ExprDelete(db, pLeft);
78171    sqlite3ExprDelete(db, pRight);
78172    return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
78173  }else{
78174    Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
78175    sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
78176    return pNew;
78177  }
78178}
78179
78180/*
78181** Construct a new expression node for a function with multiple
78182** arguments.
78183*/
78184SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
78185  Expr *pNew;
78186  sqlite3 *db = pParse->db;
78187  assert( pToken );
78188  pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
78189  if( pNew==0 ){
78190    sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
78191    return 0;
78192  }
78193  pNew->x.pList = pList;
78194  assert( !ExprHasProperty(pNew, EP_xIsSelect) );
78195  sqlite3ExprSetHeight(pParse, pNew);
78196  return pNew;
78197}
78198
78199/*
78200** Assign a variable number to an expression that encodes a wildcard
78201** in the original SQL statement.
78202**
78203** Wildcards consisting of a single "?" are assigned the next sequential
78204** variable number.
78205**
78206** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
78207** sure "nnn" is not too be to avoid a denial of service attack when
78208** the SQL statement comes from an external source.
78209**
78210** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
78211** as the previous instance of the same wildcard.  Or if this is the first
78212** instance of the wildcard, the next sequenial variable number is
78213** assigned.
78214*/
78215SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
78216  sqlite3 *db = pParse->db;
78217  const char *z;
78218
78219  if( pExpr==0 ) return;
78220  assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
78221  z = pExpr->u.zToken;
78222  assert( z!=0 );
78223  assert( z[0]!=0 );
78224  if( z[1]==0 ){
78225    /* Wildcard of the form "?".  Assign the next variable number */
78226    assert( z[0]=='?' );
78227    pExpr->iColumn = (ynVar)(++pParse->nVar);
78228  }else{
78229    ynVar x = 0;
78230    u32 n = sqlite3Strlen30(z);
78231    if( z[0]=='?' ){
78232      /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
78233      ** use it as the variable number */
78234      i64 i;
78235      int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
78236      pExpr->iColumn = x = (ynVar)i;
78237      testcase( i==0 );
78238      testcase( i==1 );
78239      testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
78240      testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
78241      if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
78242        sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
78243            db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
78244        x = 0;
78245      }
78246      if( i>pParse->nVar ){
78247        pParse->nVar = (int)i;
78248      }
78249    }else{
78250      /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
78251      ** number as the prior appearance of the same name, or if the name
78252      ** has never appeared before, reuse the same variable number
78253      */
78254      ynVar i;
78255      for(i=0; i<pParse->nzVar; i++){
78256        if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
78257          pExpr->iColumn = x = (ynVar)i+1;
78258          break;
78259        }
78260      }
78261      if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
78262    }
78263    if( x>0 ){
78264      if( x>pParse->nzVar ){
78265        char **a;
78266        a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
78267        if( a==0 ) return;  /* Error reported through db->mallocFailed */
78268        pParse->azVar = a;
78269        memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
78270        pParse->nzVar = x;
78271      }
78272      if( z[0]!='?' || pParse->azVar[x-1]==0 ){
78273        sqlite3DbFree(db, pParse->azVar[x-1]);
78274        pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
78275      }
78276    }
78277  }
78278  if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
78279    sqlite3ErrorMsg(pParse, "too many SQL variables");
78280  }
78281}
78282
78283/*
78284** Recursively delete an expression tree.
78285*/
78286SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
78287  if( p==0 ) return;
78288  /* Sanity check: Assert that the IntValue is non-negative if it exists */
78289  assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
78290  if( !ExprHasProperty(p, EP_TokenOnly) ){
78291    /* The Expr.x union is never used at the same time as Expr.pRight */
78292    assert( p->x.pList==0 || p->pRight==0 );
78293    sqlite3ExprDelete(db, p->pLeft);
78294    sqlite3ExprDelete(db, p->pRight);
78295    if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
78296    if( ExprHasProperty(p, EP_xIsSelect) ){
78297      sqlite3SelectDelete(db, p->x.pSelect);
78298    }else{
78299      sqlite3ExprListDelete(db, p->x.pList);
78300    }
78301  }
78302  if( !ExprHasProperty(p, EP_Static) ){
78303    sqlite3DbFree(db, p);
78304  }
78305}
78306
78307/*
78308** Return the number of bytes allocated for the expression structure
78309** passed as the first argument. This is always one of EXPR_FULLSIZE,
78310** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
78311*/
78312static int exprStructSize(Expr *p){
78313  if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
78314  if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
78315  return EXPR_FULLSIZE;
78316}
78317
78318/*
78319** The dupedExpr*Size() routines each return the number of bytes required
78320** to store a copy of an expression or expression tree.  They differ in
78321** how much of the tree is measured.
78322**
78323**     dupedExprStructSize()     Size of only the Expr structure
78324**     dupedExprNodeSize()       Size of Expr + space for token
78325**     dupedExprSize()           Expr + token + subtree components
78326**
78327***************************************************************************
78328**
78329** The dupedExprStructSize() function returns two values OR-ed together:
78330** (1) the space required for a copy of the Expr structure only and
78331** (2) the EP_xxx flags that indicate what the structure size should be.
78332** The return values is always one of:
78333**
78334**      EXPR_FULLSIZE
78335**      EXPR_REDUCEDSIZE   | EP_Reduced
78336**      EXPR_TOKENONLYSIZE | EP_TokenOnly
78337**
78338** The size of the structure can be found by masking the return value
78339** of this routine with 0xfff.  The flags can be found by masking the
78340** return value with EP_Reduced|EP_TokenOnly.
78341**
78342** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
78343** (unreduced) Expr objects as they or originally constructed by the parser.
78344** During expression analysis, extra information is computed and moved into
78345** later parts of teh Expr object and that extra information might get chopped
78346** off if the expression is reduced.  Note also that it does not work to
78347** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
78348** to reduce a pristine expression tree from the parser.  The implementation
78349** of dupedExprStructSize() contain multiple assert() statements that attempt
78350** to enforce this constraint.
78351*/
78352static int dupedExprStructSize(Expr *p, int flags){
78353  int nSize;
78354  assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
78355  assert( EXPR_FULLSIZE<=0xfff );
78356  assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
78357  if( 0==(flags&EXPRDUP_REDUCE) ){
78358    nSize = EXPR_FULLSIZE;
78359  }else{
78360    assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
78361    assert( !ExprHasProperty(p, EP_FromJoin) );
78362    assert( !ExprHasProperty(p, EP_MemToken) );
78363    assert( !ExprHasProperty(p, EP_NoReduce) );
78364    if( p->pLeft || p->x.pList ){
78365      nSize = EXPR_REDUCEDSIZE | EP_Reduced;
78366    }else{
78367      assert( p->pRight==0 );
78368      nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
78369    }
78370  }
78371  return nSize;
78372}
78373
78374/*
78375** This function returns the space in bytes required to store the copy
78376** of the Expr structure and a copy of the Expr.u.zToken string (if that
78377** string is defined.)
78378*/
78379static int dupedExprNodeSize(Expr *p, int flags){
78380  int nByte = dupedExprStructSize(p, flags) & 0xfff;
78381  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
78382    nByte += sqlite3Strlen30(p->u.zToken)+1;
78383  }
78384  return ROUND8(nByte);
78385}
78386
78387/*
78388** Return the number of bytes required to create a duplicate of the
78389** expression passed as the first argument. The second argument is a
78390** mask containing EXPRDUP_XXX flags.
78391**
78392** The value returned includes space to create a copy of the Expr struct
78393** itself and the buffer referred to by Expr.u.zToken, if any.
78394**
78395** If the EXPRDUP_REDUCE flag is set, then the return value includes
78396** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
78397** and Expr.pRight variables (but not for any structures pointed to or
78398** descended from the Expr.x.pList or Expr.x.pSelect variables).
78399*/
78400static int dupedExprSize(Expr *p, int flags){
78401  int nByte = 0;
78402  if( p ){
78403    nByte = dupedExprNodeSize(p, flags);
78404    if( flags&EXPRDUP_REDUCE ){
78405      nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
78406    }
78407  }
78408  return nByte;
78409}
78410
78411/*
78412** This function is similar to sqlite3ExprDup(), except that if pzBuffer
78413** is not NULL then *pzBuffer is assumed to point to a buffer large enough
78414** to store the copy of expression p, the copies of p->u.zToken
78415** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
78416** if any. Before returning, *pzBuffer is set to the first byte passed the
78417** portion of the buffer copied into by this function.
78418*/
78419static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
78420  Expr *pNew = 0;                      /* Value to return */
78421  if( p ){
78422    const int isReduced = (flags&EXPRDUP_REDUCE);
78423    u8 *zAlloc;
78424    u32 staticFlag = 0;
78425
78426    assert( pzBuffer==0 || isReduced );
78427
78428    /* Figure out where to write the new Expr structure. */
78429    if( pzBuffer ){
78430      zAlloc = *pzBuffer;
78431      staticFlag = EP_Static;
78432    }else{
78433      zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
78434    }
78435    pNew = (Expr *)zAlloc;
78436
78437    if( pNew ){
78438      /* Set nNewSize to the size allocated for the structure pointed to
78439      ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
78440      ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
78441      ** by the copy of the p->u.zToken string (if any).
78442      */
78443      const unsigned nStructSize = dupedExprStructSize(p, flags);
78444      const int nNewSize = nStructSize & 0xfff;
78445      int nToken;
78446      if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
78447        nToken = sqlite3Strlen30(p->u.zToken) + 1;
78448      }else{
78449        nToken = 0;
78450      }
78451      if( isReduced ){
78452        assert( ExprHasProperty(p, EP_Reduced)==0 );
78453        memcpy(zAlloc, p, nNewSize);
78454      }else{
78455        int nSize = exprStructSize(p);
78456        memcpy(zAlloc, p, nSize);
78457        memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
78458      }
78459
78460      /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
78461      pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
78462      pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
78463      pNew->flags |= staticFlag;
78464
78465      /* Copy the p->u.zToken string, if any. */
78466      if( nToken ){
78467        char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
78468        memcpy(zToken, p->u.zToken, nToken);
78469      }
78470
78471      if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
78472        /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
78473        if( ExprHasProperty(p, EP_xIsSelect) ){
78474          pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
78475        }else{
78476          pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
78477        }
78478      }
78479
78480      /* Fill in pNew->pLeft and pNew->pRight. */
78481      if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
78482        zAlloc += dupedExprNodeSize(p, flags);
78483        if( ExprHasProperty(pNew, EP_Reduced) ){
78484          pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
78485          pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
78486        }
78487        if( pzBuffer ){
78488          *pzBuffer = zAlloc;
78489        }
78490      }else{
78491        if( !ExprHasProperty(p, EP_TokenOnly) ){
78492          pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
78493          pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
78494        }
78495      }
78496
78497    }
78498  }
78499  return pNew;
78500}
78501
78502/*
78503** Create and return a deep copy of the object passed as the second
78504** argument. If an OOM condition is encountered, NULL is returned
78505** and the db->mallocFailed flag set.
78506*/
78507#ifndef SQLITE_OMIT_CTE
78508static With *withDup(sqlite3 *db, With *p){
78509  With *pRet = 0;
78510  if( p ){
78511    int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
78512    pRet = sqlite3DbMallocZero(db, nByte);
78513    if( pRet ){
78514      int i;
78515      pRet->nCte = p->nCte;
78516      for(i=0; i<p->nCte; i++){
78517        pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
78518        pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
78519        pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
78520      }
78521    }
78522  }
78523  return pRet;
78524}
78525#else
78526# define withDup(x,y) 0
78527#endif
78528
78529/*
78530** The following group of routines make deep copies of expressions,
78531** expression lists, ID lists, and select statements.  The copies can
78532** be deleted (by being passed to their respective ...Delete() routines)
78533** without effecting the originals.
78534**
78535** The expression list, ID, and source lists return by sqlite3ExprListDup(),
78536** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
78537** by subsequent calls to sqlite*ListAppend() routines.
78538**
78539** Any tables that the SrcList might point to are not duplicated.
78540**
78541** The flags parameter contains a combination of the EXPRDUP_XXX flags.
78542** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
78543** truncated version of the usual Expr structure that will be stored as
78544** part of the in-memory representation of the database schema.
78545*/
78546SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
78547  return exprDup(db, p, flags, 0);
78548}
78549SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
78550  ExprList *pNew;
78551  struct ExprList_item *pItem, *pOldItem;
78552  int i;
78553  if( p==0 ) return 0;
78554  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
78555  if( pNew==0 ) return 0;
78556  pNew->nExpr = i = p->nExpr;
78557  if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
78558  pNew->a = pItem = sqlite3DbMallocRaw(db,  i*sizeof(p->a[0]) );
78559  if( pItem==0 ){
78560    sqlite3DbFree(db, pNew);
78561    return 0;
78562  }
78563  pOldItem = p->a;
78564  for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
78565    Expr *pOldExpr = pOldItem->pExpr;
78566    pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
78567    pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
78568    pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
78569    pItem->sortOrder = pOldItem->sortOrder;
78570    pItem->done = 0;
78571    pItem->bSpanIsTab = pOldItem->bSpanIsTab;
78572    pItem->u = pOldItem->u;
78573  }
78574  return pNew;
78575}
78576
78577/*
78578** If cursors, triggers, views and subqueries are all omitted from
78579** the build, then none of the following routines, except for
78580** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
78581** called with a NULL argument.
78582*/
78583#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
78584 || !defined(SQLITE_OMIT_SUBQUERY)
78585SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
78586  SrcList *pNew;
78587  int i;
78588  int nByte;
78589  if( p==0 ) return 0;
78590  nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
78591  pNew = sqlite3DbMallocRaw(db, nByte );
78592  if( pNew==0 ) return 0;
78593  pNew->nSrc = pNew->nAlloc = p->nSrc;
78594  for(i=0; i<p->nSrc; i++){
78595    struct SrcList_item *pNewItem = &pNew->a[i];
78596    struct SrcList_item *pOldItem = &p->a[i];
78597    Table *pTab;
78598    pNewItem->pSchema = pOldItem->pSchema;
78599    pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
78600    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
78601    pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
78602    pNewItem->jointype = pOldItem->jointype;
78603    pNewItem->iCursor = pOldItem->iCursor;
78604    pNewItem->addrFillSub = pOldItem->addrFillSub;
78605    pNewItem->regReturn = pOldItem->regReturn;
78606    pNewItem->isCorrelated = pOldItem->isCorrelated;
78607    pNewItem->viaCoroutine = pOldItem->viaCoroutine;
78608    pNewItem->isRecursive = pOldItem->isRecursive;
78609    pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
78610    pNewItem->notIndexed = pOldItem->notIndexed;
78611    pNewItem->pIndex = pOldItem->pIndex;
78612    pTab = pNewItem->pTab = pOldItem->pTab;
78613    if( pTab ){
78614      pTab->nRef++;
78615    }
78616    pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
78617    pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
78618    pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
78619    pNewItem->colUsed = pOldItem->colUsed;
78620  }
78621  return pNew;
78622}
78623SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
78624  IdList *pNew;
78625  int i;
78626  if( p==0 ) return 0;
78627  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
78628  if( pNew==0 ) return 0;
78629  pNew->nId = p->nId;
78630  pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
78631  if( pNew->a==0 ){
78632    sqlite3DbFree(db, pNew);
78633    return 0;
78634  }
78635  /* Note that because the size of the allocation for p->a[] is not
78636  ** necessarily a power of two, sqlite3IdListAppend() may not be called
78637  ** on the duplicate created by this function. */
78638  for(i=0; i<p->nId; i++){
78639    struct IdList_item *pNewItem = &pNew->a[i];
78640    struct IdList_item *pOldItem = &p->a[i];
78641    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
78642    pNewItem->idx = pOldItem->idx;
78643  }
78644  return pNew;
78645}
78646SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
78647  Select *pNew, *pPrior;
78648  if( p==0 ) return 0;
78649  pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
78650  if( pNew==0 ) return 0;
78651  pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
78652  pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
78653  pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
78654  pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
78655  pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
78656  pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
78657  pNew->op = p->op;
78658  pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
78659  if( pPrior ) pPrior->pNext = pNew;
78660  pNew->pNext = 0;
78661  pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
78662  pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
78663  pNew->iLimit = 0;
78664  pNew->iOffset = 0;
78665  pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
78666  pNew->addrOpenEphm[0] = -1;
78667  pNew->addrOpenEphm[1] = -1;
78668  pNew->nSelectRow = p->nSelectRow;
78669  pNew->pWith = withDup(db, p->pWith);
78670  return pNew;
78671}
78672#else
78673SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
78674  assert( p==0 );
78675  return 0;
78676}
78677#endif
78678
78679
78680/*
78681** Add a new element to the end of an expression list.  If pList is
78682** initially NULL, then create a new expression list.
78683**
78684** If a memory allocation error occurs, the entire list is freed and
78685** NULL is returned.  If non-NULL is returned, then it is guaranteed
78686** that the new entry was successfully appended.
78687*/
78688SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
78689  Parse *pParse,          /* Parsing context */
78690  ExprList *pList,        /* List to which to append. Might be NULL */
78691  Expr *pExpr             /* Expression to be appended. Might be NULL */
78692){
78693  sqlite3 *db = pParse->db;
78694  if( pList==0 ){
78695    pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
78696    if( pList==0 ){
78697      goto no_mem;
78698    }
78699    pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
78700    if( pList->a==0 ) goto no_mem;
78701  }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
78702    struct ExprList_item *a;
78703    assert( pList->nExpr>0 );
78704    a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
78705    if( a==0 ){
78706      goto no_mem;
78707    }
78708    pList->a = a;
78709  }
78710  assert( pList->a!=0 );
78711  if( 1 ){
78712    struct ExprList_item *pItem = &pList->a[pList->nExpr++];
78713    memset(pItem, 0, sizeof(*pItem));
78714    pItem->pExpr = pExpr;
78715  }
78716  return pList;
78717
78718no_mem:
78719  /* Avoid leaking memory if malloc has failed. */
78720  sqlite3ExprDelete(db, pExpr);
78721  sqlite3ExprListDelete(db, pList);
78722  return 0;
78723}
78724
78725/*
78726** Set the ExprList.a[].zName element of the most recently added item
78727** on the expression list.
78728**
78729** pList might be NULL following an OOM error.  But pName should never be
78730** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
78731** is set.
78732*/
78733SQLITE_PRIVATE void sqlite3ExprListSetName(
78734  Parse *pParse,          /* Parsing context */
78735  ExprList *pList,        /* List to which to add the span. */
78736  Token *pName,           /* Name to be added */
78737  int dequote             /* True to cause the name to be dequoted */
78738){
78739  assert( pList!=0 || pParse->db->mallocFailed!=0 );
78740  if( pList ){
78741    struct ExprList_item *pItem;
78742    assert( pList->nExpr>0 );
78743    pItem = &pList->a[pList->nExpr-1];
78744    assert( pItem->zName==0 );
78745    pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
78746    if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
78747  }
78748}
78749
78750/*
78751** Set the ExprList.a[].zSpan element of the most recently added item
78752** on the expression list.
78753**
78754** pList might be NULL following an OOM error.  But pSpan should never be
78755** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
78756** is set.
78757*/
78758SQLITE_PRIVATE void sqlite3ExprListSetSpan(
78759  Parse *pParse,          /* Parsing context */
78760  ExprList *pList,        /* List to which to add the span. */
78761  ExprSpan *pSpan         /* The span to be added */
78762){
78763  sqlite3 *db = pParse->db;
78764  assert( pList!=0 || db->mallocFailed!=0 );
78765  if( pList ){
78766    struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
78767    assert( pList->nExpr>0 );
78768    assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
78769    sqlite3DbFree(db, pItem->zSpan);
78770    pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
78771                                    (int)(pSpan->zEnd - pSpan->zStart));
78772  }
78773}
78774
78775/*
78776** If the expression list pEList contains more than iLimit elements,
78777** leave an error message in pParse.
78778*/
78779SQLITE_PRIVATE void sqlite3ExprListCheckLength(
78780  Parse *pParse,
78781  ExprList *pEList,
78782  const char *zObject
78783){
78784  int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
78785  testcase( pEList && pEList->nExpr==mx );
78786  testcase( pEList && pEList->nExpr==mx+1 );
78787  if( pEList && pEList->nExpr>mx ){
78788    sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
78789  }
78790}
78791
78792/*
78793** Delete an entire expression list.
78794*/
78795SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
78796  int i;
78797  struct ExprList_item *pItem;
78798  if( pList==0 ) return;
78799  assert( pList->a!=0 || pList->nExpr==0 );
78800  for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
78801    sqlite3ExprDelete(db, pItem->pExpr);
78802    sqlite3DbFree(db, pItem->zName);
78803    sqlite3DbFree(db, pItem->zSpan);
78804  }
78805  sqlite3DbFree(db, pList->a);
78806  sqlite3DbFree(db, pList);
78807}
78808
78809/*
78810** These routines are Walker callbacks.  Walker.u.pi is a pointer
78811** to an integer.  These routines are checking an expression to see
78812** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
78813** not constant.
78814**
78815** These callback routines are used to implement the following:
78816**
78817**     sqlite3ExprIsConstant()
78818**     sqlite3ExprIsConstantNotJoin()
78819**     sqlite3ExprIsConstantOrFunction()
78820**
78821*/
78822static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
78823
78824  /* If pWalker->u.i is 3 then any term of the expression that comes from
78825  ** the ON or USING clauses of a join disqualifies the expression
78826  ** from being considered constant. */
78827  if( pWalker->u.i==3 && ExprHasProperty(pExpr, EP_FromJoin) ){
78828    pWalker->u.i = 0;
78829    return WRC_Abort;
78830  }
78831
78832  switch( pExpr->op ){
78833    /* Consider functions to be constant if all their arguments are constant
78834    ** and either pWalker->u.i==2 or the function as the SQLITE_FUNC_CONST
78835    ** flag. */
78836    case TK_FUNCTION:
78837      if( pWalker->u.i==2 || ExprHasProperty(pExpr,EP_Constant) ){
78838        return WRC_Continue;
78839      }
78840      /* Fall through */
78841    case TK_ID:
78842    case TK_COLUMN:
78843    case TK_AGG_FUNCTION:
78844    case TK_AGG_COLUMN:
78845      testcase( pExpr->op==TK_ID );
78846      testcase( pExpr->op==TK_COLUMN );
78847      testcase( pExpr->op==TK_AGG_FUNCTION );
78848      testcase( pExpr->op==TK_AGG_COLUMN );
78849      pWalker->u.i = 0;
78850      return WRC_Abort;
78851    default:
78852      testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
78853      testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
78854      return WRC_Continue;
78855  }
78856}
78857static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
78858  UNUSED_PARAMETER(NotUsed);
78859  pWalker->u.i = 0;
78860  return WRC_Abort;
78861}
78862static int exprIsConst(Expr *p, int initFlag){
78863  Walker w;
78864  memset(&w, 0, sizeof(w));
78865  w.u.i = initFlag;
78866  w.xExprCallback = exprNodeIsConstant;
78867  w.xSelectCallback = selectNodeIsConstant;
78868  sqlite3WalkExpr(&w, p);
78869  return w.u.i;
78870}
78871
78872/*
78873** Walk an expression tree.  Return 1 if the expression is constant
78874** and 0 if it involves variables or function calls.
78875**
78876** For the purposes of this function, a double-quoted string (ex: "abc")
78877** is considered a variable but a single-quoted string (ex: 'abc') is
78878** a constant.
78879*/
78880SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
78881  return exprIsConst(p, 1);
78882}
78883
78884/*
78885** Walk an expression tree.  Return 1 if the expression is constant
78886** that does no originate from the ON or USING clauses of a join.
78887** Return 0 if it involves variables or function calls or terms from
78888** an ON or USING clause.
78889*/
78890SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
78891  return exprIsConst(p, 3);
78892}
78893
78894/*
78895** Walk an expression tree.  Return 1 if the expression is constant
78896** or a function call with constant arguments.  Return and 0 if there
78897** are any variables.
78898**
78899** For the purposes of this function, a double-quoted string (ex: "abc")
78900** is considered a variable but a single-quoted string (ex: 'abc') is
78901** a constant.
78902*/
78903SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
78904  return exprIsConst(p, 2);
78905}
78906
78907/*
78908** If the expression p codes a constant integer that is small enough
78909** to fit in a 32-bit integer, return 1 and put the value of the integer
78910** in *pValue.  If the expression is not an integer or if it is too big
78911** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
78912*/
78913SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
78914  int rc = 0;
78915
78916  /* If an expression is an integer literal that fits in a signed 32-bit
78917  ** integer, then the EP_IntValue flag will have already been set */
78918  assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
78919           || sqlite3GetInt32(p->u.zToken, &rc)==0 );
78920
78921  if( p->flags & EP_IntValue ){
78922    *pValue = p->u.iValue;
78923    return 1;
78924  }
78925  switch( p->op ){
78926    case TK_UPLUS: {
78927      rc = sqlite3ExprIsInteger(p->pLeft, pValue);
78928      break;
78929    }
78930    case TK_UMINUS: {
78931      int v;
78932      if( sqlite3ExprIsInteger(p->pLeft, &v) ){
78933        assert( v!=(-2147483647-1) );
78934        *pValue = -v;
78935        rc = 1;
78936      }
78937      break;
78938    }
78939    default: break;
78940  }
78941  return rc;
78942}
78943
78944/*
78945** Return FALSE if there is no chance that the expression can be NULL.
78946**
78947** If the expression might be NULL or if the expression is too complex
78948** to tell return TRUE.
78949**
78950** This routine is used as an optimization, to skip OP_IsNull opcodes
78951** when we know that a value cannot be NULL.  Hence, a false positive
78952** (returning TRUE when in fact the expression can never be NULL) might
78953** be a small performance hit but is otherwise harmless.  On the other
78954** hand, a false negative (returning FALSE when the result could be NULL)
78955** will likely result in an incorrect answer.  So when in doubt, return
78956** TRUE.
78957*/
78958SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
78959  u8 op;
78960  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
78961  op = p->op;
78962  if( op==TK_REGISTER ) op = p->op2;
78963  switch( op ){
78964    case TK_INTEGER:
78965    case TK_STRING:
78966    case TK_FLOAT:
78967    case TK_BLOB:
78968      return 0;
78969    default:
78970      return 1;
78971  }
78972}
78973
78974/*
78975** Return TRUE if the given expression is a constant which would be
78976** unchanged by OP_Affinity with the affinity given in the second
78977** argument.
78978**
78979** This routine is used to determine if the OP_Affinity operation
78980** can be omitted.  When in doubt return FALSE.  A false negative
78981** is harmless.  A false positive, however, can result in the wrong
78982** answer.
78983*/
78984SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
78985  u8 op;
78986  if( aff==SQLITE_AFF_NONE ) return 1;
78987  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
78988  op = p->op;
78989  if( op==TK_REGISTER ) op = p->op2;
78990  switch( op ){
78991    case TK_INTEGER: {
78992      return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
78993    }
78994    case TK_FLOAT: {
78995      return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
78996    }
78997    case TK_STRING: {
78998      return aff==SQLITE_AFF_TEXT;
78999    }
79000    case TK_BLOB: {
79001      return 1;
79002    }
79003    case TK_COLUMN: {
79004      assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
79005      return p->iColumn<0
79006          && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
79007    }
79008    default: {
79009      return 0;
79010    }
79011  }
79012}
79013
79014/*
79015** Return TRUE if the given string is a row-id column name.
79016*/
79017SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
79018  if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
79019  if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
79020  if( sqlite3StrICmp(z, "OID")==0 ) return 1;
79021  return 0;
79022}
79023
79024/*
79025** Return true if we are able to the IN operator optimization on a
79026** query of the form
79027**
79028**       x IN (SELECT ...)
79029**
79030** Where the SELECT... clause is as specified by the parameter to this
79031** routine.
79032**
79033** The Select object passed in has already been preprocessed and no
79034** errors have been found.
79035*/
79036#ifndef SQLITE_OMIT_SUBQUERY
79037static int isCandidateForInOpt(Select *p){
79038  SrcList *pSrc;
79039  ExprList *pEList;
79040  Table *pTab;
79041  if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
79042  if( p->pPrior ) return 0;              /* Not a compound SELECT */
79043  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
79044    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
79045    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
79046    return 0; /* No DISTINCT keyword and no aggregate functions */
79047  }
79048  assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
79049  if( p->pLimit ) return 0;              /* Has no LIMIT clause */
79050  assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
79051  if( p->pWhere ) return 0;              /* Has no WHERE clause */
79052  pSrc = p->pSrc;
79053  assert( pSrc!=0 );
79054  if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
79055  if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
79056  pTab = pSrc->a[0].pTab;
79057  if( NEVER(pTab==0) ) return 0;
79058  assert( pTab->pSelect==0 );            /* FROM clause is not a view */
79059  if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
79060  pEList = p->pEList;
79061  if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
79062  if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
79063  return 1;
79064}
79065#endif /* SQLITE_OMIT_SUBQUERY */
79066
79067/*
79068** Code an OP_Once instruction and allocate space for its flag. Return the
79069** address of the new instruction.
79070*/
79071SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
79072  Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
79073  return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
79074}
79075
79076/*
79077** This function is used by the implementation of the IN (...) operator.
79078** The pX parameter is the expression on the RHS of the IN operator, which
79079** might be either a list of expressions or a subquery.
79080**
79081** The job of this routine is to find or create a b-tree object that can
79082** be used either to test for membership in the RHS set or to iterate through
79083** all members of the RHS set, skipping duplicates.
79084**
79085** A cursor is opened on the b-tree object that the RHS of the IN operator
79086** and pX->iTable is set to the index of that cursor.
79087**
79088** The returned value of this function indicates the b-tree type, as follows:
79089**
79090**   IN_INDEX_ROWID      - The cursor was opened on a database table.
79091**   IN_INDEX_INDEX_ASC  - The cursor was opened on an ascending index.
79092**   IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
79093**   IN_INDEX_EPH        - The cursor was opened on a specially created and
79094**                         populated epheremal table.
79095**
79096** An existing b-tree might be used if the RHS expression pX is a simple
79097** subquery such as:
79098**
79099**     SELECT <column> FROM <table>
79100**
79101** If the RHS of the IN operator is a list or a more complex subquery, then
79102** an ephemeral table might need to be generated from the RHS and then
79103** pX->iTable made to point to the ephermeral table instead of an
79104** existing table.
79105**
79106** If the prNotFound parameter is 0, then the b-tree will be used to iterate
79107** through the set members, skipping any duplicates. In this case an
79108** epheremal table must be used unless the selected <column> is guaranteed
79109** to be unique - either because it is an INTEGER PRIMARY KEY or it
79110** has a UNIQUE constraint or UNIQUE index.
79111**
79112** If the prNotFound parameter is not 0, then the b-tree will be used
79113** for fast set membership tests. In this case an epheremal table must
79114** be used unless <column> is an INTEGER PRIMARY KEY or an index can
79115** be found with <column> as its left-most column.
79116**
79117** When the b-tree is being used for membership tests, the calling function
79118** needs to know whether or not the structure contains an SQL NULL
79119** value in order to correctly evaluate expressions like "X IN (Y, Z)".
79120** If there is any chance that the (...) might contain a NULL value at
79121** runtime, then a register is allocated and the register number written
79122** to *prNotFound. If there is no chance that the (...) contains a
79123** NULL value, then *prNotFound is left unchanged.
79124**
79125** If a register is allocated and its location stored in *prNotFound, then
79126** its initial value is NULL.  If the (...) does not remain constant
79127** for the duration of the query (i.e. the SELECT within the (...)
79128** is a correlated subquery) then the value of the allocated register is
79129** reset to NULL each time the subquery is rerun. This allows the
79130** caller to use vdbe code equivalent to the following:
79131**
79132**   if( register==NULL ){
79133**     has_null = <test if data structure contains null>
79134**     register = 1
79135**   }
79136**
79137** in order to avoid running the <test if data structure contains null>
79138** test more often than is necessary.
79139*/
79140#ifndef SQLITE_OMIT_SUBQUERY
79141SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
79142  Select *p;                            /* SELECT to the right of IN operator */
79143  int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
79144  int iTab = pParse->nTab++;            /* Cursor of the RHS table */
79145  int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
79146  Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
79147
79148  assert( pX->op==TK_IN );
79149
79150  /* Check to see if an existing table or index can be used to
79151  ** satisfy the query.  This is preferable to generating a new
79152  ** ephemeral table.
79153  */
79154  p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
79155  if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
79156    sqlite3 *db = pParse->db;              /* Database connection */
79157    Table *pTab;                           /* Table <table>. */
79158    Expr *pExpr;                           /* Expression <column> */
79159    i16 iCol;                              /* Index of column <column> */
79160    i16 iDb;                               /* Database idx for pTab */
79161
79162    assert( p );                        /* Because of isCandidateForInOpt(p) */
79163    assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
79164    assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
79165    assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
79166    pTab = p->pSrc->a[0].pTab;
79167    pExpr = p->pEList->a[0].pExpr;
79168    iCol = (i16)pExpr->iColumn;
79169
79170    /* Code an OP_Transaction and OP_TableLock for <table>. */
79171    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
79172    sqlite3CodeVerifySchema(pParse, iDb);
79173    sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
79174
79175    /* This function is only called from two places. In both cases the vdbe
79176    ** has already been allocated. So assume sqlite3GetVdbe() is always
79177    ** successful here.
79178    */
79179    assert(v);
79180    if( iCol<0 ){
79181      int iAddr = sqlite3CodeOnce(pParse);
79182      VdbeCoverage(v);
79183
79184      sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
79185      eType = IN_INDEX_ROWID;
79186
79187      sqlite3VdbeJumpHere(v, iAddr);
79188    }else{
79189      Index *pIdx;                         /* Iterator variable */
79190
79191      /* The collation sequence used by the comparison. If an index is to
79192      ** be used in place of a temp-table, it must be ordered according
79193      ** to this collation sequence.  */
79194      CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
79195
79196      /* Check that the affinity that will be used to perform the
79197      ** comparison is the same as the affinity of the column. If
79198      ** it is not, it is not possible to use any index.
79199      */
79200      int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
79201
79202      for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
79203        if( (pIdx->aiColumn[0]==iCol)
79204         && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
79205         && (!mustBeUnique || (pIdx->nKeyCol==1 && pIdx->onError!=OE_None))
79206        ){
79207          int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
79208          sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
79209          sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
79210          VdbeComment((v, "%s", pIdx->zName));
79211          assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
79212          eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
79213
79214          if( prNotFound && !pTab->aCol[iCol].notNull ){
79215            *prNotFound = ++pParse->nMem;
79216            sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
79217          }
79218          sqlite3VdbeJumpHere(v, iAddr);
79219        }
79220      }
79221    }
79222  }
79223
79224  if( eType==0 ){
79225    /* Could not found an existing table or index to use as the RHS b-tree.
79226    ** We will have to generate an ephemeral table to do the job.
79227    */
79228    u32 savedNQueryLoop = pParse->nQueryLoop;
79229    int rMayHaveNull = 0;
79230    eType = IN_INDEX_EPH;
79231    if( prNotFound ){
79232      *prNotFound = rMayHaveNull = ++pParse->nMem;
79233      sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
79234    }else{
79235      pParse->nQueryLoop = 0;
79236      if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
79237        eType = IN_INDEX_ROWID;
79238      }
79239    }
79240    sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
79241    pParse->nQueryLoop = savedNQueryLoop;
79242  }else{
79243    pX->iTable = iTab;
79244  }
79245  return eType;
79246}
79247#endif
79248
79249/*
79250** Generate code for scalar subqueries used as a subquery expression, EXISTS,
79251** or IN operators.  Examples:
79252**
79253**     (SELECT a FROM b)          -- subquery
79254**     EXISTS (SELECT a FROM b)   -- EXISTS subquery
79255**     x IN (4,5,11)              -- IN operator with list on right-hand side
79256**     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
79257**
79258** The pExpr parameter describes the expression that contains the IN
79259** operator or subquery.
79260**
79261** If parameter isRowid is non-zero, then expression pExpr is guaranteed
79262** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
79263** to some integer key column of a table B-Tree. In this case, use an
79264** intkey B-Tree to store the set of IN(...) values instead of the usual
79265** (slower) variable length keys B-Tree.
79266**
79267** If rMayHaveNull is non-zero, that means that the operation is an IN
79268** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
79269** Furthermore, the IN is in a WHERE clause and that we really want
79270** to iterate over the RHS of the IN operator in order to quickly locate
79271** all corresponding LHS elements.  All this routine does is initialize
79272** the register given by rMayHaveNull to NULL.  Calling routines will take
79273** care of changing this register value to non-NULL if the RHS is NULL-free.
79274**
79275** If rMayHaveNull is zero, that means that the subquery is being used
79276** for membership testing only.  There is no need to initialize any
79277** registers to indicate the presence or absence of NULLs on the RHS.
79278**
79279** For a SELECT or EXISTS operator, return the register that holds the
79280** result.  For IN operators or if an error occurs, the return value is 0.
79281*/
79282#ifndef SQLITE_OMIT_SUBQUERY
79283SQLITE_PRIVATE int sqlite3CodeSubselect(
79284  Parse *pParse,          /* Parsing context */
79285  Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
79286  int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
79287  int isRowid             /* If true, LHS of IN operator is a rowid */
79288){
79289  int testAddr = -1;                      /* One-time test address */
79290  int rReg = 0;                           /* Register storing resulting */
79291  Vdbe *v = sqlite3GetVdbe(pParse);
79292  if( NEVER(v==0) ) return 0;
79293  sqlite3ExprCachePush(pParse);
79294
79295  /* This code must be run in its entirety every time it is encountered
79296  ** if any of the following is true:
79297  **
79298  **    *  The right-hand side is a correlated subquery
79299  **    *  The right-hand side is an expression list containing variables
79300  **    *  We are inside a trigger
79301  **
79302  ** If all of the above are false, then we can run this code just once
79303  ** save the results, and reuse the same result on subsequent invocations.
79304  */
79305  if( !ExprHasProperty(pExpr, EP_VarSelect) ){
79306    testAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
79307  }
79308
79309#ifndef SQLITE_OMIT_EXPLAIN
79310  if( pParse->explain==2 ){
79311    char *zMsg = sqlite3MPrintf(
79312        pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
79313        pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
79314    );
79315    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
79316  }
79317#endif
79318
79319  switch( pExpr->op ){
79320    case TK_IN: {
79321      char affinity;              /* Affinity of the LHS of the IN */
79322      int addr;                   /* Address of OP_OpenEphemeral instruction */
79323      Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
79324      KeyInfo *pKeyInfo = 0;      /* Key information */
79325
79326      if( rMayHaveNull ){
79327        sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
79328      }
79329
79330      affinity = sqlite3ExprAffinity(pLeft);
79331
79332      /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
79333      ** expression it is handled the same way.  An ephemeral table is
79334      ** filled with single-field index keys representing the results
79335      ** from the SELECT or the <exprlist>.
79336      **
79337      ** If the 'x' expression is a column value, or the SELECT...
79338      ** statement returns a column value, then the affinity of that
79339      ** column is used to build the index keys. If both 'x' and the
79340      ** SELECT... statement are columns, then numeric affinity is used
79341      ** if either column has NUMERIC or INTEGER affinity. If neither
79342      ** 'x' nor the SELECT... statement are columns, then numeric affinity
79343      ** is used.
79344      */
79345      pExpr->iTable = pParse->nTab++;
79346      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
79347      pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1, 1);
79348
79349      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
79350        /* Case 1:     expr IN (SELECT ...)
79351        **
79352        ** Generate code to write the results of the select into the temporary
79353        ** table allocated and opened above.
79354        */
79355        SelectDest dest;
79356        ExprList *pEList;
79357
79358        assert( !isRowid );
79359        sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
79360        dest.affSdst = (u8)affinity;
79361        assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
79362        pExpr->x.pSelect->iLimit = 0;
79363        testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
79364        if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
79365          sqlite3KeyInfoUnref(pKeyInfo);
79366          return 0;
79367        }
79368        pEList = pExpr->x.pSelect->pEList;
79369        assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
79370        assert( pEList!=0 );
79371        assert( pEList->nExpr>0 );
79372        assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
79373        pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
79374                                                         pEList->a[0].pExpr);
79375      }else if( ALWAYS(pExpr->x.pList!=0) ){
79376        /* Case 2:     expr IN (exprlist)
79377        **
79378        ** For each expression, build an index key from the evaluation and
79379        ** store it in the temporary table. If <expr> is a column, then use
79380        ** that columns affinity when building index keys. If <expr> is not
79381        ** a column, use numeric affinity.
79382        */
79383        int i;
79384        ExprList *pList = pExpr->x.pList;
79385        struct ExprList_item *pItem;
79386        int r1, r2, r3;
79387
79388        if( !affinity ){
79389          affinity = SQLITE_AFF_NONE;
79390        }
79391        if( pKeyInfo ){
79392          assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
79393          pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
79394        }
79395
79396        /* Loop through each expression in <exprlist>. */
79397        r1 = sqlite3GetTempReg(pParse);
79398        r2 = sqlite3GetTempReg(pParse);
79399        sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
79400        for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
79401          Expr *pE2 = pItem->pExpr;
79402          int iValToIns;
79403
79404          /* If the expression is not constant then we will need to
79405          ** disable the test that was generated above that makes sure
79406          ** this code only executes once.  Because for a non-constant
79407          ** expression we need to rerun this code each time.
79408          */
79409          if( testAddr>=0 && !sqlite3ExprIsConstant(pE2) ){
79410            sqlite3VdbeChangeToNoop(v, testAddr);
79411            testAddr = -1;
79412          }
79413
79414          /* Evaluate the expression and insert it into the temp table */
79415          if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
79416            sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
79417          }else{
79418            r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
79419            if( isRowid ){
79420              sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
79421                                sqlite3VdbeCurrentAddr(v)+2);
79422              VdbeCoverage(v);
79423              sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
79424            }else{
79425              sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
79426              sqlite3ExprCacheAffinityChange(pParse, r3, 1);
79427              sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
79428            }
79429          }
79430        }
79431        sqlite3ReleaseTempReg(pParse, r1);
79432        sqlite3ReleaseTempReg(pParse, r2);
79433      }
79434      if( pKeyInfo ){
79435        sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
79436      }
79437      break;
79438    }
79439
79440    case TK_EXISTS:
79441    case TK_SELECT:
79442    default: {
79443      /* If this has to be a scalar SELECT.  Generate code to put the
79444      ** value of this select in a memory cell and record the number
79445      ** of the memory cell in iColumn.  If this is an EXISTS, write
79446      ** an integer 0 (not exists) or 1 (exists) into a memory cell
79447      ** and record that memory cell in iColumn.
79448      */
79449      Select *pSel;                         /* SELECT statement to encode */
79450      SelectDest dest;                      /* How to deal with SELECt result */
79451
79452      testcase( pExpr->op==TK_EXISTS );
79453      testcase( pExpr->op==TK_SELECT );
79454      assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
79455
79456      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
79457      pSel = pExpr->x.pSelect;
79458      sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
79459      if( pExpr->op==TK_SELECT ){
79460        dest.eDest = SRT_Mem;
79461        sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
79462        VdbeComment((v, "Init subquery result"));
79463      }else{
79464        dest.eDest = SRT_Exists;
79465        sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
79466        VdbeComment((v, "Init EXISTS result"));
79467      }
79468      sqlite3ExprDelete(pParse->db, pSel->pLimit);
79469      pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
79470                                  &sqlite3IntTokens[1]);
79471      pSel->iLimit = 0;
79472      if( sqlite3Select(pParse, pSel, &dest) ){
79473        return 0;
79474      }
79475      rReg = dest.iSDParm;
79476      ExprSetVVAProperty(pExpr, EP_NoReduce);
79477      break;
79478    }
79479  }
79480
79481  if( testAddr>=0 ){
79482    sqlite3VdbeJumpHere(v, testAddr);
79483  }
79484  sqlite3ExprCachePop(pParse);
79485
79486  return rReg;
79487}
79488#endif /* SQLITE_OMIT_SUBQUERY */
79489
79490#ifndef SQLITE_OMIT_SUBQUERY
79491/*
79492** Generate code for an IN expression.
79493**
79494**      x IN (SELECT ...)
79495**      x IN (value, value, ...)
79496**
79497** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
79498** is an array of zero or more values.  The expression is true if the LHS is
79499** contained within the RHS.  The value of the expression is unknown (NULL)
79500** if the LHS is NULL or if the LHS is not contained within the RHS and the
79501** RHS contains one or more NULL values.
79502**
79503** This routine generates code will jump to destIfFalse if the LHS is not
79504** contained within the RHS.  If due to NULLs we cannot determine if the LHS
79505** is contained in the RHS then jump to destIfNull.  If the LHS is contained
79506** within the RHS then fall through.
79507*/
79508static void sqlite3ExprCodeIN(
79509  Parse *pParse,        /* Parsing and code generating context */
79510  Expr *pExpr,          /* The IN expression */
79511  int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
79512  int destIfNull        /* Jump here if the results are unknown due to NULLs */
79513){
79514  int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
79515  char affinity;        /* Comparison affinity to use */
79516  int eType;            /* Type of the RHS */
79517  int r1;               /* Temporary use register */
79518  Vdbe *v;              /* Statement under construction */
79519
79520  /* Compute the RHS.   After this step, the table with cursor
79521  ** pExpr->iTable will contains the values that make up the RHS.
79522  */
79523  v = pParse->pVdbe;
79524  assert( v!=0 );       /* OOM detected prior to this routine */
79525  VdbeNoopComment((v, "begin IN expr"));
79526  eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
79527
79528  /* Figure out the affinity to use to create a key from the results
79529  ** of the expression. affinityStr stores a static string suitable for
79530  ** P4 of OP_MakeRecord.
79531  */
79532  affinity = comparisonAffinity(pExpr);
79533
79534  /* Code the LHS, the <expr> from "<expr> IN (...)".
79535  */
79536  sqlite3ExprCachePush(pParse);
79537  r1 = sqlite3GetTempReg(pParse);
79538  sqlite3ExprCode(pParse, pExpr->pLeft, r1);
79539
79540  /* If the LHS is NULL, then the result is either false or NULL depending
79541  ** on whether the RHS is empty or not, respectively.
79542  */
79543  if( destIfNull==destIfFalse ){
79544    /* Shortcut for the common case where the false and NULL outcomes are
79545    ** the same. */
79546    sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull); VdbeCoverage(v);
79547  }else{
79548    int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
79549    sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
79550    VdbeCoverage(v);
79551    sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
79552    sqlite3VdbeJumpHere(v, addr1);
79553  }
79554
79555  if( eType==IN_INDEX_ROWID ){
79556    /* In this case, the RHS is the ROWID of table b-tree
79557    */
79558    sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse); VdbeCoverage(v);
79559    sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
79560    VdbeCoverage(v);
79561  }else{
79562    /* In this case, the RHS is an index b-tree.
79563    */
79564    sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
79565
79566    /* If the set membership test fails, then the result of the
79567    ** "x IN (...)" expression must be either 0 or NULL. If the set
79568    ** contains no NULL values, then the result is 0. If the set
79569    ** contains one or more NULL values, then the result of the
79570    ** expression is also NULL.
79571    */
79572    if( rRhsHasNull==0 || destIfFalse==destIfNull ){
79573      /* This branch runs if it is known at compile time that the RHS
79574      ** cannot contain NULL values. This happens as the result
79575      ** of a "NOT NULL" constraint in the database schema.
79576      **
79577      ** Also run this branch if NULL is equivalent to FALSE
79578      ** for this particular IN operator.
79579      */
79580      sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
79581      VdbeCoverage(v);
79582    }else{
79583      /* In this branch, the RHS of the IN might contain a NULL and
79584      ** the presence of a NULL on the RHS makes a difference in the
79585      ** outcome.
79586      */
79587      int j1, j2;
79588
79589      /* First check to see if the LHS is contained in the RHS.  If so,
79590      ** then the presence of NULLs in the RHS does not matter, so jump
79591      ** over all of the code that follows.
79592      */
79593      j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
79594      VdbeCoverage(v);
79595
79596      /* Here we begin generating code that runs if the LHS is not
79597      ** contained within the RHS.  Generate additional code that
79598      ** tests the RHS for NULLs.  If the RHS contains a NULL then
79599      ** jump to destIfNull.  If there are no NULLs in the RHS then
79600      ** jump to destIfFalse.
79601      */
79602      sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull); VdbeCoverage(v);
79603      sqlite3VdbeAddOp2(v, OP_IfNot, rRhsHasNull, destIfFalse); VdbeCoverage(v);
79604      j2 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
79605      VdbeCoverage(v);
79606      sqlite3VdbeAddOp2(v, OP_Integer, 0, rRhsHasNull);
79607      sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
79608      sqlite3VdbeJumpHere(v, j2);
79609      sqlite3VdbeAddOp2(v, OP_Integer, 1, rRhsHasNull);
79610      sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
79611
79612      /* The OP_Found at the top of this branch jumps here when true,
79613      ** causing the overall IN expression evaluation to fall through.
79614      */
79615      sqlite3VdbeJumpHere(v, j1);
79616    }
79617  }
79618  sqlite3ReleaseTempReg(pParse, r1);
79619  sqlite3ExprCachePop(pParse);
79620  VdbeComment((v, "end IN expr"));
79621}
79622#endif /* SQLITE_OMIT_SUBQUERY */
79623
79624/*
79625** Duplicate an 8-byte value
79626*/
79627static char *dup8bytes(Vdbe *v, const char *in){
79628  char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
79629  if( out ){
79630    memcpy(out, in, 8);
79631  }
79632  return out;
79633}
79634
79635#ifndef SQLITE_OMIT_FLOATING_POINT
79636/*
79637** Generate an instruction that will put the floating point
79638** value described by z[0..n-1] into register iMem.
79639**
79640** The z[] string will probably not be zero-terminated.  But the
79641** z[n] character is guaranteed to be something that does not look
79642** like the continuation of the number.
79643*/
79644static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
79645  if( ALWAYS(z!=0) ){
79646    double value;
79647    char *zV;
79648    sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
79649    assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
79650    if( negateFlag ) value = -value;
79651    zV = dup8bytes(v, (char*)&value);
79652    sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
79653  }
79654}
79655#endif
79656
79657
79658/*
79659** Generate an instruction that will put the integer describe by
79660** text z[0..n-1] into register iMem.
79661**
79662** Expr.u.zToken is always UTF8 and zero-terminated.
79663*/
79664static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
79665  Vdbe *v = pParse->pVdbe;
79666  if( pExpr->flags & EP_IntValue ){
79667    int i = pExpr->u.iValue;
79668    assert( i>=0 );
79669    if( negFlag ) i = -i;
79670    sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
79671  }else{
79672    int c;
79673    i64 value;
79674    const char *z = pExpr->u.zToken;
79675    assert( z!=0 );
79676    c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
79677    if( c==0 || (c==2 && negFlag) ){
79678      char *zV;
79679      if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
79680      zV = dup8bytes(v, (char*)&value);
79681      sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
79682    }else{
79683#ifdef SQLITE_OMIT_FLOATING_POINT
79684      sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
79685#else
79686      codeReal(v, z, negFlag, iMem);
79687#endif
79688    }
79689  }
79690}
79691
79692/*
79693** Clear a cache entry.
79694*/
79695static void cacheEntryClear(Parse *pParse, struct yColCache *p){
79696  if( p->tempReg ){
79697    if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
79698      pParse->aTempReg[pParse->nTempReg++] = p->iReg;
79699    }
79700    p->tempReg = 0;
79701  }
79702}
79703
79704
79705/*
79706** Record in the column cache that a particular column from a
79707** particular table is stored in a particular register.
79708*/
79709SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
79710  int i;
79711  int minLru;
79712  int idxLru;
79713  struct yColCache *p;
79714
79715  assert( iReg>0 );  /* Register numbers are always positive */
79716  assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
79717
79718  /* The SQLITE_ColumnCache flag disables the column cache.  This is used
79719  ** for testing only - to verify that SQLite always gets the same answer
79720  ** with and without the column cache.
79721  */
79722  if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
79723
79724  /* First replace any existing entry.
79725  **
79726  ** Actually, the way the column cache is currently used, we are guaranteed
79727  ** that the object will never already be in cache.  Verify this guarantee.
79728  */
79729#ifndef NDEBUG
79730  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
79731    assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
79732  }
79733#endif
79734
79735  /* Find an empty slot and replace it */
79736  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
79737    if( p->iReg==0 ){
79738      p->iLevel = pParse->iCacheLevel;
79739      p->iTable = iTab;
79740      p->iColumn = iCol;
79741      p->iReg = iReg;
79742      p->tempReg = 0;
79743      p->lru = pParse->iCacheCnt++;
79744      return;
79745    }
79746  }
79747
79748  /* Replace the last recently used */
79749  minLru = 0x7fffffff;
79750  idxLru = -1;
79751  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
79752    if( p->lru<minLru ){
79753      idxLru = i;
79754      minLru = p->lru;
79755    }
79756  }
79757  if( ALWAYS(idxLru>=0) ){
79758    p = &pParse->aColCache[idxLru];
79759    p->iLevel = pParse->iCacheLevel;
79760    p->iTable = iTab;
79761    p->iColumn = iCol;
79762    p->iReg = iReg;
79763    p->tempReg = 0;
79764    p->lru = pParse->iCacheCnt++;
79765    return;
79766  }
79767}
79768
79769/*
79770** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
79771** Purge the range of registers from the column cache.
79772*/
79773SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
79774  int i;
79775  int iLast = iReg + nReg - 1;
79776  struct yColCache *p;
79777  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
79778    int r = p->iReg;
79779    if( r>=iReg && r<=iLast ){
79780      cacheEntryClear(pParse, p);
79781      p->iReg = 0;
79782    }
79783  }
79784}
79785
79786/*
79787** Remember the current column cache context.  Any new entries added
79788** added to the column cache after this call are removed when the
79789** corresponding pop occurs.
79790*/
79791SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
79792  pParse->iCacheLevel++;
79793#ifdef SQLITE_DEBUG
79794  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
79795    printf("PUSH to %d\n", pParse->iCacheLevel);
79796  }
79797#endif
79798}
79799
79800/*
79801** Remove from the column cache any entries that were added since the
79802** the previous sqlite3ExprCachePush operation.  In other words, restore
79803** the cache to the state it was in prior the most recent Push.
79804*/
79805SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){
79806  int i;
79807  struct yColCache *p;
79808  assert( pParse->iCacheLevel>=1 );
79809  pParse->iCacheLevel--;
79810#ifdef SQLITE_DEBUG
79811  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
79812    printf("POP  to %d\n", pParse->iCacheLevel);
79813  }
79814#endif
79815  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
79816    if( p->iReg && p->iLevel>pParse->iCacheLevel ){
79817      cacheEntryClear(pParse, p);
79818      p->iReg = 0;
79819    }
79820  }
79821}
79822
79823/*
79824** When a cached column is reused, make sure that its register is
79825** no longer available as a temp register.  ticket #3879:  that same
79826** register might be in the cache in multiple places, so be sure to
79827** get them all.
79828*/
79829static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
79830  int i;
79831  struct yColCache *p;
79832  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
79833    if( p->iReg==iReg ){
79834      p->tempReg = 0;
79835    }
79836  }
79837}
79838
79839/*
79840** Generate code to extract the value of the iCol-th column of a table.
79841*/
79842SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
79843  Vdbe *v,        /* The VDBE under construction */
79844  Table *pTab,    /* The table containing the value */
79845  int iTabCur,    /* The table cursor.  Or the PK cursor for WITHOUT ROWID */
79846  int iCol,       /* Index of the column to extract */
79847  int regOut      /* Extract the value into this register */
79848){
79849  if( iCol<0 || iCol==pTab->iPKey ){
79850    sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
79851  }else{
79852    int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
79853    int x = iCol;
79854    if( !HasRowid(pTab) ){
79855      x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
79856    }
79857    sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
79858  }
79859  if( iCol>=0 ){
79860    sqlite3ColumnDefault(v, pTab, iCol, regOut);
79861  }
79862}
79863
79864/*
79865** Generate code that will extract the iColumn-th column from
79866** table pTab and store the column value in a register.  An effort
79867** is made to store the column value in register iReg, but this is
79868** not guaranteed.  The location of the column value is returned.
79869**
79870** There must be an open cursor to pTab in iTable when this routine
79871** is called.  If iColumn<0 then code is generated that extracts the rowid.
79872*/
79873SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
79874  Parse *pParse,   /* Parsing and code generating context */
79875  Table *pTab,     /* Description of the table we are reading from */
79876  int iColumn,     /* Index of the table column */
79877  int iTable,      /* The cursor pointing to the table */
79878  int iReg,        /* Store results here */
79879  u8 p5            /* P5 value for OP_Column */
79880){
79881  Vdbe *v = pParse->pVdbe;
79882  int i;
79883  struct yColCache *p;
79884
79885  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
79886    if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
79887      p->lru = pParse->iCacheCnt++;
79888      sqlite3ExprCachePinRegister(pParse, p->iReg);
79889      return p->iReg;
79890    }
79891  }
79892  assert( v!=0 );
79893  sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
79894  if( p5 ){
79895    sqlite3VdbeChangeP5(v, p5);
79896  }else{
79897    sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
79898  }
79899  return iReg;
79900}
79901
79902/*
79903** Clear all column cache entries.
79904*/
79905SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
79906  int i;
79907  struct yColCache *p;
79908
79909#if SQLITE_DEBUG
79910  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
79911    printf("CLEAR\n");
79912  }
79913#endif
79914  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
79915    if( p->iReg ){
79916      cacheEntryClear(pParse, p);
79917      p->iReg = 0;
79918    }
79919  }
79920}
79921
79922/*
79923** Record the fact that an affinity change has occurred on iCount
79924** registers starting with iStart.
79925*/
79926SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
79927  sqlite3ExprCacheRemove(pParse, iStart, iCount);
79928}
79929
79930/*
79931** Generate code to move content from registers iFrom...iFrom+nReg-1
79932** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
79933*/
79934SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
79935  int i;
79936  struct yColCache *p;
79937  assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
79938  sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
79939  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
79940    int x = p->iReg;
79941    if( x>=iFrom && x<iFrom+nReg ){
79942      p->iReg += iTo-iFrom;
79943    }
79944  }
79945}
79946
79947#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
79948/*
79949** Return true if any register in the range iFrom..iTo (inclusive)
79950** is used as part of the column cache.
79951**
79952** This routine is used within assert() and testcase() macros only
79953** and does not appear in a normal build.
79954*/
79955static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
79956  int i;
79957  struct yColCache *p;
79958  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
79959    int r = p->iReg;
79960    if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
79961  }
79962  return 0;
79963}
79964#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
79965
79966/*
79967** Convert an expression node to a TK_REGISTER
79968*/
79969static void exprToRegister(Expr *p, int iReg){
79970  p->op2 = p->op;
79971  p->op = TK_REGISTER;
79972  p->iTable = iReg;
79973  ExprClearProperty(p, EP_Skip);
79974}
79975
79976/*
79977** Generate code into the current Vdbe to evaluate the given
79978** expression.  Attempt to store the results in register "target".
79979** Return the register where results are stored.
79980**
79981** With this routine, there is no guarantee that results will
79982** be stored in target.  The result might be stored in some other
79983** register if it is convenient to do so.  The calling function
79984** must check the return code and move the results to the desired
79985** register.
79986*/
79987SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
79988  Vdbe *v = pParse->pVdbe;  /* The VM under construction */
79989  int op;                   /* The opcode being coded */
79990  int inReg = target;       /* Results stored in register inReg */
79991  int regFree1 = 0;         /* If non-zero free this temporary register */
79992  int regFree2 = 0;         /* If non-zero free this temporary register */
79993  int r1, r2, r3, r4;       /* Various register numbers */
79994  sqlite3 *db = pParse->db; /* The database connection */
79995  Expr tempX;               /* Temporary expression node */
79996
79997  assert( target>0 && target<=pParse->nMem );
79998  if( v==0 ){
79999    assert( pParse->db->mallocFailed );
80000    return 0;
80001  }
80002
80003  if( pExpr==0 ){
80004    op = TK_NULL;
80005  }else{
80006    op = pExpr->op;
80007  }
80008  switch( op ){
80009    case TK_AGG_COLUMN: {
80010      AggInfo *pAggInfo = pExpr->pAggInfo;
80011      struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
80012      if( !pAggInfo->directMode ){
80013        assert( pCol->iMem>0 );
80014        inReg = pCol->iMem;
80015        break;
80016      }else if( pAggInfo->useSortingIdx ){
80017        sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
80018                              pCol->iSorterColumn, target);
80019        break;
80020      }
80021      /* Otherwise, fall thru into the TK_COLUMN case */
80022    }
80023    case TK_COLUMN: {
80024      int iTab = pExpr->iTable;
80025      if( iTab<0 ){
80026        if( pParse->ckBase>0 ){
80027          /* Generating CHECK constraints or inserting into partial index */
80028          inReg = pExpr->iColumn + pParse->ckBase;
80029          break;
80030        }else{
80031          /* Deleting from a partial index */
80032          iTab = pParse->iPartIdxTab;
80033        }
80034      }
80035      inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
80036                               pExpr->iColumn, iTab, target,
80037                               pExpr->op2);
80038      break;
80039    }
80040    case TK_INTEGER: {
80041      codeInteger(pParse, pExpr, 0, target);
80042      break;
80043    }
80044#ifndef SQLITE_OMIT_FLOATING_POINT
80045    case TK_FLOAT: {
80046      assert( !ExprHasProperty(pExpr, EP_IntValue) );
80047      codeReal(v, pExpr->u.zToken, 0, target);
80048      break;
80049    }
80050#endif
80051    case TK_STRING: {
80052      assert( !ExprHasProperty(pExpr, EP_IntValue) );
80053      sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
80054      break;
80055    }
80056    case TK_NULL: {
80057      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
80058      break;
80059    }
80060#ifndef SQLITE_OMIT_BLOB_LITERAL
80061    case TK_BLOB: {
80062      int n;
80063      const char *z;
80064      char *zBlob;
80065      assert( !ExprHasProperty(pExpr, EP_IntValue) );
80066      assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
80067      assert( pExpr->u.zToken[1]=='\'' );
80068      z = &pExpr->u.zToken[2];
80069      n = sqlite3Strlen30(z) - 1;
80070      assert( z[n]=='\'' );
80071      zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
80072      sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
80073      break;
80074    }
80075#endif
80076    case TK_VARIABLE: {
80077      assert( !ExprHasProperty(pExpr, EP_IntValue) );
80078      assert( pExpr->u.zToken!=0 );
80079      assert( pExpr->u.zToken[0]!=0 );
80080      sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
80081      if( pExpr->u.zToken[1]!=0 ){
80082        assert( pExpr->u.zToken[0]=='?'
80083             || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
80084        sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
80085      }
80086      break;
80087    }
80088    case TK_REGISTER: {
80089      inReg = pExpr->iTable;
80090      break;
80091    }
80092    case TK_AS: {
80093      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
80094      break;
80095    }
80096#ifndef SQLITE_OMIT_CAST
80097    case TK_CAST: {
80098      /* Expressions of the form:   CAST(pLeft AS token) */
80099      int aff, to_op;
80100      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
80101      assert( !ExprHasProperty(pExpr, EP_IntValue) );
80102      aff = sqlite3AffinityType(pExpr->u.zToken, 0);
80103      to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
80104      assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
80105      assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
80106      assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
80107      assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
80108      assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
80109      testcase( to_op==OP_ToText );
80110      testcase( to_op==OP_ToBlob );
80111      testcase( to_op==OP_ToNumeric );
80112      testcase( to_op==OP_ToInt );
80113      testcase( to_op==OP_ToReal );
80114      if( inReg!=target ){
80115        sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
80116        inReg = target;
80117      }
80118      sqlite3VdbeAddOp1(v, to_op, inReg);
80119      testcase( usedAsColumnCache(pParse, inReg, inReg) );
80120      sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
80121      break;
80122    }
80123#endif /* SQLITE_OMIT_CAST */
80124    case TK_LT:
80125    case TK_LE:
80126    case TK_GT:
80127    case TK_GE:
80128    case TK_NE:
80129    case TK_EQ: {
80130      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
80131      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
80132      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
80133                  r1, r2, inReg, SQLITE_STOREP2);
80134      assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
80135      assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
80136      assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
80137      assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
80138      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
80139      assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
80140      testcase( regFree1==0 );
80141      testcase( regFree2==0 );
80142      break;
80143    }
80144    case TK_IS:
80145    case TK_ISNOT: {
80146      testcase( op==TK_IS );
80147      testcase( op==TK_ISNOT );
80148      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
80149      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
80150      op = (op==TK_IS) ? TK_EQ : TK_NE;
80151      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
80152                  r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
80153      VdbeCoverageIf(v, op==TK_EQ);
80154      VdbeCoverageIf(v, op==TK_NE);
80155      testcase( regFree1==0 );
80156      testcase( regFree2==0 );
80157      break;
80158    }
80159    case TK_AND:
80160    case TK_OR:
80161    case TK_PLUS:
80162    case TK_STAR:
80163    case TK_MINUS:
80164    case TK_REM:
80165    case TK_BITAND:
80166    case TK_BITOR:
80167    case TK_SLASH:
80168    case TK_LSHIFT:
80169    case TK_RSHIFT:
80170    case TK_CONCAT: {
80171      assert( TK_AND==OP_And );            testcase( op==TK_AND );
80172      assert( TK_OR==OP_Or );              testcase( op==TK_OR );
80173      assert( TK_PLUS==OP_Add );           testcase( op==TK_PLUS );
80174      assert( TK_MINUS==OP_Subtract );     testcase( op==TK_MINUS );
80175      assert( TK_REM==OP_Remainder );      testcase( op==TK_REM );
80176      assert( TK_BITAND==OP_BitAnd );      testcase( op==TK_BITAND );
80177      assert( TK_BITOR==OP_BitOr );        testcase( op==TK_BITOR );
80178      assert( TK_SLASH==OP_Divide );       testcase( op==TK_SLASH );
80179      assert( TK_LSHIFT==OP_ShiftLeft );   testcase( op==TK_LSHIFT );
80180      assert( TK_RSHIFT==OP_ShiftRight );  testcase( op==TK_RSHIFT );
80181      assert( TK_CONCAT==OP_Concat );      testcase( op==TK_CONCAT );
80182      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
80183      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
80184      sqlite3VdbeAddOp3(v, op, r2, r1, target);
80185      testcase( regFree1==0 );
80186      testcase( regFree2==0 );
80187      break;
80188    }
80189    case TK_UMINUS: {
80190      Expr *pLeft = pExpr->pLeft;
80191      assert( pLeft );
80192      if( pLeft->op==TK_INTEGER ){
80193        codeInteger(pParse, pLeft, 1, target);
80194#ifndef SQLITE_OMIT_FLOATING_POINT
80195      }else if( pLeft->op==TK_FLOAT ){
80196        assert( !ExprHasProperty(pExpr, EP_IntValue) );
80197        codeReal(v, pLeft->u.zToken, 1, target);
80198#endif
80199      }else{
80200        tempX.op = TK_INTEGER;
80201        tempX.flags = EP_IntValue|EP_TokenOnly;
80202        tempX.u.iValue = 0;
80203        r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
80204        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
80205        sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
80206        testcase( regFree2==0 );
80207      }
80208      inReg = target;
80209      break;
80210    }
80211    case TK_BITNOT:
80212    case TK_NOT: {
80213      assert( TK_BITNOT==OP_BitNot );   testcase( op==TK_BITNOT );
80214      assert( TK_NOT==OP_Not );         testcase( op==TK_NOT );
80215      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
80216      testcase( regFree1==0 );
80217      inReg = target;
80218      sqlite3VdbeAddOp2(v, op, r1, inReg);
80219      break;
80220    }
80221    case TK_ISNULL:
80222    case TK_NOTNULL: {
80223      int addr;
80224      assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
80225      assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
80226      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
80227      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
80228      testcase( regFree1==0 );
80229      addr = sqlite3VdbeAddOp1(v, op, r1);
80230      VdbeCoverageIf(v, op==TK_ISNULL);
80231      VdbeCoverageIf(v, op==TK_NOTNULL);
80232      sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
80233      sqlite3VdbeJumpHere(v, addr);
80234      break;
80235    }
80236    case TK_AGG_FUNCTION: {
80237      AggInfo *pInfo = pExpr->pAggInfo;
80238      if( pInfo==0 ){
80239        assert( !ExprHasProperty(pExpr, EP_IntValue) );
80240        sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
80241      }else{
80242        inReg = pInfo->aFunc[pExpr->iAgg].iMem;
80243      }
80244      break;
80245    }
80246    case TK_FUNCTION: {
80247      ExprList *pFarg;       /* List of function arguments */
80248      int nFarg;             /* Number of function arguments */
80249      FuncDef *pDef;         /* The function definition object */
80250      int nId;               /* Length of the function name in bytes */
80251      const char *zId;       /* The function name */
80252      u32 constMask = 0;     /* Mask of function arguments that are constant */
80253      int i;                 /* Loop counter */
80254      u8 enc = ENC(db);      /* The text encoding used by this database */
80255      CollSeq *pColl = 0;    /* A collating sequence */
80256
80257      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
80258      if( ExprHasProperty(pExpr, EP_TokenOnly) ){
80259        pFarg = 0;
80260      }else{
80261        pFarg = pExpr->x.pList;
80262      }
80263      nFarg = pFarg ? pFarg->nExpr : 0;
80264      assert( !ExprHasProperty(pExpr, EP_IntValue) );
80265      zId = pExpr->u.zToken;
80266      nId = sqlite3Strlen30(zId);
80267      pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
80268      if( pDef==0 ){
80269        sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
80270        break;
80271      }
80272
80273      /* Attempt a direct implementation of the built-in COALESCE() and
80274      ** IFNULL() functions.  This avoids unnecessary evalation of
80275      ** arguments past the first non-NULL argument.
80276      */
80277      if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
80278        int endCoalesce = sqlite3VdbeMakeLabel(v);
80279        assert( nFarg>=2 );
80280        sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
80281        for(i=1; i<nFarg; i++){
80282          sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
80283          VdbeCoverage(v);
80284          sqlite3ExprCacheRemove(pParse, target, 1);
80285          sqlite3ExprCachePush(pParse);
80286          sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
80287          sqlite3ExprCachePop(pParse);
80288        }
80289        sqlite3VdbeResolveLabel(v, endCoalesce);
80290        break;
80291      }
80292
80293      /* The UNLIKELY() function is a no-op.  The result is the value
80294      ** of the first argument.
80295      */
80296      if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
80297        assert( nFarg>=1 );
80298        sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
80299        break;
80300      }
80301
80302      for(i=0; i<nFarg; i++){
80303        if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
80304          testcase( i==31 );
80305          constMask |= MASKBIT32(i);
80306        }
80307        if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
80308          pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
80309        }
80310      }
80311      if( pFarg ){
80312        if( constMask ){
80313          r1 = pParse->nMem+1;
80314          pParse->nMem += nFarg;
80315        }else{
80316          r1 = sqlite3GetTempRange(pParse, nFarg);
80317        }
80318
80319        /* For length() and typeof() functions with a column argument,
80320        ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
80321        ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
80322        ** loading.
80323        */
80324        if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
80325          u8 exprOp;
80326          assert( nFarg==1 );
80327          assert( pFarg->a[0].pExpr!=0 );
80328          exprOp = pFarg->a[0].pExpr->op;
80329          if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
80330            assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
80331            assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
80332            testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
80333            pFarg->a[0].pExpr->op2 =
80334                  pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
80335          }
80336        }
80337
80338        sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
80339        sqlite3ExprCodeExprList(pParse, pFarg, r1,
80340                                SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
80341        sqlite3ExprCachePop(pParse);      /* Ticket 2ea2425d34be */
80342      }else{
80343        r1 = 0;
80344      }
80345#ifndef SQLITE_OMIT_VIRTUALTABLE
80346      /* Possibly overload the function if the first argument is
80347      ** a virtual table column.
80348      **
80349      ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
80350      ** second argument, not the first, as the argument to test to
80351      ** see if it is a column in a virtual table.  This is done because
80352      ** the left operand of infix functions (the operand we want to
80353      ** control overloading) ends up as the second argument to the
80354      ** function.  The expression "A glob B" is equivalent to
80355      ** "glob(B,A).  We want to use the A in "A glob B" to test
80356      ** for function overloading.  But we use the B term in "glob(B,A)".
80357      */
80358      if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
80359        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
80360      }else if( nFarg>0 ){
80361        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
80362      }
80363#endif
80364      if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
80365        if( !pColl ) pColl = db->pDfltColl;
80366        sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
80367      }
80368      sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
80369                        (char*)pDef, P4_FUNCDEF);
80370      sqlite3VdbeChangeP5(v, (u8)nFarg);
80371      if( nFarg && constMask==0 ){
80372        sqlite3ReleaseTempRange(pParse, r1, nFarg);
80373      }
80374      break;
80375    }
80376#ifndef SQLITE_OMIT_SUBQUERY
80377    case TK_EXISTS:
80378    case TK_SELECT: {
80379      testcase( op==TK_EXISTS );
80380      testcase( op==TK_SELECT );
80381      inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
80382      break;
80383    }
80384    case TK_IN: {
80385      int destIfFalse = sqlite3VdbeMakeLabel(v);
80386      int destIfNull = sqlite3VdbeMakeLabel(v);
80387      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
80388      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
80389      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
80390      sqlite3VdbeResolveLabel(v, destIfFalse);
80391      sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
80392      sqlite3VdbeResolveLabel(v, destIfNull);
80393      break;
80394    }
80395#endif /* SQLITE_OMIT_SUBQUERY */
80396
80397
80398    /*
80399    **    x BETWEEN y AND z
80400    **
80401    ** This is equivalent to
80402    **
80403    **    x>=y AND x<=z
80404    **
80405    ** X is stored in pExpr->pLeft.
80406    ** Y is stored in pExpr->pList->a[0].pExpr.
80407    ** Z is stored in pExpr->pList->a[1].pExpr.
80408    */
80409    case TK_BETWEEN: {
80410      Expr *pLeft = pExpr->pLeft;
80411      struct ExprList_item *pLItem = pExpr->x.pList->a;
80412      Expr *pRight = pLItem->pExpr;
80413
80414      r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
80415      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
80416      testcase( regFree1==0 );
80417      testcase( regFree2==0 );
80418      r3 = sqlite3GetTempReg(pParse);
80419      r4 = sqlite3GetTempReg(pParse);
80420      codeCompare(pParse, pLeft, pRight, OP_Ge,
80421                  r1, r2, r3, SQLITE_STOREP2);  VdbeCoverage(v);
80422      pLItem++;
80423      pRight = pLItem->pExpr;
80424      sqlite3ReleaseTempReg(pParse, regFree2);
80425      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
80426      testcase( regFree2==0 );
80427      codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
80428      VdbeCoverage(v);
80429      sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
80430      sqlite3ReleaseTempReg(pParse, r3);
80431      sqlite3ReleaseTempReg(pParse, r4);
80432      break;
80433    }
80434    case TK_COLLATE:
80435    case TK_UPLUS: {
80436      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
80437      break;
80438    }
80439
80440    case TK_TRIGGER: {
80441      /* If the opcode is TK_TRIGGER, then the expression is a reference
80442      ** to a column in the new.* or old.* pseudo-tables available to
80443      ** trigger programs. In this case Expr.iTable is set to 1 for the
80444      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
80445      ** is set to the column of the pseudo-table to read, or to -1 to
80446      ** read the rowid field.
80447      **
80448      ** The expression is implemented using an OP_Param opcode. The p1
80449      ** parameter is set to 0 for an old.rowid reference, or to (i+1)
80450      ** to reference another column of the old.* pseudo-table, where
80451      ** i is the index of the column. For a new.rowid reference, p1 is
80452      ** set to (n+1), where n is the number of columns in each pseudo-table.
80453      ** For a reference to any other column in the new.* pseudo-table, p1
80454      ** is set to (n+2+i), where n and i are as defined previously. For
80455      ** example, if the table on which triggers are being fired is
80456      ** declared as:
80457      **
80458      **   CREATE TABLE t1(a, b);
80459      **
80460      ** Then p1 is interpreted as follows:
80461      **
80462      **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
80463      **   p1==1   ->    old.a         p1==4   ->    new.a
80464      **   p1==2   ->    old.b         p1==5   ->    new.b
80465      */
80466      Table *pTab = pExpr->pTab;
80467      int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
80468
80469      assert( pExpr->iTable==0 || pExpr->iTable==1 );
80470      assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
80471      assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
80472      assert( p1>=0 && p1<(pTab->nCol*2+2) );
80473
80474      sqlite3VdbeAddOp2(v, OP_Param, p1, target);
80475      VdbeComment((v, "%s.%s -> $%d",
80476        (pExpr->iTable ? "new" : "old"),
80477        (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
80478        target
80479      ));
80480
80481#ifndef SQLITE_OMIT_FLOATING_POINT
80482      /* If the column has REAL affinity, it may currently be stored as an
80483      ** integer. Use OP_RealAffinity to make sure it is really real.  */
80484      if( pExpr->iColumn>=0
80485       && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
80486      ){
80487        sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
80488      }
80489#endif
80490      break;
80491    }
80492
80493
80494    /*
80495    ** Form A:
80496    **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
80497    **
80498    ** Form B:
80499    **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
80500    **
80501    ** Form A is can be transformed into the equivalent form B as follows:
80502    **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
80503    **        WHEN x=eN THEN rN ELSE y END
80504    **
80505    ** X (if it exists) is in pExpr->pLeft.
80506    ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
80507    ** odd.  The Y is also optional.  If the number of elements in x.pList
80508    ** is even, then Y is omitted and the "otherwise" result is NULL.
80509    ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
80510    **
80511    ** The result of the expression is the Ri for the first matching Ei,
80512    ** or if there is no matching Ei, the ELSE term Y, or if there is
80513    ** no ELSE term, NULL.
80514    */
80515    default: assert( op==TK_CASE ); {
80516      int endLabel;                     /* GOTO label for end of CASE stmt */
80517      int nextCase;                     /* GOTO label for next WHEN clause */
80518      int nExpr;                        /* 2x number of WHEN terms */
80519      int i;                            /* Loop counter */
80520      ExprList *pEList;                 /* List of WHEN terms */
80521      struct ExprList_item *aListelem;  /* Array of WHEN terms */
80522      Expr opCompare;                   /* The X==Ei expression */
80523      Expr *pX;                         /* The X expression */
80524      Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
80525      VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
80526
80527      assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
80528      assert(pExpr->x.pList->nExpr > 0);
80529      pEList = pExpr->x.pList;
80530      aListelem = pEList->a;
80531      nExpr = pEList->nExpr;
80532      endLabel = sqlite3VdbeMakeLabel(v);
80533      if( (pX = pExpr->pLeft)!=0 ){
80534        tempX = *pX;
80535        testcase( pX->op==TK_COLUMN );
80536        exprToRegister(&tempX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
80537        testcase( regFree1==0 );
80538        opCompare.op = TK_EQ;
80539        opCompare.pLeft = &tempX;
80540        pTest = &opCompare;
80541        /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
80542        ** The value in regFree1 might get SCopy-ed into the file result.
80543        ** So make sure that the regFree1 register is not reused for other
80544        ** purposes and possibly overwritten.  */
80545        regFree1 = 0;
80546      }
80547      for(i=0; i<nExpr-1; i=i+2){
80548        sqlite3ExprCachePush(pParse);
80549        if( pX ){
80550          assert( pTest!=0 );
80551          opCompare.pRight = aListelem[i].pExpr;
80552        }else{
80553          pTest = aListelem[i].pExpr;
80554        }
80555        nextCase = sqlite3VdbeMakeLabel(v);
80556        testcase( pTest->op==TK_COLUMN );
80557        sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
80558        testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
80559        sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
80560        sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
80561        sqlite3ExprCachePop(pParse);
80562        sqlite3VdbeResolveLabel(v, nextCase);
80563      }
80564      if( (nExpr&1)!=0 ){
80565        sqlite3ExprCachePush(pParse);
80566        sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
80567        sqlite3ExprCachePop(pParse);
80568      }else{
80569        sqlite3VdbeAddOp2(v, OP_Null, 0, target);
80570      }
80571      assert( db->mallocFailed || pParse->nErr>0
80572           || pParse->iCacheLevel==iCacheLevel );
80573      sqlite3VdbeResolveLabel(v, endLabel);
80574      break;
80575    }
80576#ifndef SQLITE_OMIT_TRIGGER
80577    case TK_RAISE: {
80578      assert( pExpr->affinity==OE_Rollback
80579           || pExpr->affinity==OE_Abort
80580           || pExpr->affinity==OE_Fail
80581           || pExpr->affinity==OE_Ignore
80582      );
80583      if( !pParse->pTriggerTab ){
80584        sqlite3ErrorMsg(pParse,
80585                       "RAISE() may only be used within a trigger-program");
80586        return 0;
80587      }
80588      if( pExpr->affinity==OE_Abort ){
80589        sqlite3MayAbort(pParse);
80590      }
80591      assert( !ExprHasProperty(pExpr, EP_IntValue) );
80592      if( pExpr->affinity==OE_Ignore ){
80593        sqlite3VdbeAddOp4(
80594            v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
80595        VdbeCoverage(v);
80596      }else{
80597        sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
80598                              pExpr->affinity, pExpr->u.zToken, 0, 0);
80599      }
80600
80601      break;
80602    }
80603#endif
80604  }
80605  sqlite3ReleaseTempReg(pParse, regFree1);
80606  sqlite3ReleaseTempReg(pParse, regFree2);
80607  return inReg;
80608}
80609
80610/*
80611** Factor out the code of the given expression to initialization time.
80612*/
80613SQLITE_PRIVATE void sqlite3ExprCodeAtInit(
80614  Parse *pParse,    /* Parsing context */
80615  Expr *pExpr,      /* The expression to code when the VDBE initializes */
80616  int regDest,      /* Store the value in this register */
80617  u8 reusable       /* True if this expression is reusable */
80618){
80619  ExprList *p;
80620  assert( ConstFactorOk(pParse) );
80621  p = pParse->pConstExpr;
80622  pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
80623  p = sqlite3ExprListAppend(pParse, p, pExpr);
80624  if( p ){
80625     struct ExprList_item *pItem = &p->a[p->nExpr-1];
80626     pItem->u.iConstExprReg = regDest;
80627     pItem->reusable = reusable;
80628  }
80629  pParse->pConstExpr = p;
80630}
80631
80632/*
80633** Generate code to evaluate an expression and store the results
80634** into a register.  Return the register number where the results
80635** are stored.
80636**
80637** If the register is a temporary register that can be deallocated,
80638** then write its number into *pReg.  If the result register is not
80639** a temporary, then set *pReg to zero.
80640**
80641** If pExpr is a constant, then this routine might generate this
80642** code to fill the register in the initialization section of the
80643** VDBE program, in order to factor it out of the evaluation loop.
80644*/
80645SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
80646  int r2;
80647  pExpr = sqlite3ExprSkipCollate(pExpr);
80648  if( ConstFactorOk(pParse)
80649   && pExpr->op!=TK_REGISTER
80650   && sqlite3ExprIsConstantNotJoin(pExpr)
80651  ){
80652    ExprList *p = pParse->pConstExpr;
80653    int i;
80654    *pReg  = 0;
80655    if( p ){
80656      struct ExprList_item *pItem;
80657      for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
80658        if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
80659          return pItem->u.iConstExprReg;
80660        }
80661      }
80662    }
80663    r2 = ++pParse->nMem;
80664    sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
80665  }else{
80666    int r1 = sqlite3GetTempReg(pParse);
80667    r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
80668    if( r2==r1 ){
80669      *pReg = r1;
80670    }else{
80671      sqlite3ReleaseTempReg(pParse, r1);
80672      *pReg = 0;
80673    }
80674  }
80675  return r2;
80676}
80677
80678/*
80679** Generate code that will evaluate expression pExpr and store the
80680** results in register target.  The results are guaranteed to appear
80681** in register target.
80682*/
80683SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
80684  int inReg;
80685
80686  assert( target>0 && target<=pParse->nMem );
80687  if( pExpr && pExpr->op==TK_REGISTER ){
80688    sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
80689  }else{
80690    inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
80691    assert( pParse->pVdbe || pParse->db->mallocFailed );
80692    if( inReg!=target && pParse->pVdbe ){
80693      sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
80694    }
80695  }
80696}
80697
80698/*
80699** Generate code that will evaluate expression pExpr and store the
80700** results in register target.  The results are guaranteed to appear
80701** in register target.  If the expression is constant, then this routine
80702** might choose to code the expression at initialization time.
80703*/
80704SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
80705  if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
80706    sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
80707  }else{
80708    sqlite3ExprCode(pParse, pExpr, target);
80709  }
80710}
80711
80712/*
80713** Generate code that evalutes the given expression and puts the result
80714** in register target.
80715**
80716** Also make a copy of the expression results into another "cache" register
80717** and modify the expression so that the next time it is evaluated,
80718** the result is a copy of the cache register.
80719**
80720** This routine is used for expressions that are used multiple
80721** times.  They are evaluated once and the results of the expression
80722** are reused.
80723*/
80724SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
80725  Vdbe *v = pParse->pVdbe;
80726  int iMem;
80727
80728  assert( target>0 );
80729  assert( pExpr->op!=TK_REGISTER );
80730  sqlite3ExprCode(pParse, pExpr, target);
80731  iMem = ++pParse->nMem;
80732  sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
80733  exprToRegister(pExpr, iMem);
80734}
80735
80736#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
80737/*
80738** Generate a human-readable explanation of an expression tree.
80739*/
80740SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){
80741  int op;                   /* The opcode being coded */
80742  const char *zBinOp = 0;   /* Binary operator */
80743  const char *zUniOp = 0;   /* Unary operator */
80744  if( pExpr==0 ){
80745    op = TK_NULL;
80746  }else{
80747    op = pExpr->op;
80748  }
80749  switch( op ){
80750    case TK_AGG_COLUMN: {
80751      sqlite3ExplainPrintf(pOut, "AGG{%d:%d}",
80752            pExpr->iTable, pExpr->iColumn);
80753      break;
80754    }
80755    case TK_COLUMN: {
80756      if( pExpr->iTable<0 ){
80757        /* This only happens when coding check constraints */
80758        sqlite3ExplainPrintf(pOut, "COLUMN(%d)", pExpr->iColumn);
80759      }else{
80760        sqlite3ExplainPrintf(pOut, "{%d:%d}",
80761                             pExpr->iTable, pExpr->iColumn);
80762      }
80763      break;
80764    }
80765    case TK_INTEGER: {
80766      if( pExpr->flags & EP_IntValue ){
80767        sqlite3ExplainPrintf(pOut, "%d", pExpr->u.iValue);
80768      }else{
80769        sqlite3ExplainPrintf(pOut, "%s", pExpr->u.zToken);
80770      }
80771      break;
80772    }
80773#ifndef SQLITE_OMIT_FLOATING_POINT
80774    case TK_FLOAT: {
80775      sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
80776      break;
80777    }
80778#endif
80779    case TK_STRING: {
80780      sqlite3ExplainPrintf(pOut,"%Q", pExpr->u.zToken);
80781      break;
80782    }
80783    case TK_NULL: {
80784      sqlite3ExplainPrintf(pOut,"NULL");
80785      break;
80786    }
80787#ifndef SQLITE_OMIT_BLOB_LITERAL
80788    case TK_BLOB: {
80789      sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
80790      break;
80791    }
80792#endif
80793    case TK_VARIABLE: {
80794      sqlite3ExplainPrintf(pOut,"VARIABLE(%s,%d)",
80795                           pExpr->u.zToken, pExpr->iColumn);
80796      break;
80797    }
80798    case TK_REGISTER: {
80799      sqlite3ExplainPrintf(pOut,"REGISTER(%d)", pExpr->iTable);
80800      break;
80801    }
80802    case TK_AS: {
80803      sqlite3ExplainExpr(pOut, pExpr->pLeft);
80804      break;
80805    }
80806#ifndef SQLITE_OMIT_CAST
80807    case TK_CAST: {
80808      /* Expressions of the form:   CAST(pLeft AS token) */
80809      const char *zAff = "unk";
80810      switch( sqlite3AffinityType(pExpr->u.zToken, 0) ){
80811        case SQLITE_AFF_TEXT:    zAff = "TEXT";     break;
80812        case SQLITE_AFF_NONE:    zAff = "NONE";     break;
80813        case SQLITE_AFF_NUMERIC: zAff = "NUMERIC";  break;
80814        case SQLITE_AFF_INTEGER: zAff = "INTEGER";  break;
80815        case SQLITE_AFF_REAL:    zAff = "REAL";     break;
80816      }
80817      sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff);
80818      sqlite3ExplainExpr(pOut, pExpr->pLeft);
80819      sqlite3ExplainPrintf(pOut, ")");
80820      break;
80821    }
80822#endif /* SQLITE_OMIT_CAST */
80823    case TK_LT:      zBinOp = "LT";     break;
80824    case TK_LE:      zBinOp = "LE";     break;
80825    case TK_GT:      zBinOp = "GT";     break;
80826    case TK_GE:      zBinOp = "GE";     break;
80827    case TK_NE:      zBinOp = "NE";     break;
80828    case TK_EQ:      zBinOp = "EQ";     break;
80829    case TK_IS:      zBinOp = "IS";     break;
80830    case TK_ISNOT:   zBinOp = "ISNOT";  break;
80831    case TK_AND:     zBinOp = "AND";    break;
80832    case TK_OR:      zBinOp = "OR";     break;
80833    case TK_PLUS:    zBinOp = "ADD";    break;
80834    case TK_STAR:    zBinOp = "MUL";    break;
80835    case TK_MINUS:   zBinOp = "SUB";    break;
80836    case TK_REM:     zBinOp = "REM";    break;
80837    case TK_BITAND:  zBinOp = "BITAND"; break;
80838    case TK_BITOR:   zBinOp = "BITOR";  break;
80839    case TK_SLASH:   zBinOp = "DIV";    break;
80840    case TK_LSHIFT:  zBinOp = "LSHIFT"; break;
80841    case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
80842    case TK_CONCAT:  zBinOp = "CONCAT"; break;
80843
80844    case TK_UMINUS:  zUniOp = "UMINUS"; break;
80845    case TK_UPLUS:   zUniOp = "UPLUS";  break;
80846    case TK_BITNOT:  zUniOp = "BITNOT"; break;
80847    case TK_NOT:     zUniOp = "NOT";    break;
80848    case TK_ISNULL:  zUniOp = "ISNULL"; break;
80849    case TK_NOTNULL: zUniOp = "NOTNULL"; break;
80850
80851    case TK_COLLATE: {
80852      sqlite3ExplainExpr(pOut, pExpr->pLeft);
80853      sqlite3ExplainPrintf(pOut,".COLLATE(%s)",pExpr->u.zToken);
80854      break;
80855    }
80856
80857    case TK_AGG_FUNCTION:
80858    case TK_FUNCTION: {
80859      ExprList *pFarg;       /* List of function arguments */
80860      if( ExprHasProperty(pExpr, EP_TokenOnly) ){
80861        pFarg = 0;
80862      }else{
80863        pFarg = pExpr->x.pList;
80864      }
80865      if( op==TK_AGG_FUNCTION ){
80866        sqlite3ExplainPrintf(pOut, "AGG_FUNCTION%d:%s(",
80867                             pExpr->op2, pExpr->u.zToken);
80868      }else{
80869        sqlite3ExplainPrintf(pOut, "FUNCTION:%s(", pExpr->u.zToken);
80870      }
80871      if( pFarg ){
80872        sqlite3ExplainExprList(pOut, pFarg);
80873      }
80874      sqlite3ExplainPrintf(pOut, ")");
80875      break;
80876    }
80877#ifndef SQLITE_OMIT_SUBQUERY
80878    case TK_EXISTS: {
80879      sqlite3ExplainPrintf(pOut, "EXISTS(");
80880      sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
80881      sqlite3ExplainPrintf(pOut,")");
80882      break;
80883    }
80884    case TK_SELECT: {
80885      sqlite3ExplainPrintf(pOut, "(");
80886      sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
80887      sqlite3ExplainPrintf(pOut, ")");
80888      break;
80889    }
80890    case TK_IN: {
80891      sqlite3ExplainPrintf(pOut, "IN(");
80892      sqlite3ExplainExpr(pOut, pExpr->pLeft);
80893      sqlite3ExplainPrintf(pOut, ",");
80894      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
80895        sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
80896      }else{
80897        sqlite3ExplainExprList(pOut, pExpr->x.pList);
80898      }
80899      sqlite3ExplainPrintf(pOut, ")");
80900      break;
80901    }
80902#endif /* SQLITE_OMIT_SUBQUERY */
80903
80904    /*
80905    **    x BETWEEN y AND z
80906    **
80907    ** This is equivalent to
80908    **
80909    **    x>=y AND x<=z
80910    **
80911    ** X is stored in pExpr->pLeft.
80912    ** Y is stored in pExpr->pList->a[0].pExpr.
80913    ** Z is stored in pExpr->pList->a[1].pExpr.
80914    */
80915    case TK_BETWEEN: {
80916      Expr *pX = pExpr->pLeft;
80917      Expr *pY = pExpr->x.pList->a[0].pExpr;
80918      Expr *pZ = pExpr->x.pList->a[1].pExpr;
80919      sqlite3ExplainPrintf(pOut, "BETWEEN(");
80920      sqlite3ExplainExpr(pOut, pX);
80921      sqlite3ExplainPrintf(pOut, ",");
80922      sqlite3ExplainExpr(pOut, pY);
80923      sqlite3ExplainPrintf(pOut, ",");
80924      sqlite3ExplainExpr(pOut, pZ);
80925      sqlite3ExplainPrintf(pOut, ")");
80926      break;
80927    }
80928    case TK_TRIGGER: {
80929      /* If the opcode is TK_TRIGGER, then the expression is a reference
80930      ** to a column in the new.* or old.* pseudo-tables available to
80931      ** trigger programs. In this case Expr.iTable is set to 1 for the
80932      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
80933      ** is set to the column of the pseudo-table to read, or to -1 to
80934      ** read the rowid field.
80935      */
80936      sqlite3ExplainPrintf(pOut, "%s(%d)",
80937          pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
80938      break;
80939    }
80940    case TK_CASE: {
80941      sqlite3ExplainPrintf(pOut, "CASE(");
80942      sqlite3ExplainExpr(pOut, pExpr->pLeft);
80943      sqlite3ExplainPrintf(pOut, ",");
80944      sqlite3ExplainExprList(pOut, pExpr->x.pList);
80945      break;
80946    }
80947#ifndef SQLITE_OMIT_TRIGGER
80948    case TK_RAISE: {
80949      const char *zType = "unk";
80950      switch( pExpr->affinity ){
80951        case OE_Rollback:   zType = "rollback";  break;
80952        case OE_Abort:      zType = "abort";     break;
80953        case OE_Fail:       zType = "fail";      break;
80954        case OE_Ignore:     zType = "ignore";    break;
80955      }
80956      sqlite3ExplainPrintf(pOut, "RAISE-%s(%s)", zType, pExpr->u.zToken);
80957      break;
80958    }
80959#endif
80960  }
80961  if( zBinOp ){
80962    sqlite3ExplainPrintf(pOut,"%s(", zBinOp);
80963    sqlite3ExplainExpr(pOut, pExpr->pLeft);
80964    sqlite3ExplainPrintf(pOut,",");
80965    sqlite3ExplainExpr(pOut, pExpr->pRight);
80966    sqlite3ExplainPrintf(pOut,")");
80967  }else if( zUniOp ){
80968    sqlite3ExplainPrintf(pOut,"%s(", zUniOp);
80969    sqlite3ExplainExpr(pOut, pExpr->pLeft);
80970    sqlite3ExplainPrintf(pOut,")");
80971  }
80972}
80973#endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
80974
80975#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
80976/*
80977** Generate a human-readable explanation of an expression list.
80978*/
80979SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){
80980  int i;
80981  if( pList==0 || pList->nExpr==0 ){
80982    sqlite3ExplainPrintf(pOut, "(empty-list)");
80983    return;
80984  }else if( pList->nExpr==1 ){
80985    sqlite3ExplainExpr(pOut, pList->a[0].pExpr);
80986  }else{
80987    sqlite3ExplainPush(pOut);
80988    for(i=0; i<pList->nExpr; i++){
80989      sqlite3ExplainPrintf(pOut, "item[%d] = ", i);
80990      sqlite3ExplainPush(pOut);
80991      sqlite3ExplainExpr(pOut, pList->a[i].pExpr);
80992      sqlite3ExplainPop(pOut);
80993      if( pList->a[i].zName ){
80994        sqlite3ExplainPrintf(pOut, " AS %s", pList->a[i].zName);
80995      }
80996      if( pList->a[i].bSpanIsTab ){
80997        sqlite3ExplainPrintf(pOut, " (%s)", pList->a[i].zSpan);
80998      }
80999      if( i<pList->nExpr-1 ){
81000        sqlite3ExplainNL(pOut);
81001      }
81002    }
81003    sqlite3ExplainPop(pOut);
81004  }
81005}
81006#endif /* SQLITE_DEBUG */
81007
81008/*
81009** Generate code that pushes the value of every element of the given
81010** expression list into a sequence of registers beginning at target.
81011**
81012** Return the number of elements evaluated.
81013**
81014** The SQLITE_ECEL_DUP flag prevents the arguments from being
81015** filled using OP_SCopy.  OP_Copy must be used instead.
81016**
81017** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
81018** factored out into initialization code.
81019*/
81020SQLITE_PRIVATE int sqlite3ExprCodeExprList(
81021  Parse *pParse,     /* Parsing context */
81022  ExprList *pList,   /* The expression list to be coded */
81023  int target,        /* Where to write results */
81024  u8 flags           /* SQLITE_ECEL_* flags */
81025){
81026  struct ExprList_item *pItem;
81027  int i, n;
81028  u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
81029  assert( pList!=0 );
81030  assert( target>0 );
81031  assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
81032  n = pList->nExpr;
81033  if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
81034  for(pItem=pList->a, i=0; i<n; i++, pItem++){
81035    Expr *pExpr = pItem->pExpr;
81036    if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
81037      sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
81038    }else{
81039      int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
81040      if( inReg!=target+i ){
81041        VdbeOp *pOp;
81042        Vdbe *v = pParse->pVdbe;
81043        if( copyOp==OP_Copy
81044         && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
81045         && pOp->p1+pOp->p3+1==inReg
81046         && pOp->p2+pOp->p3+1==target+i
81047        ){
81048          pOp->p3++;
81049        }else{
81050          sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
81051        }
81052      }
81053    }
81054  }
81055  return n;
81056}
81057
81058/*
81059** Generate code for a BETWEEN operator.
81060**
81061**    x BETWEEN y AND z
81062**
81063** The above is equivalent to
81064**
81065**    x>=y AND x<=z
81066**
81067** Code it as such, taking care to do the common subexpression
81068** elementation of x.
81069*/
81070static void exprCodeBetween(
81071  Parse *pParse,    /* Parsing and code generating context */
81072  Expr *pExpr,      /* The BETWEEN expression */
81073  int dest,         /* Jump here if the jump is taken */
81074  int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
81075  int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
81076){
81077  Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
81078  Expr compLeft;    /* The  x>=y  term */
81079  Expr compRight;   /* The  x<=z  term */
81080  Expr exprX;       /* The  x  subexpression */
81081  int regFree1 = 0; /* Temporary use register */
81082
81083  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
81084  exprX = *pExpr->pLeft;
81085  exprAnd.op = TK_AND;
81086  exprAnd.pLeft = &compLeft;
81087  exprAnd.pRight = &compRight;
81088  compLeft.op = TK_GE;
81089  compLeft.pLeft = &exprX;
81090  compLeft.pRight = pExpr->x.pList->a[0].pExpr;
81091  compRight.op = TK_LE;
81092  compRight.pLeft = &exprX;
81093  compRight.pRight = pExpr->x.pList->a[1].pExpr;
81094  exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
81095  if( jumpIfTrue ){
81096    sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
81097  }else{
81098    sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
81099  }
81100  sqlite3ReleaseTempReg(pParse, regFree1);
81101
81102  /* Ensure adequate test coverage */
81103  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
81104  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
81105  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
81106  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
81107  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
81108  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
81109  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
81110  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
81111}
81112
81113/*
81114** Generate code for a boolean expression such that a jump is made
81115** to the label "dest" if the expression is true but execution
81116** continues straight thru if the expression is false.
81117**
81118** If the expression evaluates to NULL (neither true nor false), then
81119** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
81120**
81121** This code depends on the fact that certain token values (ex: TK_EQ)
81122** are the same as opcode values (ex: OP_Eq) that implement the corresponding
81123** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
81124** the make process cause these values to align.  Assert()s in the code
81125** below verify that the numbers are aligned correctly.
81126*/
81127SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
81128  Vdbe *v = pParse->pVdbe;
81129  int op = 0;
81130  int regFree1 = 0;
81131  int regFree2 = 0;
81132  int r1, r2;
81133
81134  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
81135  if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */
81136  if( NEVER(pExpr==0) ) return;  /* No way this can happen */
81137  op = pExpr->op;
81138  switch( op ){
81139    case TK_AND: {
81140      int d2 = sqlite3VdbeMakeLabel(v);
81141      testcase( jumpIfNull==0 );
81142      sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
81143      sqlite3ExprCachePush(pParse);
81144      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
81145      sqlite3VdbeResolveLabel(v, d2);
81146      sqlite3ExprCachePop(pParse);
81147      break;
81148    }
81149    case TK_OR: {
81150      testcase( jumpIfNull==0 );
81151      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
81152      sqlite3ExprCachePush(pParse);
81153      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
81154      sqlite3ExprCachePop(pParse);
81155      break;
81156    }
81157    case TK_NOT: {
81158      testcase( jumpIfNull==0 );
81159      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
81160      break;
81161    }
81162    case TK_LT:
81163    case TK_LE:
81164    case TK_GT:
81165    case TK_GE:
81166    case TK_NE:
81167    case TK_EQ: {
81168      testcase( jumpIfNull==0 );
81169      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
81170      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
81171      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
81172                  r1, r2, dest, jumpIfNull);
81173      assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
81174      assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
81175      assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
81176      assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
81177      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
81178      assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
81179      testcase( regFree1==0 );
81180      testcase( regFree2==0 );
81181      break;
81182    }
81183    case TK_IS:
81184    case TK_ISNOT: {
81185      testcase( op==TK_IS );
81186      testcase( op==TK_ISNOT );
81187      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
81188      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
81189      op = (op==TK_IS) ? TK_EQ : TK_NE;
81190      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
81191                  r1, r2, dest, SQLITE_NULLEQ);
81192      VdbeCoverageIf(v, op==TK_EQ);
81193      VdbeCoverageIf(v, op==TK_NE);
81194      testcase( regFree1==0 );
81195      testcase( regFree2==0 );
81196      break;
81197    }
81198    case TK_ISNULL:
81199    case TK_NOTNULL: {
81200      assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
81201      assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
81202      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
81203      sqlite3VdbeAddOp2(v, op, r1, dest);
81204      VdbeCoverageIf(v, op==TK_ISNULL);
81205      VdbeCoverageIf(v, op==TK_NOTNULL);
81206      testcase( regFree1==0 );
81207      break;
81208    }
81209    case TK_BETWEEN: {
81210      testcase( jumpIfNull==0 );
81211      exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
81212      break;
81213    }
81214#ifndef SQLITE_OMIT_SUBQUERY
81215    case TK_IN: {
81216      int destIfFalse = sqlite3VdbeMakeLabel(v);
81217      int destIfNull = jumpIfNull ? dest : destIfFalse;
81218      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
81219      sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
81220      sqlite3VdbeResolveLabel(v, destIfFalse);
81221      break;
81222    }
81223#endif
81224    default: {
81225      if( exprAlwaysTrue(pExpr) ){
81226        sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
81227      }else if( exprAlwaysFalse(pExpr) ){
81228        /* No-op */
81229      }else{
81230        r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
81231        sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
81232        VdbeCoverage(v);
81233        testcase( regFree1==0 );
81234        testcase( jumpIfNull==0 );
81235      }
81236      break;
81237    }
81238  }
81239  sqlite3ReleaseTempReg(pParse, regFree1);
81240  sqlite3ReleaseTempReg(pParse, regFree2);
81241}
81242
81243/*
81244** Generate code for a boolean expression such that a jump is made
81245** to the label "dest" if the expression is false but execution
81246** continues straight thru if the expression is true.
81247**
81248** If the expression evaluates to NULL (neither true nor false) then
81249** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
81250** is 0.
81251*/
81252SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
81253  Vdbe *v = pParse->pVdbe;
81254  int op = 0;
81255  int regFree1 = 0;
81256  int regFree2 = 0;
81257  int r1, r2;
81258
81259  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
81260  if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
81261  if( pExpr==0 )    return;
81262
81263  /* The value of pExpr->op and op are related as follows:
81264  **
81265  **       pExpr->op            op
81266  **       ---------          ----------
81267  **       TK_ISNULL          OP_NotNull
81268  **       TK_NOTNULL         OP_IsNull
81269  **       TK_NE              OP_Eq
81270  **       TK_EQ              OP_Ne
81271  **       TK_GT              OP_Le
81272  **       TK_LE              OP_Gt
81273  **       TK_GE              OP_Lt
81274  **       TK_LT              OP_Ge
81275  **
81276  ** For other values of pExpr->op, op is undefined and unused.
81277  ** The value of TK_ and OP_ constants are arranged such that we
81278  ** can compute the mapping above using the following expression.
81279  ** Assert()s verify that the computation is correct.
81280  */
81281  op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
81282
81283  /* Verify correct alignment of TK_ and OP_ constants
81284  */
81285  assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
81286  assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
81287  assert( pExpr->op!=TK_NE || op==OP_Eq );
81288  assert( pExpr->op!=TK_EQ || op==OP_Ne );
81289  assert( pExpr->op!=TK_LT || op==OP_Ge );
81290  assert( pExpr->op!=TK_LE || op==OP_Gt );
81291  assert( pExpr->op!=TK_GT || op==OP_Le );
81292  assert( pExpr->op!=TK_GE || op==OP_Lt );
81293
81294  switch( pExpr->op ){
81295    case TK_AND: {
81296      testcase( jumpIfNull==0 );
81297      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
81298      sqlite3ExprCachePush(pParse);
81299      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
81300      sqlite3ExprCachePop(pParse);
81301      break;
81302    }
81303    case TK_OR: {
81304      int d2 = sqlite3VdbeMakeLabel(v);
81305      testcase( jumpIfNull==0 );
81306      sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
81307      sqlite3ExprCachePush(pParse);
81308      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
81309      sqlite3VdbeResolveLabel(v, d2);
81310      sqlite3ExprCachePop(pParse);
81311      break;
81312    }
81313    case TK_NOT: {
81314      testcase( jumpIfNull==0 );
81315      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
81316      break;
81317    }
81318    case TK_LT:
81319    case TK_LE:
81320    case TK_GT:
81321    case TK_GE:
81322    case TK_NE:
81323    case TK_EQ: {
81324      testcase( jumpIfNull==0 );
81325      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
81326      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
81327      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
81328                  r1, r2, dest, jumpIfNull);
81329      assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
81330      assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
81331      assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
81332      assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
81333      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
81334      assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
81335      testcase( regFree1==0 );
81336      testcase( regFree2==0 );
81337      break;
81338    }
81339    case TK_IS:
81340    case TK_ISNOT: {
81341      testcase( pExpr->op==TK_IS );
81342      testcase( pExpr->op==TK_ISNOT );
81343      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
81344      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
81345      op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
81346      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
81347                  r1, r2, dest, SQLITE_NULLEQ);
81348      VdbeCoverageIf(v, op==TK_EQ);
81349      VdbeCoverageIf(v, op==TK_NE);
81350      testcase( regFree1==0 );
81351      testcase( regFree2==0 );
81352      break;
81353    }
81354    case TK_ISNULL:
81355    case TK_NOTNULL: {
81356      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
81357      sqlite3VdbeAddOp2(v, op, r1, dest);
81358      testcase( op==TK_ISNULL );   VdbeCoverageIf(v, op==TK_ISNULL);
81359      testcase( op==TK_NOTNULL );  VdbeCoverageIf(v, op==TK_NOTNULL);
81360      testcase( regFree1==0 );
81361      break;
81362    }
81363    case TK_BETWEEN: {
81364      testcase( jumpIfNull==0 );
81365      exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
81366      break;
81367    }
81368#ifndef SQLITE_OMIT_SUBQUERY
81369    case TK_IN: {
81370      if( jumpIfNull ){
81371        sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
81372      }else{
81373        int destIfNull = sqlite3VdbeMakeLabel(v);
81374        sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
81375        sqlite3VdbeResolveLabel(v, destIfNull);
81376      }
81377      break;
81378    }
81379#endif
81380    default: {
81381      if( exprAlwaysFalse(pExpr) ){
81382        sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
81383      }else if( exprAlwaysTrue(pExpr) ){
81384        /* no-op */
81385      }else{
81386        r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
81387        sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
81388        VdbeCoverage(v);
81389        testcase( regFree1==0 );
81390        testcase( jumpIfNull==0 );
81391      }
81392      break;
81393    }
81394  }
81395  sqlite3ReleaseTempReg(pParse, regFree1);
81396  sqlite3ReleaseTempReg(pParse, regFree2);
81397}
81398
81399/*
81400** Do a deep comparison of two expression trees.  Return 0 if the two
81401** expressions are completely identical.  Return 1 if they differ only
81402** by a COLLATE operator at the top level.  Return 2 if there are differences
81403** other than the top-level COLLATE operator.
81404**
81405** If any subelement of pB has Expr.iTable==(-1) then it is allowed
81406** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
81407**
81408** The pA side might be using TK_REGISTER.  If that is the case and pB is
81409** not using TK_REGISTER but is otherwise equivalent, then still return 0.
81410**
81411** Sometimes this routine will return 2 even if the two expressions
81412** really are equivalent.  If we cannot prove that the expressions are
81413** identical, we return 2 just to be safe.  So if this routine
81414** returns 2, then you do not really know for certain if the two
81415** expressions are the same.  But if you get a 0 or 1 return, then you
81416** can be sure the expressions are the same.  In the places where
81417** this routine is used, it does not hurt to get an extra 2 - that
81418** just might result in some slightly slower code.  But returning
81419** an incorrect 0 or 1 could lead to a malfunction.
81420*/
81421SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
81422  u32 combinedFlags;
81423  if( pA==0 || pB==0 ){
81424    return pB==pA ? 0 : 2;
81425  }
81426  combinedFlags = pA->flags | pB->flags;
81427  if( combinedFlags & EP_IntValue ){
81428    if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
81429      return 0;
81430    }
81431    return 2;
81432  }
81433  if( pA->op!=pB->op ){
81434    if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
81435      return 1;
81436    }
81437    if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
81438      return 1;
81439    }
81440    return 2;
81441  }
81442  if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken ){
81443    if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
81444      return pA->op==TK_COLLATE ? 1 : 2;
81445    }
81446  }
81447  if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
81448  if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
81449    if( combinedFlags & EP_xIsSelect ) return 2;
81450    if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
81451    if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
81452    if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
81453    if( ALWAYS((combinedFlags & EP_Reduced)==0) ){
81454      if( pA->iColumn!=pB->iColumn ) return 2;
81455      if( pA->iTable!=pB->iTable
81456       && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
81457    }
81458  }
81459  return 0;
81460}
81461
81462/*
81463** Compare two ExprList objects.  Return 0 if they are identical and
81464** non-zero if they differ in any way.
81465**
81466** If any subelement of pB has Expr.iTable==(-1) then it is allowed
81467** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
81468**
81469** This routine might return non-zero for equivalent ExprLists.  The
81470** only consequence will be disabled optimizations.  But this routine
81471** must never return 0 if the two ExprList objects are different, or
81472** a malfunction will result.
81473**
81474** Two NULL pointers are considered to be the same.  But a NULL pointer
81475** always differs from a non-NULL pointer.
81476*/
81477SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
81478  int i;
81479  if( pA==0 && pB==0 ) return 0;
81480  if( pA==0 || pB==0 ) return 1;
81481  if( pA->nExpr!=pB->nExpr ) return 1;
81482  for(i=0; i<pA->nExpr; i++){
81483    Expr *pExprA = pA->a[i].pExpr;
81484    Expr *pExprB = pB->a[i].pExpr;
81485    if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
81486    if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
81487  }
81488  return 0;
81489}
81490
81491/*
81492** Return true if we can prove the pE2 will always be true if pE1 is
81493** true.  Return false if we cannot complete the proof or if pE2 might
81494** be false.  Examples:
81495**
81496**     pE1: x==5       pE2: x==5             Result: true
81497**     pE1: x>0        pE2: x==5             Result: false
81498**     pE1: x=21       pE2: x=21 OR y=43     Result: true
81499**     pE1: x!=123     pE2: x IS NOT NULL    Result: true
81500**     pE1: x!=?1      pE2: x IS NOT NULL    Result: true
81501**     pE1: x IS NULL  pE2: x IS NOT NULL    Result: false
81502**     pE1: x IS ?2    pE2: x IS NOT NULL    Reuslt: false
81503**
81504** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
81505** Expr.iTable<0 then assume a table number given by iTab.
81506**
81507** When in doubt, return false.  Returning true might give a performance
81508** improvement.  Returning false might cause a performance reduction, but
81509** it will always give the correct answer and is hence always safe.
81510*/
81511SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
81512  if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
81513    return 1;
81514  }
81515  if( pE2->op==TK_OR
81516   && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
81517             || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
81518  ){
81519    return 1;
81520  }
81521  if( pE2->op==TK_NOTNULL
81522   && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
81523   && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
81524  ){
81525    return 1;
81526  }
81527  return 0;
81528}
81529
81530/*
81531** An instance of the following structure is used by the tree walker
81532** to count references to table columns in the arguments of an
81533** aggregate function, in order to implement the
81534** sqlite3FunctionThisSrc() routine.
81535*/
81536struct SrcCount {
81537  SrcList *pSrc;   /* One particular FROM clause in a nested query */
81538  int nThis;       /* Number of references to columns in pSrcList */
81539  int nOther;      /* Number of references to columns in other FROM clauses */
81540};
81541
81542/*
81543** Count the number of references to columns.
81544*/
81545static int exprSrcCount(Walker *pWalker, Expr *pExpr){
81546  /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
81547  ** is always called before sqlite3ExprAnalyzeAggregates() and so the
81548  ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
81549  ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
81550  ** NEVER() will need to be removed. */
81551  if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
81552    int i;
81553    struct SrcCount *p = pWalker->u.pSrcCount;
81554    SrcList *pSrc = p->pSrc;
81555    for(i=0; i<pSrc->nSrc; i++){
81556      if( pExpr->iTable==pSrc->a[i].iCursor ) break;
81557    }
81558    if( i<pSrc->nSrc ){
81559      p->nThis++;
81560    }else{
81561      p->nOther++;
81562    }
81563  }
81564  return WRC_Continue;
81565}
81566
81567/*
81568** Determine if any of the arguments to the pExpr Function reference
81569** pSrcList.  Return true if they do.  Also return true if the function
81570** has no arguments or has only constant arguments.  Return false if pExpr
81571** references columns but not columns of tables found in pSrcList.
81572*/
81573SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
81574  Walker w;
81575  struct SrcCount cnt;
81576  assert( pExpr->op==TK_AGG_FUNCTION );
81577  memset(&w, 0, sizeof(w));
81578  w.xExprCallback = exprSrcCount;
81579  w.u.pSrcCount = &cnt;
81580  cnt.pSrc = pSrcList;
81581  cnt.nThis = 0;
81582  cnt.nOther = 0;
81583  sqlite3WalkExprList(&w, pExpr->x.pList);
81584  return cnt.nThis>0 || cnt.nOther==0;
81585}
81586
81587/*
81588** Add a new element to the pAggInfo->aCol[] array.  Return the index of
81589** the new element.  Return a negative number if malloc fails.
81590*/
81591static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
81592  int i;
81593  pInfo->aCol = sqlite3ArrayAllocate(
81594       db,
81595       pInfo->aCol,
81596       sizeof(pInfo->aCol[0]),
81597       &pInfo->nColumn,
81598       &i
81599  );
81600  return i;
81601}
81602
81603/*
81604** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
81605** the new element.  Return a negative number if malloc fails.
81606*/
81607static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
81608  int i;
81609  pInfo->aFunc = sqlite3ArrayAllocate(
81610       db,
81611       pInfo->aFunc,
81612       sizeof(pInfo->aFunc[0]),
81613       &pInfo->nFunc,
81614       &i
81615  );
81616  return i;
81617}
81618
81619/*
81620** This is the xExprCallback for a tree walker.  It is used to
81621** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
81622** for additional information.
81623*/
81624static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
81625  int i;
81626  NameContext *pNC = pWalker->u.pNC;
81627  Parse *pParse = pNC->pParse;
81628  SrcList *pSrcList = pNC->pSrcList;
81629  AggInfo *pAggInfo = pNC->pAggInfo;
81630
81631  switch( pExpr->op ){
81632    case TK_AGG_COLUMN:
81633    case TK_COLUMN: {
81634      testcase( pExpr->op==TK_AGG_COLUMN );
81635      testcase( pExpr->op==TK_COLUMN );
81636      /* Check to see if the column is in one of the tables in the FROM
81637      ** clause of the aggregate query */
81638      if( ALWAYS(pSrcList!=0) ){
81639        struct SrcList_item *pItem = pSrcList->a;
81640        for(i=0; i<pSrcList->nSrc; i++, pItem++){
81641          struct AggInfo_col *pCol;
81642          assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
81643          if( pExpr->iTable==pItem->iCursor ){
81644            /* If we reach this point, it means that pExpr refers to a table
81645            ** that is in the FROM clause of the aggregate query.
81646            **
81647            ** Make an entry for the column in pAggInfo->aCol[] if there
81648            ** is not an entry there already.
81649            */
81650            int k;
81651            pCol = pAggInfo->aCol;
81652            for(k=0; k<pAggInfo->nColumn; k++, pCol++){
81653              if( pCol->iTable==pExpr->iTable &&
81654                  pCol->iColumn==pExpr->iColumn ){
81655                break;
81656              }
81657            }
81658            if( (k>=pAggInfo->nColumn)
81659             && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
81660            ){
81661              pCol = &pAggInfo->aCol[k];
81662              pCol->pTab = pExpr->pTab;
81663              pCol->iTable = pExpr->iTable;
81664              pCol->iColumn = pExpr->iColumn;
81665              pCol->iMem = ++pParse->nMem;
81666              pCol->iSorterColumn = -1;
81667              pCol->pExpr = pExpr;
81668              if( pAggInfo->pGroupBy ){
81669                int j, n;
81670                ExprList *pGB = pAggInfo->pGroupBy;
81671                struct ExprList_item *pTerm = pGB->a;
81672                n = pGB->nExpr;
81673                for(j=0; j<n; j++, pTerm++){
81674                  Expr *pE = pTerm->pExpr;
81675                  if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
81676                      pE->iColumn==pExpr->iColumn ){
81677                    pCol->iSorterColumn = j;
81678                    break;
81679                  }
81680                }
81681              }
81682              if( pCol->iSorterColumn<0 ){
81683                pCol->iSorterColumn = pAggInfo->nSortingColumn++;
81684              }
81685            }
81686            /* There is now an entry for pExpr in pAggInfo->aCol[] (either
81687            ** because it was there before or because we just created it).
81688            ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
81689            ** pAggInfo->aCol[] entry.
81690            */
81691            ExprSetVVAProperty(pExpr, EP_NoReduce);
81692            pExpr->pAggInfo = pAggInfo;
81693            pExpr->op = TK_AGG_COLUMN;
81694            pExpr->iAgg = (i16)k;
81695            break;
81696          } /* endif pExpr->iTable==pItem->iCursor */
81697        } /* end loop over pSrcList */
81698      }
81699      return WRC_Prune;
81700    }
81701    case TK_AGG_FUNCTION: {
81702      if( (pNC->ncFlags & NC_InAggFunc)==0
81703       && pWalker->walkerDepth==pExpr->op2
81704      ){
81705        /* Check to see if pExpr is a duplicate of another aggregate
81706        ** function that is already in the pAggInfo structure
81707        */
81708        struct AggInfo_func *pItem = pAggInfo->aFunc;
81709        for(i=0; i<pAggInfo->nFunc; i++, pItem++){
81710          if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
81711            break;
81712          }
81713        }
81714        if( i>=pAggInfo->nFunc ){
81715          /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
81716          */
81717          u8 enc = ENC(pParse->db);
81718          i = addAggInfoFunc(pParse->db, pAggInfo);
81719          if( i>=0 ){
81720            assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
81721            pItem = &pAggInfo->aFunc[i];
81722            pItem->pExpr = pExpr;
81723            pItem->iMem = ++pParse->nMem;
81724            assert( !ExprHasProperty(pExpr, EP_IntValue) );
81725            pItem->pFunc = sqlite3FindFunction(pParse->db,
81726                   pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
81727                   pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
81728            if( pExpr->flags & EP_Distinct ){
81729              pItem->iDistinct = pParse->nTab++;
81730            }else{
81731              pItem->iDistinct = -1;
81732            }
81733          }
81734        }
81735        /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
81736        */
81737        assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
81738        ExprSetVVAProperty(pExpr, EP_NoReduce);
81739        pExpr->iAgg = (i16)i;
81740        pExpr->pAggInfo = pAggInfo;
81741        return WRC_Prune;
81742      }else{
81743        return WRC_Continue;
81744      }
81745    }
81746  }
81747  return WRC_Continue;
81748}
81749static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
81750  UNUSED_PARAMETER(pWalker);
81751  UNUSED_PARAMETER(pSelect);
81752  return WRC_Continue;
81753}
81754
81755/*
81756** Analyze the pExpr expression looking for aggregate functions and
81757** for variables that need to be added to AggInfo object that pNC->pAggInfo
81758** points to.  Additional entries are made on the AggInfo object as
81759** necessary.
81760**
81761** This routine should only be called after the expression has been
81762** analyzed by sqlite3ResolveExprNames().
81763*/
81764SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
81765  Walker w;
81766  memset(&w, 0, sizeof(w));
81767  w.xExprCallback = analyzeAggregate;
81768  w.xSelectCallback = analyzeAggregatesInSelect;
81769  w.u.pNC = pNC;
81770  assert( pNC->pSrcList!=0 );
81771  sqlite3WalkExpr(&w, pExpr);
81772}
81773
81774/*
81775** Call sqlite3ExprAnalyzeAggregates() for every expression in an
81776** expression list.  Return the number of errors.
81777**
81778** If an error is found, the analysis is cut short.
81779*/
81780SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
81781  struct ExprList_item *pItem;
81782  int i;
81783  if( pList ){
81784    for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
81785      sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
81786    }
81787  }
81788}
81789
81790/*
81791** Allocate a single new register for use to hold some intermediate result.
81792*/
81793SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
81794  if( pParse->nTempReg==0 ){
81795    return ++pParse->nMem;
81796  }
81797  return pParse->aTempReg[--pParse->nTempReg];
81798}
81799
81800/*
81801** Deallocate a register, making available for reuse for some other
81802** purpose.
81803**
81804** If a register is currently being used by the column cache, then
81805** the dallocation is deferred until the column cache line that uses
81806** the register becomes stale.
81807*/
81808SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
81809  if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
81810    int i;
81811    struct yColCache *p;
81812    for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
81813      if( p->iReg==iReg ){
81814        p->tempReg = 1;
81815        return;
81816      }
81817    }
81818    pParse->aTempReg[pParse->nTempReg++] = iReg;
81819  }
81820}
81821
81822/*
81823** Allocate or deallocate a block of nReg consecutive registers
81824*/
81825SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
81826  int i, n;
81827  i = pParse->iRangeReg;
81828  n = pParse->nRangeReg;
81829  if( nReg<=n ){
81830    assert( !usedAsColumnCache(pParse, i, i+n-1) );
81831    pParse->iRangeReg += nReg;
81832    pParse->nRangeReg -= nReg;
81833  }else{
81834    i = pParse->nMem+1;
81835    pParse->nMem += nReg;
81836  }
81837  return i;
81838}
81839SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
81840  sqlite3ExprCacheRemove(pParse, iReg, nReg);
81841  if( nReg>pParse->nRangeReg ){
81842    pParse->nRangeReg = nReg;
81843    pParse->iRangeReg = iReg;
81844  }
81845}
81846
81847/*
81848** Mark all temporary registers as being unavailable for reuse.
81849*/
81850SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
81851  pParse->nTempReg = 0;
81852  pParse->nRangeReg = 0;
81853}
81854
81855/************** End of expr.c ************************************************/
81856/************** Begin file alter.c *******************************************/
81857/*
81858** 2005 February 15
81859**
81860** The author disclaims copyright to this source code.  In place of
81861** a legal notice, here is a blessing:
81862**
81863**    May you do good and not evil.
81864**    May you find forgiveness for yourself and forgive others.
81865**    May you share freely, never taking more than you give.
81866**
81867*************************************************************************
81868** This file contains C code routines that used to generate VDBE code
81869** that implements the ALTER TABLE command.
81870*/
81871
81872/*
81873** The code in this file only exists if we are not omitting the
81874** ALTER TABLE logic from the build.
81875*/
81876#ifndef SQLITE_OMIT_ALTERTABLE
81877
81878
81879/*
81880** This function is used by SQL generated to implement the
81881** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
81882** CREATE INDEX command. The second is a table name. The table name in
81883** the CREATE TABLE or CREATE INDEX statement is replaced with the third
81884** argument and the result returned. Examples:
81885**
81886** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
81887**     -> 'CREATE TABLE def(a, b, c)'
81888**
81889** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
81890**     -> 'CREATE INDEX i ON def(a, b, c)'
81891*/
81892static void renameTableFunc(
81893  sqlite3_context *context,
81894  int NotUsed,
81895  sqlite3_value **argv
81896){
81897  unsigned char const *zSql = sqlite3_value_text(argv[0]);
81898  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
81899
81900  int token;
81901  Token tname;
81902  unsigned char const *zCsr = zSql;
81903  int len = 0;
81904  char *zRet;
81905
81906  sqlite3 *db = sqlite3_context_db_handle(context);
81907
81908  UNUSED_PARAMETER(NotUsed);
81909
81910  /* The principle used to locate the table name in the CREATE TABLE
81911  ** statement is that the table name is the first non-space token that
81912  ** is immediately followed by a TK_LP or TK_USING token.
81913  */
81914  if( zSql ){
81915    do {
81916      if( !*zCsr ){
81917        /* Ran out of input before finding an opening bracket. Return NULL. */
81918        return;
81919      }
81920
81921      /* Store the token that zCsr points to in tname. */
81922      tname.z = (char*)zCsr;
81923      tname.n = len;
81924
81925      /* Advance zCsr to the next token. Store that token type in 'token',
81926      ** and its length in 'len' (to be used next iteration of this loop).
81927      */
81928      do {
81929        zCsr += len;
81930        len = sqlite3GetToken(zCsr, &token);
81931      } while( token==TK_SPACE );
81932      assert( len>0 );
81933    } while( token!=TK_LP && token!=TK_USING );
81934
81935    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
81936       zSql, zTableName, tname.z+tname.n);
81937    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
81938  }
81939}
81940
81941/*
81942** This C function implements an SQL user function that is used by SQL code
81943** generated by the ALTER TABLE ... RENAME command to modify the definition
81944** of any foreign key constraints that use the table being renamed as the
81945** parent table. It is passed three arguments:
81946**
81947**   1) The complete text of the CREATE TABLE statement being modified,
81948**   2) The old name of the table being renamed, and
81949**   3) The new name of the table being renamed.
81950**
81951** It returns the new CREATE TABLE statement. For example:
81952**
81953**   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
81954**       -> 'CREATE TABLE t1(a REFERENCES t3)'
81955*/
81956#ifndef SQLITE_OMIT_FOREIGN_KEY
81957static void renameParentFunc(
81958  sqlite3_context *context,
81959  int NotUsed,
81960  sqlite3_value **argv
81961){
81962  sqlite3 *db = sqlite3_context_db_handle(context);
81963  char *zOutput = 0;
81964  char *zResult;
81965  unsigned char const *zInput = sqlite3_value_text(argv[0]);
81966  unsigned char const *zOld = sqlite3_value_text(argv[1]);
81967  unsigned char const *zNew = sqlite3_value_text(argv[2]);
81968
81969  unsigned const char *z;         /* Pointer to token */
81970  int n;                          /* Length of token z */
81971  int token;                      /* Type of token */
81972
81973  UNUSED_PARAMETER(NotUsed);
81974  if( zInput==0 || zOld==0 ) return;
81975  for(z=zInput; *z; z=z+n){
81976    n = sqlite3GetToken(z, &token);
81977    if( token==TK_REFERENCES ){
81978      char *zParent;
81979      do {
81980        z += n;
81981        n = sqlite3GetToken(z, &token);
81982      }while( token==TK_SPACE );
81983
81984      zParent = sqlite3DbStrNDup(db, (const char *)z, n);
81985      if( zParent==0 ) break;
81986      sqlite3Dequote(zParent);
81987      if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
81988        char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
81989            (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
81990        );
81991        sqlite3DbFree(db, zOutput);
81992        zOutput = zOut;
81993        zInput = &z[n];
81994      }
81995      sqlite3DbFree(db, zParent);
81996    }
81997  }
81998
81999  zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
82000  sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
82001  sqlite3DbFree(db, zOutput);
82002}
82003#endif
82004
82005#ifndef SQLITE_OMIT_TRIGGER
82006/* This function is used by SQL generated to implement the
82007** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
82008** statement. The second is a table name. The table name in the CREATE
82009** TRIGGER statement is replaced with the third argument and the result
82010** returned. This is analagous to renameTableFunc() above, except for CREATE
82011** TRIGGER, not CREATE INDEX and CREATE TABLE.
82012*/
82013static void renameTriggerFunc(
82014  sqlite3_context *context,
82015  int NotUsed,
82016  sqlite3_value **argv
82017){
82018  unsigned char const *zSql = sqlite3_value_text(argv[0]);
82019  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
82020
82021  int token;
82022  Token tname;
82023  int dist = 3;
82024  unsigned char const *zCsr = zSql;
82025  int len = 0;
82026  char *zRet;
82027  sqlite3 *db = sqlite3_context_db_handle(context);
82028
82029  UNUSED_PARAMETER(NotUsed);
82030
82031  /* The principle used to locate the table name in the CREATE TRIGGER
82032  ** statement is that the table name is the first token that is immediatedly
82033  ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
82034  ** of TK_WHEN, TK_BEGIN or TK_FOR.
82035  */
82036  if( zSql ){
82037    do {
82038
82039      if( !*zCsr ){
82040        /* Ran out of input before finding the table name. Return NULL. */
82041        return;
82042      }
82043
82044      /* Store the token that zCsr points to in tname. */
82045      tname.z = (char*)zCsr;
82046      tname.n = len;
82047
82048      /* Advance zCsr to the next token. Store that token type in 'token',
82049      ** and its length in 'len' (to be used next iteration of this loop).
82050      */
82051      do {
82052        zCsr += len;
82053        len = sqlite3GetToken(zCsr, &token);
82054      }while( token==TK_SPACE );
82055      assert( len>0 );
82056
82057      /* Variable 'dist' stores the number of tokens read since the most
82058      ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
82059      ** token is read and 'dist' equals 2, the condition stated above
82060      ** to be met.
82061      **
82062      ** Note that ON cannot be a database, table or column name, so
82063      ** there is no need to worry about syntax like
82064      ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
82065      */
82066      dist++;
82067      if( token==TK_DOT || token==TK_ON ){
82068        dist = 0;
82069      }
82070    } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
82071
82072    /* Variable tname now contains the token that is the old table-name
82073    ** in the CREATE TRIGGER statement.
82074    */
82075    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
82076       zSql, zTableName, tname.z+tname.n);
82077    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
82078  }
82079}
82080#endif   /* !SQLITE_OMIT_TRIGGER */
82081
82082/*
82083** Register built-in functions used to help implement ALTER TABLE
82084*/
82085SQLITE_PRIVATE void sqlite3AlterFunctions(void){
82086  static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
82087    FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
82088#ifndef SQLITE_OMIT_TRIGGER
82089    FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
82090#endif
82091#ifndef SQLITE_OMIT_FOREIGN_KEY
82092    FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
82093#endif
82094  };
82095  int i;
82096  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
82097  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
82098
82099  for(i=0; i<ArraySize(aAlterTableFuncs); i++){
82100    sqlite3FuncDefInsert(pHash, &aFunc[i]);
82101  }
82102}
82103
82104/*
82105** This function is used to create the text of expressions of the form:
82106**
82107**   name=<constant1> OR name=<constant2> OR ...
82108**
82109** If argument zWhere is NULL, then a pointer string containing the text
82110** "name=<constant>" is returned, where <constant> is the quoted version
82111** of the string passed as argument zConstant. The returned buffer is
82112** allocated using sqlite3DbMalloc(). It is the responsibility of the
82113** caller to ensure that it is eventually freed.
82114**
82115** If argument zWhere is not NULL, then the string returned is
82116** "<where> OR name=<constant>", where <where> is the contents of zWhere.
82117** In this case zWhere is passed to sqlite3DbFree() before returning.
82118**
82119*/
82120static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
82121  char *zNew;
82122  if( !zWhere ){
82123    zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
82124  }else{
82125    zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
82126    sqlite3DbFree(db, zWhere);
82127  }
82128  return zNew;
82129}
82130
82131#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
82132/*
82133** Generate the text of a WHERE expression which can be used to select all
82134** tables that have foreign key constraints that refer to table pTab (i.e.
82135** constraints for which pTab is the parent table) from the sqlite_master
82136** table.
82137*/
82138static char *whereForeignKeys(Parse *pParse, Table *pTab){
82139  FKey *p;
82140  char *zWhere = 0;
82141  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
82142    zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
82143  }
82144  return zWhere;
82145}
82146#endif
82147
82148/*
82149** Generate the text of a WHERE expression which can be used to select all
82150** temporary triggers on table pTab from the sqlite_temp_master table. If
82151** table pTab has no temporary triggers, or is itself stored in the
82152** temporary database, NULL is returned.
82153*/
82154static char *whereTempTriggers(Parse *pParse, Table *pTab){
82155  Trigger *pTrig;
82156  char *zWhere = 0;
82157  const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
82158
82159  /* If the table is not located in the temp-db (in which case NULL is
82160  ** returned, loop through the tables list of triggers. For each trigger
82161  ** that is not part of the temp-db schema, add a clause to the WHERE
82162  ** expression being built up in zWhere.
82163  */
82164  if( pTab->pSchema!=pTempSchema ){
82165    sqlite3 *db = pParse->db;
82166    for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
82167      if( pTrig->pSchema==pTempSchema ){
82168        zWhere = whereOrName(db, zWhere, pTrig->zName);
82169      }
82170    }
82171  }
82172  if( zWhere ){
82173    char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
82174    sqlite3DbFree(pParse->db, zWhere);
82175    zWhere = zNew;
82176  }
82177  return zWhere;
82178}
82179
82180/*
82181** Generate code to drop and reload the internal representation of table
82182** pTab from the database, including triggers and temporary triggers.
82183** Argument zName is the name of the table in the database schema at
82184** the time the generated code is executed. This can be different from
82185** pTab->zName if this function is being called to code part of an
82186** "ALTER TABLE RENAME TO" statement.
82187*/
82188static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
82189  Vdbe *v;
82190  char *zWhere;
82191  int iDb;                   /* Index of database containing pTab */
82192#ifndef SQLITE_OMIT_TRIGGER
82193  Trigger *pTrig;
82194#endif
82195
82196  v = sqlite3GetVdbe(pParse);
82197  if( NEVER(v==0) ) return;
82198  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
82199  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
82200  assert( iDb>=0 );
82201
82202#ifndef SQLITE_OMIT_TRIGGER
82203  /* Drop any table triggers from the internal schema. */
82204  for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
82205    int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
82206    assert( iTrigDb==iDb || iTrigDb==1 );
82207    sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
82208  }
82209#endif
82210
82211  /* Drop the table and index from the internal schema.  */
82212  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
82213
82214  /* Reload the table, index and permanent trigger schemas. */
82215  zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
82216  if( !zWhere ) return;
82217  sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
82218
82219#ifndef SQLITE_OMIT_TRIGGER
82220  /* Now, if the table is not stored in the temp database, reload any temp
82221  ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
82222  */
82223  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
82224    sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
82225  }
82226#endif
82227}
82228
82229/*
82230** Parameter zName is the name of a table that is about to be altered
82231** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
82232** If the table is a system table, this function leaves an error message
82233** in pParse->zErr (system tables may not be altered) and returns non-zero.
82234**
82235** Or, if zName is not a system table, zero is returned.
82236*/
82237static int isSystemTable(Parse *pParse, const char *zName){
82238  if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
82239    sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
82240    return 1;
82241  }
82242  return 0;
82243}
82244
82245/*
82246** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
82247** command.
82248*/
82249SQLITE_PRIVATE void sqlite3AlterRenameTable(
82250  Parse *pParse,            /* Parser context. */
82251  SrcList *pSrc,            /* The table to rename. */
82252  Token *pName              /* The new table name. */
82253){
82254  int iDb;                  /* Database that contains the table */
82255  char *zDb;                /* Name of database iDb */
82256  Table *pTab;              /* Table being renamed */
82257  char *zName = 0;          /* NULL-terminated version of pName */
82258  sqlite3 *db = pParse->db; /* Database connection */
82259  int nTabName;             /* Number of UTF-8 characters in zTabName */
82260  const char *zTabName;     /* Original name of the table */
82261  Vdbe *v;
82262#ifndef SQLITE_OMIT_TRIGGER
82263  char *zWhere = 0;         /* Where clause to locate temp triggers */
82264#endif
82265  VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
82266  int savedDbFlags;         /* Saved value of db->flags */
82267
82268  savedDbFlags = db->flags;
82269  if( NEVER(db->mallocFailed) ) goto exit_rename_table;
82270  assert( pSrc->nSrc==1 );
82271  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
82272
82273  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
82274  if( !pTab ) goto exit_rename_table;
82275  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
82276  zDb = db->aDb[iDb].zName;
82277  db->flags |= SQLITE_PreferBuiltin;
82278
82279  /* Get a NULL terminated version of the new table name. */
82280  zName = sqlite3NameFromToken(db, pName);
82281  if( !zName ) goto exit_rename_table;
82282
82283  /* Check that a table or index named 'zName' does not already exist
82284  ** in database iDb. If so, this is an error.
82285  */
82286  if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
82287    sqlite3ErrorMsg(pParse,
82288        "there is already another table or index with this name: %s", zName);
82289    goto exit_rename_table;
82290  }
82291
82292  /* Make sure it is not a system table being altered, or a reserved name
82293  ** that the table is being renamed to.
82294  */
82295  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
82296    goto exit_rename_table;
82297  }
82298  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
82299    exit_rename_table;
82300  }
82301
82302#ifndef SQLITE_OMIT_VIEW
82303  if( pTab->pSelect ){
82304    sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
82305    goto exit_rename_table;
82306  }
82307#endif
82308
82309#ifndef SQLITE_OMIT_AUTHORIZATION
82310  /* Invoke the authorization callback. */
82311  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
82312    goto exit_rename_table;
82313  }
82314#endif
82315
82316#ifndef SQLITE_OMIT_VIRTUALTABLE
82317  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
82318    goto exit_rename_table;
82319  }
82320  if( IsVirtual(pTab) ){
82321    pVTab = sqlite3GetVTable(db, pTab);
82322    if( pVTab->pVtab->pModule->xRename==0 ){
82323      pVTab = 0;
82324    }
82325  }
82326#endif
82327
82328  /* Begin a transaction for database iDb.
82329  ** Then modify the schema cookie (since the ALTER TABLE modifies the
82330  ** schema). Open a statement transaction if the table is a virtual
82331  ** table.
82332  */
82333  v = sqlite3GetVdbe(pParse);
82334  if( v==0 ){
82335    goto exit_rename_table;
82336  }
82337  sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
82338  sqlite3ChangeCookie(pParse, iDb);
82339
82340  /* If this is a virtual table, invoke the xRename() function if
82341  ** one is defined. The xRename() callback will modify the names
82342  ** of any resources used by the v-table implementation (including other
82343  ** SQLite tables) that are identified by the name of the virtual table.
82344  */
82345#ifndef SQLITE_OMIT_VIRTUALTABLE
82346  if( pVTab ){
82347    int i = ++pParse->nMem;
82348    sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
82349    sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
82350    sqlite3MayAbort(pParse);
82351  }
82352#endif
82353
82354  /* figure out how many UTF-8 characters are in zName */
82355  zTabName = pTab->zName;
82356  nTabName = sqlite3Utf8CharLen(zTabName, -1);
82357
82358#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
82359  if( db->flags&SQLITE_ForeignKeys ){
82360    /* If foreign-key support is enabled, rewrite the CREATE TABLE
82361    ** statements corresponding to all child tables of foreign key constraints
82362    ** for which the renamed table is the parent table.  */
82363    if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
82364      sqlite3NestedParse(pParse,
82365          "UPDATE \"%w\".%s SET "
82366              "sql = sqlite_rename_parent(sql, %Q, %Q) "
82367              "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
82368      sqlite3DbFree(db, zWhere);
82369    }
82370  }
82371#endif
82372
82373  /* Modify the sqlite_master table to use the new table name. */
82374  sqlite3NestedParse(pParse,
82375      "UPDATE %Q.%s SET "
82376#ifdef SQLITE_OMIT_TRIGGER
82377          "sql = sqlite_rename_table(sql, %Q), "
82378#else
82379          "sql = CASE "
82380            "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
82381            "ELSE sqlite_rename_table(sql, %Q) END, "
82382#endif
82383          "tbl_name = %Q, "
82384          "name = CASE "
82385            "WHEN type='table' THEN %Q "
82386            "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
82387             "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
82388            "ELSE name END "
82389      "WHERE tbl_name=%Q COLLATE nocase AND "
82390          "(type='table' OR type='index' OR type='trigger');",
82391      zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
82392#ifndef SQLITE_OMIT_TRIGGER
82393      zName,
82394#endif
82395      zName, nTabName, zTabName
82396  );
82397
82398#ifndef SQLITE_OMIT_AUTOINCREMENT
82399  /* If the sqlite_sequence table exists in this database, then update
82400  ** it with the new table name.
82401  */
82402  if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
82403    sqlite3NestedParse(pParse,
82404        "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
82405        zDb, zName, pTab->zName);
82406  }
82407#endif
82408
82409#ifndef SQLITE_OMIT_TRIGGER
82410  /* If there are TEMP triggers on this table, modify the sqlite_temp_master
82411  ** table. Don't do this if the table being ALTERed is itself located in
82412  ** the temp database.
82413  */
82414  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
82415    sqlite3NestedParse(pParse,
82416        "UPDATE sqlite_temp_master SET "
82417            "sql = sqlite_rename_trigger(sql, %Q), "
82418            "tbl_name = %Q "
82419            "WHERE %s;", zName, zName, zWhere);
82420    sqlite3DbFree(db, zWhere);
82421  }
82422#endif
82423
82424#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
82425  if( db->flags&SQLITE_ForeignKeys ){
82426    FKey *p;
82427    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
82428      Table *pFrom = p->pFrom;
82429      if( pFrom!=pTab ){
82430        reloadTableSchema(pParse, p->pFrom, pFrom->zName);
82431      }
82432    }
82433  }
82434#endif
82435
82436  /* Drop and reload the internal table schema. */
82437  reloadTableSchema(pParse, pTab, zName);
82438
82439exit_rename_table:
82440  sqlite3SrcListDelete(db, pSrc);
82441  sqlite3DbFree(db, zName);
82442  db->flags = savedDbFlags;
82443}
82444
82445
82446/*
82447** Generate code to make sure the file format number is at least minFormat.
82448** The generated code will increase the file format number if necessary.
82449*/
82450SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
82451  Vdbe *v;
82452  v = sqlite3GetVdbe(pParse);
82453  /* The VDBE should have been allocated before this routine is called.
82454  ** If that allocation failed, we would have quit before reaching this
82455  ** point */
82456  if( ALWAYS(v) ){
82457    int r1 = sqlite3GetTempReg(pParse);
82458    int r2 = sqlite3GetTempReg(pParse);
82459    int j1;
82460    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
82461    sqlite3VdbeUsesBtree(v, iDb);
82462    sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
82463    j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
82464    sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); VdbeCoverage(v);
82465    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
82466    sqlite3VdbeJumpHere(v, j1);
82467    sqlite3ReleaseTempReg(pParse, r1);
82468    sqlite3ReleaseTempReg(pParse, r2);
82469  }
82470}
82471
82472/*
82473** This function is called after an "ALTER TABLE ... ADD" statement
82474** has been parsed. Argument pColDef contains the text of the new
82475** column definition.
82476**
82477** The Table structure pParse->pNewTable was extended to include
82478** the new column during parsing.
82479*/
82480SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
82481  Table *pNew;              /* Copy of pParse->pNewTable */
82482  Table *pTab;              /* Table being altered */
82483  int iDb;                  /* Database number */
82484  const char *zDb;          /* Database name */
82485  const char *zTab;         /* Table name */
82486  char *zCol;               /* Null-terminated column definition */
82487  Column *pCol;             /* The new column */
82488  Expr *pDflt;              /* Default value for the new column */
82489  sqlite3 *db;              /* The database connection; */
82490
82491  db = pParse->db;
82492  if( pParse->nErr || db->mallocFailed ) return;
82493  pNew = pParse->pNewTable;
82494  assert( pNew );
82495
82496  assert( sqlite3BtreeHoldsAllMutexes(db) );
82497  iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
82498  zDb = db->aDb[iDb].zName;
82499  zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
82500  pCol = &pNew->aCol[pNew->nCol-1];
82501  pDflt = pCol->pDflt;
82502  pTab = sqlite3FindTable(db, zTab, zDb);
82503  assert( pTab );
82504
82505#ifndef SQLITE_OMIT_AUTHORIZATION
82506  /* Invoke the authorization callback. */
82507  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
82508    return;
82509  }
82510#endif
82511
82512  /* If the default value for the new column was specified with a
82513  ** literal NULL, then set pDflt to 0. This simplifies checking
82514  ** for an SQL NULL default below.
82515  */
82516  if( pDflt && pDflt->op==TK_NULL ){
82517    pDflt = 0;
82518  }
82519
82520  /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
82521  ** If there is a NOT NULL constraint, then the default value for the
82522  ** column must not be NULL.
82523  */
82524  if( pCol->colFlags & COLFLAG_PRIMKEY ){
82525    sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
82526    return;
82527  }
82528  if( pNew->pIndex ){
82529    sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
82530    return;
82531  }
82532  if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
82533    sqlite3ErrorMsg(pParse,
82534        "Cannot add a REFERENCES column with non-NULL default value");
82535    return;
82536  }
82537  if( pCol->notNull && !pDflt ){
82538    sqlite3ErrorMsg(pParse,
82539        "Cannot add a NOT NULL column with default value NULL");
82540    return;
82541  }
82542
82543  /* Ensure the default expression is something that sqlite3ValueFromExpr()
82544  ** can handle (i.e. not CURRENT_TIME etc.)
82545  */
82546  if( pDflt ){
82547    sqlite3_value *pVal = 0;
82548    if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
82549      db->mallocFailed = 1;
82550      return;
82551    }
82552    if( !pVal ){
82553      sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
82554      return;
82555    }
82556    sqlite3ValueFree(pVal);
82557  }
82558
82559  /* Modify the CREATE TABLE statement. */
82560  zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
82561  if( zCol ){
82562    char *zEnd = &zCol[pColDef->n-1];
82563    int savedDbFlags = db->flags;
82564    while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
82565      *zEnd-- = '\0';
82566    }
82567    db->flags |= SQLITE_PreferBuiltin;
82568    sqlite3NestedParse(pParse,
82569        "UPDATE \"%w\".%s SET "
82570          "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
82571        "WHERE type = 'table' AND name = %Q",
82572      zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
82573      zTab
82574    );
82575    sqlite3DbFree(db, zCol);
82576    db->flags = savedDbFlags;
82577  }
82578
82579  /* If the default value of the new column is NULL, then set the file
82580  ** format to 2. If the default value of the new column is not NULL,
82581  ** the file format becomes 3.
82582  */
82583  sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
82584
82585  /* Reload the schema of the modified table. */
82586  reloadTableSchema(pParse, pTab, pTab->zName);
82587}
82588
82589/*
82590** This function is called by the parser after the table-name in
82591** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
82592** pSrc is the full-name of the table being altered.
82593**
82594** This routine makes a (partial) copy of the Table structure
82595** for the table being altered and sets Parse.pNewTable to point
82596** to it. Routines called by the parser as the column definition
82597** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
82598** the copy. The copy of the Table structure is deleted by tokenize.c
82599** after parsing is finished.
82600**
82601** Routine sqlite3AlterFinishAddColumn() will be called to complete
82602** coding the "ALTER TABLE ... ADD" statement.
82603*/
82604SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
82605  Table *pNew;
82606  Table *pTab;
82607  Vdbe *v;
82608  int iDb;
82609  int i;
82610  int nAlloc;
82611  sqlite3 *db = pParse->db;
82612
82613  /* Look up the table being altered. */
82614  assert( pParse->pNewTable==0 );
82615  assert( sqlite3BtreeHoldsAllMutexes(db) );
82616  if( db->mallocFailed ) goto exit_begin_add_column;
82617  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
82618  if( !pTab ) goto exit_begin_add_column;
82619
82620#ifndef SQLITE_OMIT_VIRTUALTABLE
82621  if( IsVirtual(pTab) ){
82622    sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
82623    goto exit_begin_add_column;
82624  }
82625#endif
82626
82627  /* Make sure this is not an attempt to ALTER a view. */
82628  if( pTab->pSelect ){
82629    sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
82630    goto exit_begin_add_column;
82631  }
82632  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
82633    goto exit_begin_add_column;
82634  }
82635
82636  assert( pTab->addColOffset>0 );
82637  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
82638
82639  /* Put a copy of the Table struct in Parse.pNewTable for the
82640  ** sqlite3AddColumn() function and friends to modify.  But modify
82641  ** the name by adding an "sqlite_altertab_" prefix.  By adding this
82642  ** prefix, we insure that the name will not collide with an existing
82643  ** table because user table are not allowed to have the "sqlite_"
82644  ** prefix on their name.
82645  */
82646  pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
82647  if( !pNew ) goto exit_begin_add_column;
82648  pParse->pNewTable = pNew;
82649  pNew->nRef = 1;
82650  pNew->nCol = pTab->nCol;
82651  assert( pNew->nCol>0 );
82652  nAlloc = (((pNew->nCol-1)/8)*8)+8;
82653  assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
82654  pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
82655  pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
82656  if( !pNew->aCol || !pNew->zName ){
82657    db->mallocFailed = 1;
82658    goto exit_begin_add_column;
82659  }
82660  memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
82661  for(i=0; i<pNew->nCol; i++){
82662    Column *pCol = &pNew->aCol[i];
82663    pCol->zName = sqlite3DbStrDup(db, pCol->zName);
82664    pCol->zColl = 0;
82665    pCol->zType = 0;
82666    pCol->pDflt = 0;
82667    pCol->zDflt = 0;
82668  }
82669  pNew->pSchema = db->aDb[iDb].pSchema;
82670  pNew->addColOffset = pTab->addColOffset;
82671  pNew->nRef = 1;
82672
82673  /* Begin a transaction and increment the schema cookie.  */
82674  sqlite3BeginWriteOperation(pParse, 0, iDb);
82675  v = sqlite3GetVdbe(pParse);
82676  if( !v ) goto exit_begin_add_column;
82677  sqlite3ChangeCookie(pParse, iDb);
82678
82679exit_begin_add_column:
82680  sqlite3SrcListDelete(db, pSrc);
82681  return;
82682}
82683#endif  /* SQLITE_ALTER_TABLE */
82684
82685/************** End of alter.c ***********************************************/
82686/************** Begin file analyze.c *****************************************/
82687/*
82688** 2005-07-08
82689**
82690** The author disclaims copyright to this source code.  In place of
82691** a legal notice, here is a blessing:
82692**
82693**    May you do good and not evil.
82694**    May you find forgiveness for yourself and forgive others.
82695**    May you share freely, never taking more than you give.
82696**
82697*************************************************************************
82698** This file contains code associated with the ANALYZE command.
82699**
82700** The ANALYZE command gather statistics about the content of tables
82701** and indices.  These statistics are made available to the query planner
82702** to help it make better decisions about how to perform queries.
82703**
82704** The following system tables are or have been supported:
82705**
82706**    CREATE TABLE sqlite_stat1(tbl, idx, stat);
82707**    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
82708**    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
82709**    CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
82710**
82711** Additional tables might be added in future releases of SQLite.
82712** The sqlite_stat2 table is not created or used unless the SQLite version
82713** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
82714** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
82715** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
82716** created and used by SQLite versions 3.7.9 and later and with
82717** SQLITE_ENABLE_STAT3 defined.  The functionality of sqlite_stat3
82718** is a superset of sqlite_stat2.  The sqlite_stat4 is an enhanced
82719** version of sqlite_stat3 and is only available when compiled with
82720** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later.  It is
82721** not possible to enable both STAT3 and STAT4 at the same time.  If they
82722** are both enabled, then STAT4 takes precedence.
82723**
82724** For most applications, sqlite_stat1 provides all the statisics required
82725** for the query planner to make good choices.
82726**
82727** Format of sqlite_stat1:
82728**
82729** There is normally one row per index, with the index identified by the
82730** name in the idx column.  The tbl column is the name of the table to
82731** which the index belongs.  In each such row, the stat column will be
82732** a string consisting of a list of integers.  The first integer in this
82733** list is the number of rows in the index.  (This is the same as the
82734** number of rows in the table, except for partial indices.)  The second
82735** integer is the average number of rows in the index that have the same
82736** value in the first column of the index.  The third integer is the average
82737** number of rows in the index that have the same value for the first two
82738** columns.  The N-th integer (for N>1) is the average number of rows in
82739** the index which have the same value for the first N-1 columns.  For
82740** a K-column index, there will be K+1 integers in the stat column.  If
82741** the index is unique, then the last integer will be 1.
82742**
82743** The list of integers in the stat column can optionally be followed
82744** by the keyword "unordered".  The "unordered" keyword, if it is present,
82745** must be separated from the last integer by a single space.  If the
82746** "unordered" keyword is present, then the query planner assumes that
82747** the index is unordered and will not use the index for a range query.
82748**
82749** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
82750** column contains a single integer which is the (estimated) number of
82751** rows in the table identified by sqlite_stat1.tbl.
82752**
82753** Format of sqlite_stat2:
82754**
82755** The sqlite_stat2 is only created and is only used if SQLite is compiled
82756** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
82757** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
82758** about the distribution of keys within an index.  The index is identified by
82759** the "idx" column and the "tbl" column is the name of the table to which
82760** the index belongs.  There are usually 10 rows in the sqlite_stat2
82761** table for each index.
82762**
82763** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
82764** inclusive are samples of the left-most key value in the index taken at
82765** evenly spaced points along the index.  Let the number of samples be S
82766** (10 in the standard build) and let C be the number of rows in the index.
82767** Then the sampled rows are given by:
82768**
82769**     rownumber = (i*C*2 + C)/(S*2)
82770**
82771** For i between 0 and S-1.  Conceptually, the index space is divided into
82772** S uniform buckets and the samples are the middle row from each bucket.
82773**
82774** The format for sqlite_stat2 is recorded here for legacy reference.  This
82775** version of SQLite does not support sqlite_stat2.  It neither reads nor
82776** writes the sqlite_stat2 table.  This version of SQLite only supports
82777** sqlite_stat3.
82778**
82779** Format for sqlite_stat3:
82780**
82781** The sqlite_stat3 format is a subset of sqlite_stat4.  Hence, the
82782** sqlite_stat4 format will be described first.  Further information
82783** about sqlite_stat3 follows the sqlite_stat4 description.
82784**
82785** Format for sqlite_stat4:
82786**
82787** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
82788** to aid the query planner in choosing good indices based on the values
82789** that indexed columns are compared against in the WHERE clauses of
82790** queries.
82791**
82792** The sqlite_stat4 table contains multiple entries for each index.
82793** The idx column names the index and the tbl column is the table of the
82794** index.  If the idx and tbl columns are the same, then the sample is
82795** of the INTEGER PRIMARY KEY.  The sample column is a blob which is the
82796** binary encoding of a key from the index.  The nEq column is a
82797** list of integers.  The first integer is the approximate number
82798** of entries in the index whose left-most column exactly matches
82799** the left-most column of the sample.  The second integer in nEq
82800** is the approximate number of entries in the index where the
82801** first two columns match the first two columns of the sample.
82802** And so forth.  nLt is another list of integers that show the approximate
82803** number of entries that are strictly less than the sample.  The first
82804** integer in nLt contains the number of entries in the index where the
82805** left-most column is less than the left-most column of the sample.
82806** The K-th integer in the nLt entry is the number of index entries
82807** where the first K columns are less than the first K columns of the
82808** sample.  The nDLt column is like nLt except that it contains the
82809** number of distinct entries in the index that are less than the
82810** sample.
82811**
82812** There can be an arbitrary number of sqlite_stat4 entries per index.
82813** The ANALYZE command will typically generate sqlite_stat4 tables
82814** that contain between 10 and 40 samples which are distributed across
82815** the key space, though not uniformly, and which include samples with
82816** large nEq values.
82817**
82818** Format for sqlite_stat3 redux:
82819**
82820** The sqlite_stat3 table is like sqlite_stat4 except that it only
82821** looks at the left-most column of the index.  The sqlite_stat3.sample
82822** column contains the actual value of the left-most column instead
82823** of a blob encoding of the complete index key as is found in
82824** sqlite_stat4.sample.  The nEq, nLt, and nDLt entries of sqlite_stat3
82825** all contain just a single integer which is the same as the first
82826** integer in the equivalent columns in sqlite_stat4.
82827*/
82828#ifndef SQLITE_OMIT_ANALYZE
82829
82830#if defined(SQLITE_ENABLE_STAT4)
82831# define IsStat4     1
82832# define IsStat3     0
82833#elif defined(SQLITE_ENABLE_STAT3)
82834# define IsStat4     0
82835# define IsStat3     1
82836#else
82837# define IsStat4     0
82838# define IsStat3     0
82839# undef SQLITE_STAT4_SAMPLES
82840# define SQLITE_STAT4_SAMPLES 1
82841#endif
82842#define IsStat34    (IsStat3+IsStat4)  /* 1 for STAT3 or STAT4. 0 otherwise */
82843
82844/*
82845** This routine generates code that opens the sqlite_statN tables.
82846** The sqlite_stat1 table is always relevant.  sqlite_stat2 is now
82847** obsolete.  sqlite_stat3 and sqlite_stat4 are only opened when
82848** appropriate compile-time options are provided.
82849**
82850** If the sqlite_statN tables do not previously exist, it is created.
82851**
82852** Argument zWhere may be a pointer to a buffer containing a table name,
82853** or it may be a NULL pointer. If it is not NULL, then all entries in
82854** the sqlite_statN tables associated with the named table are deleted.
82855** If zWhere==0, then code is generated to delete all stat table entries.
82856*/
82857static void openStatTable(
82858  Parse *pParse,          /* Parsing context */
82859  int iDb,                /* The database we are looking in */
82860  int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
82861  const char *zWhere,     /* Delete entries for this table or index */
82862  const char *zWhereType  /* Either "tbl" or "idx" */
82863){
82864  static const struct {
82865    const char *zName;
82866    const char *zCols;
82867  } aTable[] = {
82868    { "sqlite_stat1", "tbl,idx,stat" },
82869#if defined(SQLITE_ENABLE_STAT4)
82870    { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
82871    { "sqlite_stat3", 0 },
82872#elif defined(SQLITE_ENABLE_STAT3)
82873    { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
82874    { "sqlite_stat4", 0 },
82875#else
82876    { "sqlite_stat3", 0 },
82877    { "sqlite_stat4", 0 },
82878#endif
82879  };
82880  int i;
82881  sqlite3 *db = pParse->db;
82882  Db *pDb;
82883  Vdbe *v = sqlite3GetVdbe(pParse);
82884  int aRoot[ArraySize(aTable)];
82885  u8 aCreateTbl[ArraySize(aTable)];
82886
82887  if( v==0 ) return;
82888  assert( sqlite3BtreeHoldsAllMutexes(db) );
82889  assert( sqlite3VdbeDb(v)==db );
82890  pDb = &db->aDb[iDb];
82891
82892  /* Create new statistic tables if they do not exist, or clear them
82893  ** if they do already exist.
82894  */
82895  for(i=0; i<ArraySize(aTable); i++){
82896    const char *zTab = aTable[i].zName;
82897    Table *pStat;
82898    if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
82899      if( aTable[i].zCols ){
82900        /* The sqlite_statN table does not exist. Create it. Note that a
82901        ** side-effect of the CREATE TABLE statement is to leave the rootpage
82902        ** of the new table in register pParse->regRoot. This is important
82903        ** because the OpenWrite opcode below will be needing it. */
82904        sqlite3NestedParse(pParse,
82905            "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
82906        );
82907        aRoot[i] = pParse->regRoot;
82908        aCreateTbl[i] = OPFLAG_P2ISREG;
82909      }
82910    }else{
82911      /* The table already exists. If zWhere is not NULL, delete all entries
82912      ** associated with the table zWhere. If zWhere is NULL, delete the
82913      ** entire contents of the table. */
82914      aRoot[i] = pStat->tnum;
82915      aCreateTbl[i] = 0;
82916      sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
82917      if( zWhere ){
82918        sqlite3NestedParse(pParse,
82919           "DELETE FROM %Q.%s WHERE %s=%Q",
82920           pDb->zName, zTab, zWhereType, zWhere
82921        );
82922      }else{
82923        /* The sqlite_stat[134] table already exists.  Delete all rows. */
82924        sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
82925      }
82926    }
82927  }
82928
82929  /* Open the sqlite_stat[134] tables for writing. */
82930  for(i=0; aTable[i].zCols; i++){
82931    assert( i<ArraySize(aTable) );
82932    sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
82933    sqlite3VdbeChangeP5(v, aCreateTbl[i]);
82934  }
82935}
82936
82937/*
82938** Recommended number of samples for sqlite_stat4
82939*/
82940#ifndef SQLITE_STAT4_SAMPLES
82941# define SQLITE_STAT4_SAMPLES 24
82942#endif
82943
82944/*
82945** Three SQL functions - stat_init(), stat_push(), and stat_get() -
82946** share an instance of the following structure to hold their state
82947** information.
82948*/
82949typedef struct Stat4Accum Stat4Accum;
82950typedef struct Stat4Sample Stat4Sample;
82951struct Stat4Sample {
82952  tRowcnt *anEq;                  /* sqlite_stat4.nEq */
82953  tRowcnt *anDLt;                 /* sqlite_stat4.nDLt */
82954#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
82955  tRowcnt *anLt;                  /* sqlite_stat4.nLt */
82956  union {
82957    i64 iRowid;                     /* Rowid in main table of the key */
82958    u8 *aRowid;                     /* Key for WITHOUT ROWID tables */
82959  } u;
82960  u32 nRowid;                     /* Sizeof aRowid[] */
82961  u8 isPSample;                   /* True if a periodic sample */
82962  int iCol;                       /* If !isPSample, the reason for inclusion */
82963  u32 iHash;                      /* Tiebreaker hash */
82964#endif
82965};
82966struct Stat4Accum {
82967  tRowcnt nRow;             /* Number of rows in the entire table */
82968  tRowcnt nPSample;         /* How often to do a periodic sample */
82969  int nCol;                 /* Number of columns in index + rowid */
82970  int mxSample;             /* Maximum number of samples to accumulate */
82971  Stat4Sample current;      /* Current row as a Stat4Sample */
82972  u32 iPrn;                 /* Pseudo-random number used for sampling */
82973  Stat4Sample *aBest;       /* Array of nCol best samples */
82974  int iMin;                 /* Index in a[] of entry with minimum score */
82975  int nSample;              /* Current number of samples */
82976  int iGet;                 /* Index of current sample accessed by stat_get() */
82977  Stat4Sample *a;           /* Array of mxSample Stat4Sample objects */
82978  sqlite3 *db;              /* Database connection, for malloc() */
82979};
82980
82981/* Reclaim memory used by a Stat4Sample
82982*/
82983#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
82984static void sampleClear(sqlite3 *db, Stat4Sample *p){
82985  assert( db!=0 );
82986  if( p->nRowid ){
82987    sqlite3DbFree(db, p->u.aRowid);
82988    p->nRowid = 0;
82989  }
82990}
82991#endif
82992
82993/* Initialize the BLOB value of a ROWID
82994*/
82995#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
82996static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
82997  assert( db!=0 );
82998  if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
82999  p->u.aRowid = sqlite3DbMallocRaw(db, n);
83000  if( p->u.aRowid ){
83001    p->nRowid = n;
83002    memcpy(p->u.aRowid, pData, n);
83003  }else{
83004    p->nRowid = 0;
83005  }
83006}
83007#endif
83008
83009/* Initialize the INTEGER value of a ROWID.
83010*/
83011#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
83012static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
83013  assert( db!=0 );
83014  if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
83015  p->nRowid = 0;
83016  p->u.iRowid = iRowid;
83017}
83018#endif
83019
83020
83021/*
83022** Copy the contents of object (*pFrom) into (*pTo).
83023*/
83024#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
83025static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
83026  pTo->isPSample = pFrom->isPSample;
83027  pTo->iCol = pFrom->iCol;
83028  pTo->iHash = pFrom->iHash;
83029  memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
83030  memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
83031  memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
83032  if( pFrom->nRowid ){
83033    sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
83034  }else{
83035    sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
83036  }
83037}
83038#endif
83039
83040/*
83041** Reclaim all memory of a Stat4Accum structure.
83042*/
83043static void stat4Destructor(void *pOld){
83044  Stat4Accum *p = (Stat4Accum*)pOld;
83045#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
83046  int i;
83047  for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
83048  for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
83049  sampleClear(p->db, &p->current);
83050#endif
83051  sqlite3DbFree(p->db, p);
83052}
83053
83054/*
83055** Implementation of the stat_init(N,C) SQL function. The two parameters
83056** are the number of rows in the table or index (C) and the number of columns
83057** in the index (N).  The second argument (C) is only used for STAT3 and STAT4.
83058**
83059** This routine allocates the Stat4Accum object in heap memory. The return
83060** value is a pointer to the the Stat4Accum object encoded as a blob (i.e.
83061** the size of the blob is sizeof(void*) bytes).
83062*/
83063static void statInit(
83064  sqlite3_context *context,
83065  int argc,
83066  sqlite3_value **argv
83067){
83068  Stat4Accum *p;
83069  int nCol;                       /* Number of columns in index being sampled */
83070  int nColUp;                     /* nCol rounded up for alignment */
83071  int n;                          /* Bytes of space to allocate */
83072  sqlite3 *db;                    /* Database connection */
83073#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
83074  int mxSample = SQLITE_STAT4_SAMPLES;
83075#endif
83076
83077  /* Decode the three function arguments */
83078  UNUSED_PARAMETER(argc);
83079  nCol = sqlite3_value_int(argv[0]);
83080  assert( nCol>1 );               /* >1 because it includes the rowid column */
83081  nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
83082
83083  /* Allocate the space required for the Stat4Accum object */
83084  n = sizeof(*p)
83085    + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anEq */
83086    + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anDLt */
83087#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
83088    + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anLt */
83089    + sizeof(Stat4Sample)*(nCol+mxSample)     /* Stat4Accum.aBest[], a[] */
83090    + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
83091#endif
83092  ;
83093  db = sqlite3_context_db_handle(context);
83094  p = sqlite3DbMallocZero(db, n);
83095  if( p==0 ){
83096    sqlite3_result_error_nomem(context);
83097    return;
83098  }
83099
83100  p->db = db;
83101  p->nRow = 0;
83102  p->nCol = nCol;
83103  p->current.anDLt = (tRowcnt*)&p[1];
83104  p->current.anEq = &p->current.anDLt[nColUp];
83105
83106#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
83107  {
83108    u8 *pSpace;                     /* Allocated space not yet assigned */
83109    int i;                          /* Used to iterate through p->aSample[] */
83110
83111    p->iGet = -1;
83112    p->mxSample = mxSample;
83113    p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[1])/(mxSample/3+1) + 1);
83114    p->current.anLt = &p->current.anEq[nColUp];
83115    p->iPrn = nCol*0x689e962d ^ sqlite3_value_int(argv[1])*0xd0944565;
83116
83117    /* Set up the Stat4Accum.a[] and aBest[] arrays */
83118    p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
83119    p->aBest = &p->a[mxSample];
83120    pSpace = (u8*)(&p->a[mxSample+nCol]);
83121    for(i=0; i<(mxSample+nCol); i++){
83122      p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
83123      p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
83124      p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
83125    }
83126    assert( (pSpace - (u8*)p)==n );
83127
83128    for(i=0; i<nCol; i++){
83129      p->aBest[i].iCol = i;
83130    }
83131  }
83132#endif
83133
83134  /* Return a pointer to the allocated object to the caller */
83135  sqlite3_result_blob(context, p, sizeof(p), stat4Destructor);
83136}
83137static const FuncDef statInitFuncdef = {
83138  1+IsStat34,      /* nArg */
83139  SQLITE_UTF8,     /* funcFlags */
83140  0,               /* pUserData */
83141  0,               /* pNext */
83142  statInit,        /* xFunc */
83143  0,               /* xStep */
83144  0,               /* xFinalize */
83145  "stat_init",     /* zName */
83146  0,               /* pHash */
83147  0                /* pDestructor */
83148};
83149
83150#ifdef SQLITE_ENABLE_STAT4
83151/*
83152** pNew and pOld are both candidate non-periodic samples selected for
83153** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
83154** considering only any trailing columns and the sample hash value, this
83155** function returns true if sample pNew is to be preferred over pOld.
83156** In other words, if we assume that the cardinalities of the selected
83157** column for pNew and pOld are equal, is pNew to be preferred over pOld.
83158**
83159** This function assumes that for each argument sample, the contents of
83160** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
83161*/
83162static int sampleIsBetterPost(
83163  Stat4Accum *pAccum,
83164  Stat4Sample *pNew,
83165  Stat4Sample *pOld
83166){
83167  int nCol = pAccum->nCol;
83168  int i;
83169  assert( pNew->iCol==pOld->iCol );
83170  for(i=pNew->iCol+1; i<nCol; i++){
83171    if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
83172    if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
83173  }
83174  if( pNew->iHash>pOld->iHash ) return 1;
83175  return 0;
83176}
83177#endif
83178
83179#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
83180/*
83181** Return true if pNew is to be preferred over pOld.
83182**
83183** This function assumes that for each argument sample, the contents of
83184** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
83185*/
83186static int sampleIsBetter(
83187  Stat4Accum *pAccum,
83188  Stat4Sample *pNew,
83189  Stat4Sample *pOld
83190){
83191  tRowcnt nEqNew = pNew->anEq[pNew->iCol];
83192  tRowcnt nEqOld = pOld->anEq[pOld->iCol];
83193
83194  assert( pOld->isPSample==0 && pNew->isPSample==0 );
83195  assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
83196
83197  if( (nEqNew>nEqOld) ) return 1;
83198#ifdef SQLITE_ENABLE_STAT4
83199  if( nEqNew==nEqOld ){
83200    if( pNew->iCol<pOld->iCol ) return 1;
83201    return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
83202  }
83203  return 0;
83204#else
83205  return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
83206#endif
83207}
83208
83209/*
83210** Copy the contents of sample *pNew into the p->a[] array. If necessary,
83211** remove the least desirable sample from p->a[] to make room.
83212*/
83213static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
83214  Stat4Sample *pSample = 0;
83215  int i;
83216
83217  assert( IsStat4 || nEqZero==0 );
83218
83219#ifdef SQLITE_ENABLE_STAT4
83220  if( pNew->isPSample==0 ){
83221    Stat4Sample *pUpgrade = 0;
83222    assert( pNew->anEq[pNew->iCol]>0 );
83223
83224    /* This sample is being added because the prefix that ends in column
83225    ** iCol occurs many times in the table. However, if we have already
83226    ** added a sample that shares this prefix, there is no need to add
83227    ** this one. Instead, upgrade the priority of the highest priority
83228    ** existing sample that shares this prefix.  */
83229    for(i=p->nSample-1; i>=0; i--){
83230      Stat4Sample *pOld = &p->a[i];
83231      if( pOld->anEq[pNew->iCol]==0 ){
83232        if( pOld->isPSample ) return;
83233        assert( pOld->iCol>pNew->iCol );
83234        assert( sampleIsBetter(p, pNew, pOld) );
83235        if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
83236          pUpgrade = pOld;
83237        }
83238      }
83239    }
83240    if( pUpgrade ){
83241      pUpgrade->iCol = pNew->iCol;
83242      pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
83243      goto find_new_min;
83244    }
83245  }
83246#endif
83247
83248  /* If necessary, remove sample iMin to make room for the new sample. */
83249  if( p->nSample>=p->mxSample ){
83250    Stat4Sample *pMin = &p->a[p->iMin];
83251    tRowcnt *anEq = pMin->anEq;
83252    tRowcnt *anLt = pMin->anLt;
83253    tRowcnt *anDLt = pMin->anDLt;
83254    sampleClear(p->db, pMin);
83255    memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
83256    pSample = &p->a[p->nSample-1];
83257    pSample->nRowid = 0;
83258    pSample->anEq = anEq;
83259    pSample->anDLt = anDLt;
83260    pSample->anLt = anLt;
83261    p->nSample = p->mxSample-1;
83262  }
83263
83264  /* The "rows less-than" for the rowid column must be greater than that
83265  ** for the last sample in the p->a[] array. Otherwise, the samples would
83266  ** be out of order. */
83267#ifdef SQLITE_ENABLE_STAT4
83268  assert( p->nSample==0
83269       || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
83270#endif
83271
83272  /* Insert the new sample */
83273  pSample = &p->a[p->nSample];
83274  sampleCopy(p, pSample, pNew);
83275  p->nSample++;
83276
83277  /* Zero the first nEqZero entries in the anEq[] array. */
83278  memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
83279
83280#ifdef SQLITE_ENABLE_STAT4
83281 find_new_min:
83282#endif
83283  if( p->nSample>=p->mxSample ){
83284    int iMin = -1;
83285    for(i=0; i<p->mxSample; i++){
83286      if( p->a[i].isPSample ) continue;
83287      if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
83288        iMin = i;
83289      }
83290    }
83291    assert( iMin>=0 );
83292    p->iMin = iMin;
83293  }
83294}
83295#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
83296
83297/*
83298** Field iChng of the index being scanned has changed. So at this point
83299** p->current contains a sample that reflects the previous row of the
83300** index. The value of anEq[iChng] and subsequent anEq[] elements are
83301** correct at this point.
83302*/
83303static void samplePushPrevious(Stat4Accum *p, int iChng){
83304#ifdef SQLITE_ENABLE_STAT4
83305  int i;
83306
83307  /* Check if any samples from the aBest[] array should be pushed
83308  ** into IndexSample.a[] at this point.  */
83309  for(i=(p->nCol-2); i>=iChng; i--){
83310    Stat4Sample *pBest = &p->aBest[i];
83311    pBest->anEq[i] = p->current.anEq[i];
83312    if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
83313      sampleInsert(p, pBest, i);
83314    }
83315  }
83316
83317  /* Update the anEq[] fields of any samples already collected. */
83318  for(i=p->nSample-1; i>=0; i--){
83319    int j;
83320    for(j=iChng; j<p->nCol; j++){
83321      if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
83322    }
83323  }
83324#endif
83325
83326#if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
83327  if( iChng==0 ){
83328    tRowcnt nLt = p->current.anLt[0];
83329    tRowcnt nEq = p->current.anEq[0];
83330
83331    /* Check if this is to be a periodic sample. If so, add it. */
83332    if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
83333      p->current.isPSample = 1;
83334      sampleInsert(p, &p->current, 0);
83335      p->current.isPSample = 0;
83336    }else
83337
83338    /* Or if it is a non-periodic sample. Add it in this case too. */
83339    if( p->nSample<p->mxSample
83340     || sampleIsBetter(p, &p->current, &p->a[p->iMin])
83341    ){
83342      sampleInsert(p, &p->current, 0);
83343    }
83344  }
83345#endif
83346
83347#ifndef SQLITE_ENABLE_STAT3_OR_STAT4
83348  UNUSED_PARAMETER( p );
83349  UNUSED_PARAMETER( iChng );
83350#endif
83351}
83352
83353/*
83354** Implementation of the stat_push SQL function:  stat_push(P,C,R)
83355** Arguments:
83356**
83357**    P     Pointer to the Stat4Accum object created by stat_init()
83358**    C     Index of left-most column to differ from previous row
83359**    R     Rowid for the current row.  Might be a key record for
83360**          WITHOUT ROWID tables.
83361**
83362** The SQL function always returns NULL.
83363**
83364** The R parameter is only used for STAT3 and STAT4
83365*/
83366static void statPush(
83367  sqlite3_context *context,
83368  int argc,
83369  sqlite3_value **argv
83370){
83371  int i;
83372
83373  /* The three function arguments */
83374  Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
83375  int iChng = sqlite3_value_int(argv[1]);
83376
83377  UNUSED_PARAMETER( argc );
83378  UNUSED_PARAMETER( context );
83379  assert( p->nCol>1 );        /* Includes rowid field */
83380  assert( iChng<p->nCol );
83381
83382  if( p->nRow==0 ){
83383    /* This is the first call to this function. Do initialization. */
83384    for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
83385  }else{
83386    /* Second and subsequent calls get processed here */
83387    samplePushPrevious(p, iChng);
83388
83389    /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
83390    ** to the current row of the index. */
83391    for(i=0; i<iChng; i++){
83392      p->current.anEq[i]++;
83393    }
83394    for(i=iChng; i<p->nCol; i++){
83395      p->current.anDLt[i]++;
83396#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
83397      p->current.anLt[i] += p->current.anEq[i];
83398#endif
83399      p->current.anEq[i] = 1;
83400    }
83401  }
83402  p->nRow++;
83403#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
83404  if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
83405    sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
83406  }else{
83407    sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
83408                                       sqlite3_value_blob(argv[2]));
83409  }
83410  p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
83411#endif
83412
83413#ifdef SQLITE_ENABLE_STAT4
83414  {
83415    tRowcnt nLt = p->current.anLt[p->nCol-1];
83416
83417    /* Check if this is to be a periodic sample. If so, add it. */
83418    if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
83419      p->current.isPSample = 1;
83420      p->current.iCol = 0;
83421      sampleInsert(p, &p->current, p->nCol-1);
83422      p->current.isPSample = 0;
83423    }
83424
83425    /* Update the aBest[] array. */
83426    for(i=0; i<(p->nCol-1); i++){
83427      p->current.iCol = i;
83428      if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
83429        sampleCopy(p, &p->aBest[i], &p->current);
83430      }
83431    }
83432  }
83433#endif
83434}
83435static const FuncDef statPushFuncdef = {
83436  2+IsStat34,      /* nArg */
83437  SQLITE_UTF8,     /* funcFlags */
83438  0,               /* pUserData */
83439  0,               /* pNext */
83440  statPush,        /* xFunc */
83441  0,               /* xStep */
83442  0,               /* xFinalize */
83443  "stat_push",     /* zName */
83444  0,               /* pHash */
83445  0                /* pDestructor */
83446};
83447
83448#define STAT_GET_STAT1 0          /* "stat" column of stat1 table */
83449#define STAT_GET_ROWID 1          /* "rowid" column of stat[34] entry */
83450#define STAT_GET_NEQ   2          /* "neq" column of stat[34] entry */
83451#define STAT_GET_NLT   3          /* "nlt" column of stat[34] entry */
83452#define STAT_GET_NDLT  4          /* "ndlt" column of stat[34] entry */
83453
83454/*
83455** Implementation of the stat_get(P,J) SQL function.  This routine is
83456** used to query the results.  Content is returned for parameter J
83457** which is one of the STAT_GET_xxxx values defined above.
83458**
83459** If neither STAT3 nor STAT4 are enabled, then J is always
83460** STAT_GET_STAT1 and is hence omitted and this routine becomes
83461** a one-parameter function, stat_get(P), that always returns the
83462** stat1 table entry information.
83463*/
83464static void statGet(
83465  sqlite3_context *context,
83466  int argc,
83467  sqlite3_value **argv
83468){
83469  Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
83470#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
83471  /* STAT3 and STAT4 have a parameter on this routine. */
83472  int eCall = sqlite3_value_int(argv[1]);
83473  assert( argc==2 );
83474  assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
83475       || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
83476       || eCall==STAT_GET_NDLT
83477  );
83478  if( eCall==STAT_GET_STAT1 )
83479#else
83480  assert( argc==1 );
83481#endif
83482  {
83483    /* Return the value to store in the "stat" column of the sqlite_stat1
83484    ** table for this index.
83485    **
83486    ** The value is a string composed of a list of integers describing
83487    ** the index. The first integer in the list is the total number of
83488    ** entries in the index. There is one additional integer in the list
83489    ** for each indexed column. This additional integer is an estimate of
83490    ** the number of rows matched by a stabbing query on the index using
83491    ** a key with the corresponding number of fields. In other words,
83492    ** if the index is on columns (a,b) and the sqlite_stat1 value is
83493    ** "100 10 2", then SQLite estimates that:
83494    **
83495    **   * the index contains 100 rows,
83496    **   * "WHERE a=?" matches 10 rows, and
83497    **   * "WHERE a=? AND b=?" matches 2 rows.
83498    **
83499    ** If D is the count of distinct values and K is the total number of
83500    ** rows, then each estimate is computed as:
83501    **
83502    **        I = (K+D-1)/D
83503    */
83504    char *z;
83505    int i;
83506
83507    char *zRet = sqlite3MallocZero(p->nCol * 25);
83508    if( zRet==0 ){
83509      sqlite3_result_error_nomem(context);
83510      return;
83511    }
83512
83513    sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
83514    z = zRet + sqlite3Strlen30(zRet);
83515    for(i=0; i<(p->nCol-1); i++){
83516      u64 nDistinct = p->current.anDLt[i] + 1;
83517      u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
83518      sqlite3_snprintf(24, z, " %llu", iVal);
83519      z += sqlite3Strlen30(z);
83520      assert( p->current.anEq[i] );
83521    }
83522    assert( z[0]=='\0' && z>zRet );
83523
83524    sqlite3_result_text(context, zRet, -1, sqlite3_free);
83525  }
83526#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
83527  else if( eCall==STAT_GET_ROWID ){
83528    if( p->iGet<0 ){
83529      samplePushPrevious(p, 0);
83530      p->iGet = 0;
83531    }
83532    if( p->iGet<p->nSample ){
83533      Stat4Sample *pS = p->a + p->iGet;
83534      if( pS->nRowid==0 ){
83535        sqlite3_result_int64(context, pS->u.iRowid);
83536      }else{
83537        sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
83538                            SQLITE_TRANSIENT);
83539      }
83540    }
83541  }else{
83542    tRowcnt *aCnt = 0;
83543
83544    assert( p->iGet<p->nSample );
83545    switch( eCall ){
83546      case STAT_GET_NEQ:  aCnt = p->a[p->iGet].anEq; break;
83547      case STAT_GET_NLT:  aCnt = p->a[p->iGet].anLt; break;
83548      default: {
83549        aCnt = p->a[p->iGet].anDLt;
83550        p->iGet++;
83551        break;
83552      }
83553    }
83554
83555    if( IsStat3 ){
83556      sqlite3_result_int64(context, (i64)aCnt[0]);
83557    }else{
83558      char *zRet = sqlite3MallocZero(p->nCol * 25);
83559      if( zRet==0 ){
83560        sqlite3_result_error_nomem(context);
83561      }else{
83562        int i;
83563        char *z = zRet;
83564        for(i=0; i<p->nCol; i++){
83565          sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
83566          z += sqlite3Strlen30(z);
83567        }
83568        assert( z[0]=='\0' && z>zRet );
83569        z[-1] = '\0';
83570        sqlite3_result_text(context, zRet, -1, sqlite3_free);
83571      }
83572    }
83573  }
83574#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
83575#ifndef SQLITE_DEBUG
83576  UNUSED_PARAMETER( argc );
83577#endif
83578}
83579static const FuncDef statGetFuncdef = {
83580  1+IsStat34,      /* nArg */
83581  SQLITE_UTF8,     /* funcFlags */
83582  0,               /* pUserData */
83583  0,               /* pNext */
83584  statGet,         /* xFunc */
83585  0,               /* xStep */
83586  0,               /* xFinalize */
83587  "stat_get",      /* zName */
83588  0,               /* pHash */
83589  0                /* pDestructor */
83590};
83591
83592static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
83593  assert( regOut!=regStat4 && regOut!=regStat4+1 );
83594#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
83595  sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
83596#elif SQLITE_DEBUG
83597  assert( iParam==STAT_GET_STAT1 );
83598#else
83599  UNUSED_PARAMETER( iParam );
83600#endif
83601  sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4, regOut);
83602  sqlite3VdbeChangeP4(v, -1, (char*)&statGetFuncdef, P4_FUNCDEF);
83603  sqlite3VdbeChangeP5(v, 1 + IsStat34);
83604}
83605
83606/*
83607** Generate code to do an analysis of all indices associated with
83608** a single table.
83609*/
83610static void analyzeOneTable(
83611  Parse *pParse,   /* Parser context */
83612  Table *pTab,     /* Table whose indices are to be analyzed */
83613  Index *pOnlyIdx, /* If not NULL, only analyze this one index */
83614  int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
83615  int iMem,        /* Available memory locations begin here */
83616  int iTab         /* Next available cursor */
83617){
83618  sqlite3 *db = pParse->db;    /* Database handle */
83619  Index *pIdx;                 /* An index to being analyzed */
83620  int iIdxCur;                 /* Cursor open on index being analyzed */
83621  int iTabCur;                 /* Table cursor */
83622  Vdbe *v;                     /* The virtual machine being built up */
83623  int i;                       /* Loop counter */
83624  int jZeroRows = -1;          /* Jump from here if number of rows is zero */
83625  int iDb;                     /* Index of database containing pTab */
83626  u8 needTableCnt = 1;         /* True to count the table */
83627  int regNewRowid = iMem++;    /* Rowid for the inserted record */
83628  int regStat4 = iMem++;       /* Register to hold Stat4Accum object */
83629  int regChng = iMem++;        /* Index of changed index field */
83630#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
83631  int regRowid = iMem++;       /* Rowid argument passed to stat_push() */
83632#endif
83633  int regTemp = iMem++;        /* Temporary use register */
83634  int regTabname = iMem++;     /* Register containing table name */
83635  int regIdxname = iMem++;     /* Register containing index name */
83636  int regStat1 = iMem++;       /* Value for the stat column of sqlite_stat1 */
83637  int regPrev = iMem;          /* MUST BE LAST (see below) */
83638
83639  pParse->nMem = MAX(pParse->nMem, iMem);
83640  v = sqlite3GetVdbe(pParse);
83641  if( v==0 || NEVER(pTab==0) ){
83642    return;
83643  }
83644  if( pTab->tnum==0 ){
83645    /* Do not gather statistics on views or virtual tables */
83646    return;
83647  }
83648  if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
83649    /* Do not gather statistics on system tables */
83650    return;
83651  }
83652  assert( sqlite3BtreeHoldsAllMutexes(db) );
83653  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
83654  assert( iDb>=0 );
83655  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
83656#ifndef SQLITE_OMIT_AUTHORIZATION
83657  if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
83658      db->aDb[iDb].zName ) ){
83659    return;
83660  }
83661#endif
83662
83663  /* Establish a read-lock on the table at the shared-cache level.
83664  ** Open a read-only cursor on the table. Also allocate a cursor number
83665  ** to use for scanning indexes (iIdxCur). No index cursor is opened at
83666  ** this time though.  */
83667  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
83668  iTabCur = iTab++;
83669  iIdxCur = iTab++;
83670  pParse->nTab = MAX(pParse->nTab, iTab);
83671  sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
83672  sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
83673
83674  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
83675    int nCol;                     /* Number of columns indexed by pIdx */
83676    int *aGotoChng;               /* Array of jump instruction addresses */
83677    int addrRewind;               /* Address of "OP_Rewind iIdxCur" */
83678    int addrGotoChng0;            /* Address of "Goto addr_chng_0" */
83679    int addrNextRow;              /* Address of "next_row:" */
83680    const char *zIdxName;         /* Name of the index */
83681
83682    if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
83683    if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
83684    VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName));
83685    nCol = pIdx->nKeyCol;
83686    aGotoChng = sqlite3DbMallocRaw(db, sizeof(int)*(nCol+1));
83687    if( aGotoChng==0 ) continue;
83688
83689    /* Populate the register containing the index name. */
83690    if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
83691      zIdxName = pTab->zName;
83692    }else{
83693      zIdxName = pIdx->zName;
83694    }
83695    sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, zIdxName, 0);
83696
83697    /*
83698    ** Pseudo-code for loop that calls stat_push():
83699    **
83700    **   Rewind csr
83701    **   if eof(csr) goto end_of_scan;
83702    **   regChng = 0
83703    **   goto chng_addr_0;
83704    **
83705    **  next_row:
83706    **   regChng = 0
83707    **   if( idx(0) != regPrev(0) ) goto chng_addr_0
83708    **   regChng = 1
83709    **   if( idx(1) != regPrev(1) ) goto chng_addr_1
83710    **   ...
83711    **   regChng = N
83712    **   goto chng_addr_N
83713    **
83714    **  chng_addr_0:
83715    **   regPrev(0) = idx(0)
83716    **  chng_addr_1:
83717    **   regPrev(1) = idx(1)
83718    **  ...
83719    **
83720    **  chng_addr_N:
83721    **   regRowid = idx(rowid)
83722    **   stat_push(P, regChng, regRowid)
83723    **   Next csr
83724    **   if !eof(csr) goto next_row;
83725    **
83726    **  end_of_scan:
83727    */
83728
83729    /* Make sure there are enough memory cells allocated to accommodate
83730    ** the regPrev array and a trailing rowid (the rowid slot is required
83731    ** when building a record to insert into the sample column of
83732    ** the sqlite_stat4 table.  */
83733    pParse->nMem = MAX(pParse->nMem, regPrev+nCol);
83734
83735    /* Open a read-only cursor on the index being analyzed. */
83736    assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
83737    sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
83738    sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
83739    VdbeComment((v, "%s", pIdx->zName));
83740
83741    /* Invoke the stat_init() function. The arguments are:
83742    **
83743    **    (1) the number of columns in the index including the rowid,
83744    **    (2) the number of rows in the index,
83745    **
83746    ** The second argument is only used for STAT3 and STAT4
83747    */
83748#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
83749    sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+2);
83750#endif
83751    sqlite3VdbeAddOp2(v, OP_Integer, nCol+1, regStat4+1);
83752    sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4+1, regStat4);
83753    sqlite3VdbeChangeP4(v, -1, (char*)&statInitFuncdef, P4_FUNCDEF);
83754    sqlite3VdbeChangeP5(v, 1+IsStat34);
83755
83756    /* Implementation of the following:
83757    **
83758    **   Rewind csr
83759    **   if eof(csr) goto end_of_scan;
83760    **   regChng = 0
83761    **   goto next_push_0;
83762    **
83763    */
83764    addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
83765    VdbeCoverage(v);
83766    sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
83767    addrGotoChng0 = sqlite3VdbeAddOp0(v, OP_Goto);
83768
83769    /*
83770    **  next_row:
83771    **   regChng = 0
83772    **   if( idx(0) != regPrev(0) ) goto chng_addr_0
83773    **   regChng = 1
83774    **   if( idx(1) != regPrev(1) ) goto chng_addr_1
83775    **   ...
83776    **   regChng = N
83777    **   goto chng_addr_N
83778    */
83779    addrNextRow = sqlite3VdbeCurrentAddr(v);
83780    for(i=0; i<nCol; i++){
83781      char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
83782      sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
83783      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
83784      aGotoChng[i] =
83785      sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
83786      sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
83787      VdbeCoverage(v);
83788    }
83789    sqlite3VdbeAddOp2(v, OP_Integer, nCol, regChng);
83790    aGotoChng[nCol] = sqlite3VdbeAddOp0(v, OP_Goto);
83791
83792    /*
83793    **  chng_addr_0:
83794    **   regPrev(0) = idx(0)
83795    **  chng_addr_1:
83796    **   regPrev(1) = idx(1)
83797    **  ...
83798    */
83799    sqlite3VdbeJumpHere(v, addrGotoChng0);
83800    for(i=0; i<nCol; i++){
83801      sqlite3VdbeJumpHere(v, aGotoChng[i]);
83802      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
83803    }
83804
83805    /*
83806    **  chng_addr_N:
83807    **   regRowid = idx(rowid)            // STAT34 only
83808    **   stat_push(P, regChng, regRowid)  // 3rd parameter STAT34 only
83809    **   Next csr
83810    **   if !eof(csr) goto next_row;
83811    */
83812    sqlite3VdbeJumpHere(v, aGotoChng[nCol]);
83813#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
83814    assert( regRowid==(regStat4+2) );
83815    if( HasRowid(pTab) ){
83816      sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
83817    }else{
83818      Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
83819      int j, k, regKey;
83820      regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
83821      for(j=0; j<pPk->nKeyCol; j++){
83822        k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
83823        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
83824        VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
83825      }
83826      sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
83827      sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
83828    }
83829#endif
83830    assert( regChng==(regStat4+1) );
83831    sqlite3VdbeAddOp3(v, OP_Function, 1, regStat4, regTemp);
83832    sqlite3VdbeChangeP4(v, -1, (char*)&statPushFuncdef, P4_FUNCDEF);
83833    sqlite3VdbeChangeP5(v, 2+IsStat34);
83834    sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
83835
83836    /* Add the entry to the stat1 table. */
83837    callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
83838    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0);
83839    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
83840    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
83841    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
83842
83843    /* Add the entries to the stat3 or stat4 table. */
83844#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
83845    {
83846      int regEq = regStat1;
83847      int regLt = regStat1+1;
83848      int regDLt = regStat1+2;
83849      int regSample = regStat1+3;
83850      int regCol = regStat1+4;
83851      int regSampleRowid = regCol + nCol;
83852      int addrNext;
83853      int addrIsNull;
83854      u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
83855
83856      pParse->nMem = MAX(pParse->nMem, regCol+nCol+1);
83857
83858      addrNext = sqlite3VdbeCurrentAddr(v);
83859      callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
83860      addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
83861      VdbeCoverage(v);
83862      callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
83863      callStatGet(v, regStat4, STAT_GET_NLT, regLt);
83864      callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
83865      sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
83866      /* We know that the regSampleRowid row exists because it was read by
83867      ** the previous loop.  Thus the not-found jump of seekOp will never
83868      ** be taken */
83869      VdbeCoverageNeverTaken(v);
83870#ifdef SQLITE_ENABLE_STAT3
83871      sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
83872                                      pIdx->aiColumn[0], regSample);
83873#else
83874      for(i=0; i<nCol; i++){
83875        i16 iCol = pIdx->aiColumn[i];
83876        sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, iCol, regCol+i);
83877      }
83878      sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol+1, regSample);
83879#endif
83880      sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
83881      sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
83882      sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
83883      sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
83884      sqlite3VdbeJumpHere(v, addrIsNull);
83885    }
83886#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
83887
83888    /* End of analysis */
83889    sqlite3VdbeJumpHere(v, addrRewind);
83890    sqlite3DbFree(db, aGotoChng);
83891  }
83892
83893
83894  /* Create a single sqlite_stat1 entry containing NULL as the index
83895  ** name and the row count as the content.
83896  */
83897  if( pOnlyIdx==0 && needTableCnt ){
83898    VdbeComment((v, "%s", pTab->zName));
83899    sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
83900    jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
83901    sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
83902    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0);
83903    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
83904    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
83905    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
83906    sqlite3VdbeJumpHere(v, jZeroRows);
83907  }
83908}
83909
83910
83911/*
83912** Generate code that will cause the most recent index analysis to
83913** be loaded into internal hash tables where is can be used.
83914*/
83915static void loadAnalysis(Parse *pParse, int iDb){
83916  Vdbe *v = sqlite3GetVdbe(pParse);
83917  if( v ){
83918    sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
83919  }
83920}
83921
83922/*
83923** Generate code that will do an analysis of an entire database
83924*/
83925static void analyzeDatabase(Parse *pParse, int iDb){
83926  sqlite3 *db = pParse->db;
83927  Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
83928  HashElem *k;
83929  int iStatCur;
83930  int iMem;
83931  int iTab;
83932
83933  sqlite3BeginWriteOperation(pParse, 0, iDb);
83934  iStatCur = pParse->nTab;
83935  pParse->nTab += 3;
83936  openStatTable(pParse, iDb, iStatCur, 0, 0);
83937  iMem = pParse->nMem+1;
83938  iTab = pParse->nTab;
83939  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
83940  for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
83941    Table *pTab = (Table*)sqliteHashData(k);
83942    analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
83943  }
83944  loadAnalysis(pParse, iDb);
83945}
83946
83947/*
83948** Generate code that will do an analysis of a single table in
83949** a database.  If pOnlyIdx is not NULL then it is a single index
83950** in pTab that should be analyzed.
83951*/
83952static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
83953  int iDb;
83954  int iStatCur;
83955
83956  assert( pTab!=0 );
83957  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
83958  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
83959  sqlite3BeginWriteOperation(pParse, 0, iDb);
83960  iStatCur = pParse->nTab;
83961  pParse->nTab += 3;
83962  if( pOnlyIdx ){
83963    openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
83964  }else{
83965    openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
83966  }
83967  analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
83968  loadAnalysis(pParse, iDb);
83969}
83970
83971/*
83972** Generate code for the ANALYZE command.  The parser calls this routine
83973** when it recognizes an ANALYZE command.
83974**
83975**        ANALYZE                            -- 1
83976**        ANALYZE  <database>                -- 2
83977**        ANALYZE  ?<database>.?<tablename>  -- 3
83978**
83979** Form 1 causes all indices in all attached databases to be analyzed.
83980** Form 2 analyzes all indices the single database named.
83981** Form 3 analyzes all indices associated with the named table.
83982*/
83983SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
83984  sqlite3 *db = pParse->db;
83985  int iDb;
83986  int i;
83987  char *z, *zDb;
83988  Table *pTab;
83989  Index *pIdx;
83990  Token *pTableName;
83991
83992  /* Read the database schema. If an error occurs, leave an error message
83993  ** and code in pParse and return NULL. */
83994  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
83995  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
83996    return;
83997  }
83998
83999  assert( pName2!=0 || pName1==0 );
84000  if( pName1==0 ){
84001    /* Form 1:  Analyze everything */
84002    for(i=0; i<db->nDb; i++){
84003      if( i==1 ) continue;  /* Do not analyze the TEMP database */
84004      analyzeDatabase(pParse, i);
84005    }
84006  }else if( pName2->n==0 ){
84007    /* Form 2:  Analyze the database or table named */
84008    iDb = sqlite3FindDb(db, pName1);
84009    if( iDb>=0 ){
84010      analyzeDatabase(pParse, iDb);
84011    }else{
84012      z = sqlite3NameFromToken(db, pName1);
84013      if( z ){
84014        if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
84015          analyzeTable(pParse, pIdx->pTable, pIdx);
84016        }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
84017          analyzeTable(pParse, pTab, 0);
84018        }
84019        sqlite3DbFree(db, z);
84020      }
84021    }
84022  }else{
84023    /* Form 3: Analyze the fully qualified table name */
84024    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
84025    if( iDb>=0 ){
84026      zDb = db->aDb[iDb].zName;
84027      z = sqlite3NameFromToken(db, pTableName);
84028      if( z ){
84029        if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
84030          analyzeTable(pParse, pIdx->pTable, pIdx);
84031        }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
84032          analyzeTable(pParse, pTab, 0);
84033        }
84034        sqlite3DbFree(db, z);
84035      }
84036    }
84037  }
84038}
84039
84040/*
84041** Used to pass information from the analyzer reader through to the
84042** callback routine.
84043*/
84044typedef struct analysisInfo analysisInfo;
84045struct analysisInfo {
84046  sqlite3 *db;
84047  const char *zDatabase;
84048};
84049
84050/*
84051** The first argument points to a nul-terminated string containing a
84052** list of space separated integers. Read the first nOut of these into
84053** the array aOut[].
84054*/
84055static void decodeIntArray(
84056  char *zIntArray,       /* String containing int array to decode */
84057  int nOut,              /* Number of slots in aOut[] */
84058  tRowcnt *aOut,         /* Store integers here */
84059  LogEst *aLog,          /* Or, if aOut==0, here */
84060  Index *pIndex          /* Handle extra flags for this index, if not NULL */
84061){
84062  char *z = zIntArray;
84063  int c;
84064  int i;
84065  tRowcnt v;
84066
84067#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
84068  if( z==0 ) z = "";
84069#else
84070  if( NEVER(z==0) ) z = "";
84071#endif
84072  for(i=0; *z && i<nOut; i++){
84073    v = 0;
84074    while( (c=z[0])>='0' && c<='9' ){
84075      v = v*10 + c - '0';
84076      z++;
84077    }
84078#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
84079    if( aOut ){
84080      aOut[i] = v;
84081    }else
84082#else
84083    assert( aOut==0 );
84084    UNUSED_PARAMETER(aOut);
84085#endif
84086    {
84087      aLog[i] = sqlite3LogEst(v);
84088    }
84089    if( *z==' ' ) z++;
84090  }
84091#ifndef SQLITE_ENABLE_STAT3_OR_STAT4
84092  assert( pIndex!=0 );
84093#else
84094  if( pIndex )
84095#endif
84096  {
84097    if( strcmp(z, "unordered")==0 ){
84098      pIndex->bUnordered = 1;
84099    }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
84100      int v32 = 0;
84101      sqlite3GetInt32(z+3, &v32);
84102      pIndex->szIdxRow = sqlite3LogEst(v32);
84103    }
84104  }
84105}
84106
84107/*
84108** This callback is invoked once for each index when reading the
84109** sqlite_stat1 table.
84110**
84111**     argv[0] = name of the table
84112**     argv[1] = name of the index (might be NULL)
84113**     argv[2] = results of analysis - on integer for each column
84114**
84115** Entries for which argv[1]==NULL simply record the number of rows in
84116** the table.
84117*/
84118static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
84119  analysisInfo *pInfo = (analysisInfo*)pData;
84120  Index *pIndex;
84121  Table *pTable;
84122  const char *z;
84123
84124  assert( argc==3 );
84125  UNUSED_PARAMETER2(NotUsed, argc);
84126
84127  if( argv==0 || argv[0]==0 || argv[2]==0 ){
84128    return 0;
84129  }
84130  pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
84131  if( pTable==0 ){
84132    return 0;
84133  }
84134  if( argv[1]==0 ){
84135    pIndex = 0;
84136  }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
84137    pIndex = sqlite3PrimaryKeyIndex(pTable);
84138  }else{
84139    pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
84140  }
84141  z = argv[2];
84142
84143  if( pIndex ){
84144    decodeIntArray((char*)z, pIndex->nKeyCol+1, 0, pIndex->aiRowLogEst, pIndex);
84145    if( pIndex->pPartIdxWhere==0 ) pTable->nRowLogEst = pIndex->aiRowLogEst[0];
84146  }else{
84147    Index fakeIdx;
84148    fakeIdx.szIdxRow = pTable->szTabRow;
84149    decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
84150    pTable->szTabRow = fakeIdx.szIdxRow;
84151  }
84152
84153  return 0;
84154}
84155
84156/*
84157** If the Index.aSample variable is not NULL, delete the aSample[] array
84158** and its contents.
84159*/
84160SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
84161#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
84162  if( pIdx->aSample ){
84163    int j;
84164    for(j=0; j<pIdx->nSample; j++){
84165      IndexSample *p = &pIdx->aSample[j];
84166      sqlite3DbFree(db, p->p);
84167    }
84168    sqlite3DbFree(db, pIdx->aSample);
84169  }
84170  if( db && db->pnBytesFreed==0 ){
84171    pIdx->nSample = 0;
84172    pIdx->aSample = 0;
84173  }
84174#else
84175  UNUSED_PARAMETER(db);
84176  UNUSED_PARAMETER(pIdx);
84177#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
84178}
84179
84180#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
84181/*
84182** Populate the pIdx->aAvgEq[] array based on the samples currently
84183** stored in pIdx->aSample[].
84184*/
84185static void initAvgEq(Index *pIdx){
84186  if( pIdx ){
84187    IndexSample *aSample = pIdx->aSample;
84188    IndexSample *pFinal = &aSample[pIdx->nSample-1];
84189    int iCol;
84190    for(iCol=0; iCol<pIdx->nKeyCol; iCol++){
84191      int i;                    /* Used to iterate through samples */
84192      tRowcnt sumEq = 0;        /* Sum of the nEq values */
84193      tRowcnt nSum = 0;         /* Number of terms contributing to sumEq */
84194      tRowcnt avgEq = 0;
84195      tRowcnt nDLt = pFinal->anDLt[iCol];
84196
84197      /* Set nSum to the number of distinct (iCol+1) field prefixes that
84198      ** occur in the stat4 table for this index before pFinal. Set
84199      ** sumEq to the sum of the nEq values for column iCol for the same
84200      ** set (adding the value only once where there exist dupicate
84201      ** prefixes).  */
84202      for(i=0; i<(pIdx->nSample-1); i++){
84203        if( aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol] ){
84204          sumEq += aSample[i].anEq[iCol];
84205          nSum++;
84206        }
84207      }
84208      if( nDLt>nSum ){
84209        avgEq = (pFinal->anLt[iCol] - sumEq)/(nDLt - nSum);
84210      }
84211      if( avgEq==0 ) avgEq = 1;
84212      pIdx->aAvgEq[iCol] = avgEq;
84213      if( pIdx->nSampleCol==1 ) break;
84214    }
84215  }
84216}
84217
84218/*
84219** Look up an index by name.  Or, if the name of a WITHOUT ROWID table
84220** is supplied instead, find the PRIMARY KEY index for that table.
84221*/
84222static Index *findIndexOrPrimaryKey(
84223  sqlite3 *db,
84224  const char *zName,
84225  const char *zDb
84226){
84227  Index *pIdx = sqlite3FindIndex(db, zName, zDb);
84228  if( pIdx==0 ){
84229    Table *pTab = sqlite3FindTable(db, zName, zDb);
84230    if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
84231  }
84232  return pIdx;
84233}
84234
84235/*
84236** Load the content from either the sqlite_stat4 or sqlite_stat3 table
84237** into the relevant Index.aSample[] arrays.
84238**
84239** Arguments zSql1 and zSql2 must point to SQL statements that return
84240** data equivalent to the following (statements are different for stat3,
84241** see the caller of this function for details):
84242**
84243**    zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
84244**    zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
84245**
84246** where %Q is replaced with the database name before the SQL is executed.
84247*/
84248static int loadStatTbl(
84249  sqlite3 *db,                  /* Database handle */
84250  int bStat3,                   /* Assume single column records only */
84251  const char *zSql1,            /* SQL statement 1 (see above) */
84252  const char *zSql2,            /* SQL statement 2 (see above) */
84253  const char *zDb               /* Database name (e.g. "main") */
84254){
84255  int rc;                       /* Result codes from subroutines */
84256  sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
84257  char *zSql;                   /* Text of the SQL statement */
84258  Index *pPrevIdx = 0;          /* Previous index in the loop */
84259  IndexSample *pSample;         /* A slot in pIdx->aSample[] */
84260
84261  assert( db->lookaside.bEnabled==0 );
84262  zSql = sqlite3MPrintf(db, zSql1, zDb);
84263  if( !zSql ){
84264    return SQLITE_NOMEM;
84265  }
84266  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
84267  sqlite3DbFree(db, zSql);
84268  if( rc ) return rc;
84269
84270  while( sqlite3_step(pStmt)==SQLITE_ROW ){
84271    int nIdxCol = 1;              /* Number of columns in stat4 records */
84272    int nAvgCol = 1;              /* Number of entries in Index.aAvgEq */
84273
84274    char *zIndex;   /* Index name */
84275    Index *pIdx;    /* Pointer to the index object */
84276    int nSample;    /* Number of samples */
84277    int nByte;      /* Bytes of space required */
84278    int i;          /* Bytes of space required */
84279    tRowcnt *pSpace;
84280
84281    zIndex = (char *)sqlite3_column_text(pStmt, 0);
84282    if( zIndex==0 ) continue;
84283    nSample = sqlite3_column_int(pStmt, 1);
84284    pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
84285    assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
84286    /* Index.nSample is non-zero at this point if data has already been
84287    ** loaded from the stat4 table. In this case ignore stat3 data.  */
84288    if( pIdx==0 || pIdx->nSample ) continue;
84289    if( bStat3==0 ){
84290      nIdxCol = pIdx->nKeyCol+1;
84291      nAvgCol = pIdx->nKeyCol;
84292    }
84293    pIdx->nSampleCol = nIdxCol;
84294    nByte = sizeof(IndexSample) * nSample;
84295    nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
84296    nByte += nAvgCol * sizeof(tRowcnt);     /* Space for Index.aAvgEq[] */
84297
84298    pIdx->aSample = sqlite3DbMallocZero(db, nByte);
84299    if( pIdx->aSample==0 ){
84300      sqlite3_finalize(pStmt);
84301      return SQLITE_NOMEM;
84302    }
84303    pSpace = (tRowcnt*)&pIdx->aSample[nSample];
84304    pIdx->aAvgEq = pSpace; pSpace += nAvgCol;
84305    for(i=0; i<nSample; i++){
84306      pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
84307      pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
84308      pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
84309    }
84310    assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
84311  }
84312  rc = sqlite3_finalize(pStmt);
84313  if( rc ) return rc;
84314
84315  zSql = sqlite3MPrintf(db, zSql2, zDb);
84316  if( !zSql ){
84317    return SQLITE_NOMEM;
84318  }
84319  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
84320  sqlite3DbFree(db, zSql);
84321  if( rc ) return rc;
84322
84323  while( sqlite3_step(pStmt)==SQLITE_ROW ){
84324    char *zIndex;                 /* Index name */
84325    Index *pIdx;                  /* Pointer to the index object */
84326    int nCol = 1;                 /* Number of columns in index */
84327
84328    zIndex = (char *)sqlite3_column_text(pStmt, 0);
84329    if( zIndex==0 ) continue;
84330    pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
84331    if( pIdx==0 ) continue;
84332    /* This next condition is true if data has already been loaded from
84333    ** the sqlite_stat4 table. In this case ignore stat3 data.  */
84334    nCol = pIdx->nSampleCol;
84335    if( bStat3 && nCol>1 ) continue;
84336    if( pIdx!=pPrevIdx ){
84337      initAvgEq(pPrevIdx);
84338      pPrevIdx = pIdx;
84339    }
84340    pSample = &pIdx->aSample[pIdx->nSample];
84341    decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
84342    decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
84343    decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
84344
84345    /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
84346    ** This is in case the sample record is corrupted. In that case, the
84347    ** sqlite3VdbeRecordCompare() may read up to two varints past the
84348    ** end of the allocated buffer before it realizes it is dealing with
84349    ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
84350    ** a buffer overread.  */
84351    pSample->n = sqlite3_column_bytes(pStmt, 4);
84352    pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
84353    if( pSample->p==0 ){
84354      sqlite3_finalize(pStmt);
84355      return SQLITE_NOMEM;
84356    }
84357    memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
84358    pIdx->nSample++;
84359  }
84360  rc = sqlite3_finalize(pStmt);
84361  if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
84362  return rc;
84363}
84364
84365/*
84366** Load content from the sqlite_stat4 and sqlite_stat3 tables into
84367** the Index.aSample[] arrays of all indices.
84368*/
84369static int loadStat4(sqlite3 *db, const char *zDb){
84370  int rc = SQLITE_OK;             /* Result codes from subroutines */
84371
84372  assert( db->lookaside.bEnabled==0 );
84373  if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
84374    rc = loadStatTbl(db, 0,
84375      "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
84376      "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
84377      zDb
84378    );
84379  }
84380
84381  if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
84382    rc = loadStatTbl(db, 1,
84383      "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
84384      "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
84385      zDb
84386    );
84387  }
84388
84389  return rc;
84390}
84391#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
84392
84393/*
84394** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
84395** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
84396** arrays. The contents of sqlite_stat3/4 are used to populate the
84397** Index.aSample[] arrays.
84398**
84399** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
84400** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
84401** during compilation and the sqlite_stat3/4 table is present, no data is
84402** read from it.
84403**
84404** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
84405** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
84406** returned. However, in this case, data is read from the sqlite_stat1
84407** table (if it is present) before returning.
84408**
84409** If an OOM error occurs, this function always sets db->mallocFailed.
84410** This means if the caller does not care about other errors, the return
84411** code may be ignored.
84412*/
84413SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
84414  analysisInfo sInfo;
84415  HashElem *i;
84416  char *zSql;
84417  int rc;
84418
84419  assert( iDb>=0 && iDb<db->nDb );
84420  assert( db->aDb[iDb].pBt!=0 );
84421
84422  /* Clear any prior statistics */
84423  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
84424  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
84425    Index *pIdx = sqliteHashData(i);
84426    sqlite3DefaultRowEst(pIdx);
84427#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
84428    sqlite3DeleteIndexSamples(db, pIdx);
84429    pIdx->aSample = 0;
84430#endif
84431  }
84432
84433  /* Check to make sure the sqlite_stat1 table exists */
84434  sInfo.db = db;
84435  sInfo.zDatabase = db->aDb[iDb].zName;
84436  if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
84437    return SQLITE_ERROR;
84438  }
84439
84440  /* Load new statistics out of the sqlite_stat1 table */
84441  zSql = sqlite3MPrintf(db,
84442      "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
84443  if( zSql==0 ){
84444    rc = SQLITE_NOMEM;
84445  }else{
84446    rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
84447    sqlite3DbFree(db, zSql);
84448  }
84449
84450
84451  /* Load the statistics from the sqlite_stat4 table. */
84452#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
84453  if( rc==SQLITE_OK ){
84454    int lookasideEnabled = db->lookaside.bEnabled;
84455    db->lookaside.bEnabled = 0;
84456    rc = loadStat4(db, sInfo.zDatabase);
84457    db->lookaside.bEnabled = lookasideEnabled;
84458  }
84459#endif
84460
84461  if( rc==SQLITE_NOMEM ){
84462    db->mallocFailed = 1;
84463  }
84464  return rc;
84465}
84466
84467
84468#endif /* SQLITE_OMIT_ANALYZE */
84469
84470/************** End of analyze.c *********************************************/
84471/************** Begin file attach.c ******************************************/
84472/*
84473** 2003 April 6
84474**
84475** The author disclaims copyright to this source code.  In place of
84476** a legal notice, here is a blessing:
84477**
84478**    May you do good and not evil.
84479**    May you find forgiveness for yourself and forgive others.
84480**    May you share freely, never taking more than you give.
84481**
84482*************************************************************************
84483** This file contains code used to implement the ATTACH and DETACH commands.
84484*/
84485
84486#ifndef SQLITE_OMIT_ATTACH
84487/*
84488** Resolve an expression that was part of an ATTACH or DETACH statement. This
84489** is slightly different from resolving a normal SQL expression, because simple
84490** identifiers are treated as strings, not possible column names or aliases.
84491**
84492** i.e. if the parser sees:
84493**
84494**     ATTACH DATABASE abc AS def
84495**
84496** it treats the two expressions as literal strings 'abc' and 'def' instead of
84497** looking for columns of the same name.
84498**
84499** This only applies to the root node of pExpr, so the statement:
84500**
84501**     ATTACH DATABASE abc||def AS 'db2'
84502**
84503** will fail because neither abc or def can be resolved.
84504*/
84505static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
84506{
84507  int rc = SQLITE_OK;
84508  if( pExpr ){
84509    if( pExpr->op!=TK_ID ){
84510      rc = sqlite3ResolveExprNames(pName, pExpr);
84511    }else{
84512      pExpr->op = TK_STRING;
84513    }
84514  }
84515  return rc;
84516}
84517
84518/*
84519** An SQL user-function registered to do the work of an ATTACH statement. The
84520** three arguments to the function come directly from an attach statement:
84521**
84522**     ATTACH DATABASE x AS y KEY z
84523**
84524**     SELECT sqlite_attach(x, y, z)
84525**
84526** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
84527** third argument.
84528*/
84529static void attachFunc(
84530  sqlite3_context *context,
84531  int NotUsed,
84532  sqlite3_value **argv
84533){
84534  int i;
84535  int rc = 0;
84536  sqlite3 *db = sqlite3_context_db_handle(context);
84537  const char *zName;
84538  const char *zFile;
84539  char *zPath = 0;
84540  char *zErr = 0;
84541  unsigned int flags;
84542  Db *aNew;
84543  char *zErrDyn = 0;
84544  sqlite3_vfs *pVfs;
84545
84546  UNUSED_PARAMETER(NotUsed);
84547
84548  zFile = (const char *)sqlite3_value_text(argv[0]);
84549  zName = (const char *)sqlite3_value_text(argv[1]);
84550  if( zFile==0 ) zFile = "";
84551  if( zName==0 ) zName = "";
84552
84553  /* Check for the following errors:
84554  **
84555  **     * Too many attached databases,
84556  **     * Transaction currently open
84557  **     * Specified database name already being used.
84558  */
84559  if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
84560    zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
84561      db->aLimit[SQLITE_LIMIT_ATTACHED]
84562    );
84563    goto attach_error;
84564  }
84565  if( !db->autoCommit ){
84566    zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
84567    goto attach_error;
84568  }
84569  for(i=0; i<db->nDb; i++){
84570    char *z = db->aDb[i].zName;
84571    assert( z && zName );
84572    if( sqlite3StrICmp(z, zName)==0 ){
84573      zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
84574      goto attach_error;
84575    }
84576  }
84577
84578  /* Allocate the new entry in the db->aDb[] array and initialize the schema
84579  ** hash tables.
84580  */
84581  if( db->aDb==db->aDbStatic ){
84582    aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
84583    if( aNew==0 ) return;
84584    memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
84585  }else{
84586    aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
84587    if( aNew==0 ) return;
84588  }
84589  db->aDb = aNew;
84590  aNew = &db->aDb[db->nDb];
84591  memset(aNew, 0, sizeof(*aNew));
84592
84593  /* Open the database file. If the btree is successfully opened, use
84594  ** it to obtain the database schema. At this point the schema may
84595  ** or may not be initialized.
84596  */
84597  flags = db->openFlags;
84598  rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
84599  if( rc!=SQLITE_OK ){
84600    if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
84601    sqlite3_result_error(context, zErr, -1);
84602    sqlite3_free(zErr);
84603    return;
84604  }
84605  assert( pVfs );
84606  flags |= SQLITE_OPEN_MAIN_DB;
84607  rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
84608  sqlite3_free( zPath );
84609  db->nDb++;
84610  if( rc==SQLITE_CONSTRAINT ){
84611    rc = SQLITE_ERROR;
84612    zErrDyn = sqlite3MPrintf(db, "database is already attached");
84613  }else if( rc==SQLITE_OK ){
84614    Pager *pPager;
84615    aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
84616    if( !aNew->pSchema ){
84617      rc = SQLITE_NOMEM;
84618    }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
84619      zErrDyn = sqlite3MPrintf(db,
84620        "attached databases must use the same text encoding as main database");
84621      rc = SQLITE_ERROR;
84622    }
84623    pPager = sqlite3BtreePager(aNew->pBt);
84624    sqlite3PagerLockingMode(pPager, db->dfltLockMode);
84625    sqlite3BtreeSecureDelete(aNew->pBt,
84626                             sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
84627#ifndef SQLITE_OMIT_PAGER_PRAGMAS
84628    sqlite3BtreeSetPagerFlags(aNew->pBt, 3 | (db->flags & PAGER_FLAGS_MASK));
84629#endif
84630  }
84631  aNew->safety_level = 3;
84632  aNew->zName = sqlite3DbStrDup(db, zName);
84633  if( rc==SQLITE_OK && aNew->zName==0 ){
84634    rc = SQLITE_NOMEM;
84635  }
84636
84637
84638#ifdef SQLITE_HAS_CODEC
84639  if( rc==SQLITE_OK ){
84640    extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
84641    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
84642    int nKey;
84643    char *zKey;
84644    int t = sqlite3_value_type(argv[2]);
84645    switch( t ){
84646      case SQLITE_INTEGER:
84647      case SQLITE_FLOAT:
84648        zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
84649        rc = SQLITE_ERROR;
84650        break;
84651
84652      case SQLITE_TEXT:
84653      case SQLITE_BLOB:
84654        nKey = sqlite3_value_bytes(argv[2]);
84655        zKey = (char *)sqlite3_value_blob(argv[2]);
84656        rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
84657        break;
84658
84659      case SQLITE_NULL:
84660        /* No key specified.  Use the key from the main database */
84661        sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
84662        if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
84663          rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
84664        }
84665        break;
84666    }
84667  }
84668#endif
84669
84670  /* If the file was opened successfully, read the schema for the new database.
84671  ** If this fails, or if opening the file failed, then close the file and
84672  ** remove the entry from the db->aDb[] array. i.e. put everything back the way
84673  ** we found it.
84674  */
84675  if( rc==SQLITE_OK ){
84676    sqlite3BtreeEnterAll(db);
84677    rc = sqlite3Init(db, &zErrDyn);
84678    sqlite3BtreeLeaveAll(db);
84679  }
84680  if( rc ){
84681    int iDb = db->nDb - 1;
84682    assert( iDb>=2 );
84683    if( db->aDb[iDb].pBt ){
84684      sqlite3BtreeClose(db->aDb[iDb].pBt);
84685      db->aDb[iDb].pBt = 0;
84686      db->aDb[iDb].pSchema = 0;
84687    }
84688    sqlite3ResetAllSchemasOfConnection(db);
84689    db->nDb = iDb;
84690    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
84691      db->mallocFailed = 1;
84692      sqlite3DbFree(db, zErrDyn);
84693      zErrDyn = sqlite3MPrintf(db, "out of memory");
84694    }else if( zErrDyn==0 ){
84695      zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
84696    }
84697    goto attach_error;
84698  }
84699
84700  return;
84701
84702attach_error:
84703  /* Return an error if we get here */
84704  if( zErrDyn ){
84705    sqlite3_result_error(context, zErrDyn, -1);
84706    sqlite3DbFree(db, zErrDyn);
84707  }
84708  if( rc ) sqlite3_result_error_code(context, rc);
84709}
84710
84711/*
84712** An SQL user-function registered to do the work of an DETACH statement. The
84713** three arguments to the function come directly from a detach statement:
84714**
84715**     DETACH DATABASE x
84716**
84717**     SELECT sqlite_detach(x)
84718*/
84719static void detachFunc(
84720  sqlite3_context *context,
84721  int NotUsed,
84722  sqlite3_value **argv
84723){
84724  const char *zName = (const char *)sqlite3_value_text(argv[0]);
84725  sqlite3 *db = sqlite3_context_db_handle(context);
84726  int i;
84727  Db *pDb = 0;
84728  char zErr[128];
84729
84730  UNUSED_PARAMETER(NotUsed);
84731
84732  if( zName==0 ) zName = "";
84733  for(i=0; i<db->nDb; i++){
84734    pDb = &db->aDb[i];
84735    if( pDb->pBt==0 ) continue;
84736    if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
84737  }
84738
84739  if( i>=db->nDb ){
84740    sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
84741    goto detach_error;
84742  }
84743  if( i<2 ){
84744    sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
84745    goto detach_error;
84746  }
84747  if( !db->autoCommit ){
84748    sqlite3_snprintf(sizeof(zErr), zErr,
84749                     "cannot DETACH database within transaction");
84750    goto detach_error;
84751  }
84752  if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
84753    sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
84754    goto detach_error;
84755  }
84756
84757  sqlite3BtreeClose(pDb->pBt);
84758  pDb->pBt = 0;
84759  pDb->pSchema = 0;
84760  sqlite3ResetAllSchemasOfConnection(db);
84761  return;
84762
84763detach_error:
84764  sqlite3_result_error(context, zErr, -1);
84765}
84766
84767/*
84768** This procedure generates VDBE code for a single invocation of either the
84769** sqlite_detach() or sqlite_attach() SQL user functions.
84770*/
84771static void codeAttach(
84772  Parse *pParse,       /* The parser context */
84773  int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
84774  FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
84775  Expr *pAuthArg,      /* Expression to pass to authorization callback */
84776  Expr *pFilename,     /* Name of database file */
84777  Expr *pDbname,       /* Name of the database to use internally */
84778  Expr *pKey           /* Database key for encryption extension */
84779){
84780  int rc;
84781  NameContext sName;
84782  Vdbe *v;
84783  sqlite3* db = pParse->db;
84784  int regArgs;
84785
84786  memset(&sName, 0, sizeof(NameContext));
84787  sName.pParse = pParse;
84788
84789  if(
84790      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
84791      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
84792      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
84793  ){
84794    pParse->nErr++;
84795    goto attach_end;
84796  }
84797
84798#ifndef SQLITE_OMIT_AUTHORIZATION
84799  if( pAuthArg ){
84800    char *zAuthArg;
84801    if( pAuthArg->op==TK_STRING ){
84802      zAuthArg = pAuthArg->u.zToken;
84803    }else{
84804      zAuthArg = 0;
84805    }
84806    rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
84807    if(rc!=SQLITE_OK ){
84808      goto attach_end;
84809    }
84810  }
84811#endif /* SQLITE_OMIT_AUTHORIZATION */
84812
84813
84814  v = sqlite3GetVdbe(pParse);
84815  regArgs = sqlite3GetTempRange(pParse, 4);
84816  sqlite3ExprCode(pParse, pFilename, regArgs);
84817  sqlite3ExprCode(pParse, pDbname, regArgs+1);
84818  sqlite3ExprCode(pParse, pKey, regArgs+2);
84819
84820  assert( v || db->mallocFailed );
84821  if( v ){
84822    sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
84823    assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
84824    sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
84825    sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
84826
84827    /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
84828    ** statement only). For DETACH, set it to false (expire all existing
84829    ** statements).
84830    */
84831    sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
84832  }
84833
84834attach_end:
84835  sqlite3ExprDelete(db, pFilename);
84836  sqlite3ExprDelete(db, pDbname);
84837  sqlite3ExprDelete(db, pKey);
84838}
84839
84840/*
84841** Called by the parser to compile a DETACH statement.
84842**
84843**     DETACH pDbname
84844*/
84845SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
84846  static const FuncDef detach_func = {
84847    1,                /* nArg */
84848    SQLITE_UTF8,      /* funcFlags */
84849    0,                /* pUserData */
84850    0,                /* pNext */
84851    detachFunc,       /* xFunc */
84852    0,                /* xStep */
84853    0,                /* xFinalize */
84854    "sqlite_detach",  /* zName */
84855    0,                /* pHash */
84856    0                 /* pDestructor */
84857  };
84858  codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
84859}
84860
84861/*
84862** Called by the parser to compile an ATTACH statement.
84863**
84864**     ATTACH p AS pDbname KEY pKey
84865*/
84866SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
84867  static const FuncDef attach_func = {
84868    3,                /* nArg */
84869    SQLITE_UTF8,      /* funcFlags */
84870    0,                /* pUserData */
84871    0,                /* pNext */
84872    attachFunc,       /* xFunc */
84873    0,                /* xStep */
84874    0,                /* xFinalize */
84875    "sqlite_attach",  /* zName */
84876    0,                /* pHash */
84877    0                 /* pDestructor */
84878  };
84879  codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
84880}
84881#endif /* SQLITE_OMIT_ATTACH */
84882
84883/*
84884** Initialize a DbFixer structure.  This routine must be called prior
84885** to passing the structure to one of the sqliteFixAAAA() routines below.
84886*/
84887SQLITE_PRIVATE void sqlite3FixInit(
84888  DbFixer *pFix,      /* The fixer to be initialized */
84889  Parse *pParse,      /* Error messages will be written here */
84890  int iDb,            /* This is the database that must be used */
84891  const char *zType,  /* "view", "trigger", or "index" */
84892  const Token *pName  /* Name of the view, trigger, or index */
84893){
84894  sqlite3 *db;
84895
84896  db = pParse->db;
84897  assert( db->nDb>iDb );
84898  pFix->pParse = pParse;
84899  pFix->zDb = db->aDb[iDb].zName;
84900  pFix->pSchema = db->aDb[iDb].pSchema;
84901  pFix->zType = zType;
84902  pFix->pName = pName;
84903  pFix->bVarOnly = (iDb==1);
84904}
84905
84906/*
84907** The following set of routines walk through the parse tree and assign
84908** a specific database to all table references where the database name
84909** was left unspecified in the original SQL statement.  The pFix structure
84910** must have been initialized by a prior call to sqlite3FixInit().
84911**
84912** These routines are used to make sure that an index, trigger, or
84913** view in one database does not refer to objects in a different database.
84914** (Exception: indices, triggers, and views in the TEMP database are
84915** allowed to refer to anything.)  If a reference is explicitly made
84916** to an object in a different database, an error message is added to
84917** pParse->zErrMsg and these routines return non-zero.  If everything
84918** checks out, these routines return 0.
84919*/
84920SQLITE_PRIVATE int sqlite3FixSrcList(
84921  DbFixer *pFix,       /* Context of the fixation */
84922  SrcList *pList       /* The Source list to check and modify */
84923){
84924  int i;
84925  const char *zDb;
84926  struct SrcList_item *pItem;
84927
84928  if( NEVER(pList==0) ) return 0;
84929  zDb = pFix->zDb;
84930  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
84931    if( pFix->bVarOnly==0 ){
84932      if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
84933        sqlite3ErrorMsg(pFix->pParse,
84934            "%s %T cannot reference objects in database %s",
84935            pFix->zType, pFix->pName, pItem->zDatabase);
84936        return 1;
84937      }
84938      sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
84939      pItem->zDatabase = 0;
84940      pItem->pSchema = pFix->pSchema;
84941    }
84942#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
84943    if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
84944    if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
84945#endif
84946  }
84947  return 0;
84948}
84949#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
84950SQLITE_PRIVATE int sqlite3FixSelect(
84951  DbFixer *pFix,       /* Context of the fixation */
84952  Select *pSelect      /* The SELECT statement to be fixed to one database */
84953){
84954  while( pSelect ){
84955    if( sqlite3FixExprList(pFix, pSelect->pEList) ){
84956      return 1;
84957    }
84958    if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
84959      return 1;
84960    }
84961    if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
84962      return 1;
84963    }
84964    if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
84965      return 1;
84966    }
84967    if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
84968      return 1;
84969    }
84970    if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
84971      return 1;
84972    }
84973    if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
84974      return 1;
84975    }
84976    if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
84977      return 1;
84978    }
84979    pSelect = pSelect->pPrior;
84980  }
84981  return 0;
84982}
84983SQLITE_PRIVATE int sqlite3FixExpr(
84984  DbFixer *pFix,     /* Context of the fixation */
84985  Expr *pExpr        /* The expression to be fixed to one database */
84986){
84987  while( pExpr ){
84988    if( pExpr->op==TK_VARIABLE ){
84989      if( pFix->pParse->db->init.busy ){
84990        pExpr->op = TK_NULL;
84991      }else{
84992        sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
84993        return 1;
84994      }
84995    }
84996    if( ExprHasProperty(pExpr, EP_TokenOnly) ) break;
84997    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
84998      if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
84999    }else{
85000      if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
85001    }
85002    if( sqlite3FixExpr(pFix, pExpr->pRight) ){
85003      return 1;
85004    }
85005    pExpr = pExpr->pLeft;
85006  }
85007  return 0;
85008}
85009SQLITE_PRIVATE int sqlite3FixExprList(
85010  DbFixer *pFix,     /* Context of the fixation */
85011  ExprList *pList    /* The expression to be fixed to one database */
85012){
85013  int i;
85014  struct ExprList_item *pItem;
85015  if( pList==0 ) return 0;
85016  for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
85017    if( sqlite3FixExpr(pFix, pItem->pExpr) ){
85018      return 1;
85019    }
85020  }
85021  return 0;
85022}
85023#endif
85024
85025#ifndef SQLITE_OMIT_TRIGGER
85026SQLITE_PRIVATE int sqlite3FixTriggerStep(
85027  DbFixer *pFix,     /* Context of the fixation */
85028  TriggerStep *pStep /* The trigger step be fixed to one database */
85029){
85030  while( pStep ){
85031    if( sqlite3FixSelect(pFix, pStep->pSelect) ){
85032      return 1;
85033    }
85034    if( sqlite3FixExpr(pFix, pStep->pWhere) ){
85035      return 1;
85036    }
85037    if( sqlite3FixExprList(pFix, pStep->pExprList) ){
85038      return 1;
85039    }
85040    pStep = pStep->pNext;
85041  }
85042  return 0;
85043}
85044#endif
85045
85046/************** End of attach.c **********************************************/
85047/************** Begin file auth.c ********************************************/
85048/*
85049** 2003 January 11
85050**
85051** The author disclaims copyright to this source code.  In place of
85052** a legal notice, here is a blessing:
85053**
85054**    May you do good and not evil.
85055**    May you find forgiveness for yourself and forgive others.
85056**    May you share freely, never taking more than you give.
85057**
85058*************************************************************************
85059** This file contains code used to implement the sqlite3_set_authorizer()
85060** API.  This facility is an optional feature of the library.  Embedded
85061** systems that do not need this facility may omit it by recompiling
85062** the library with -DSQLITE_OMIT_AUTHORIZATION=1
85063*/
85064
85065/*
85066** All of the code in this file may be omitted by defining a single
85067** macro.
85068*/
85069#ifndef SQLITE_OMIT_AUTHORIZATION
85070
85071/*
85072** Set or clear the access authorization function.
85073**
85074** The access authorization function is be called during the compilation
85075** phase to verify that the user has read and/or write access permission on
85076** various fields of the database.  The first argument to the auth function
85077** is a copy of the 3rd argument to this routine.  The second argument
85078** to the auth function is one of these constants:
85079**
85080**       SQLITE_CREATE_INDEX
85081**       SQLITE_CREATE_TABLE
85082**       SQLITE_CREATE_TEMP_INDEX
85083**       SQLITE_CREATE_TEMP_TABLE
85084**       SQLITE_CREATE_TEMP_TRIGGER
85085**       SQLITE_CREATE_TEMP_VIEW
85086**       SQLITE_CREATE_TRIGGER
85087**       SQLITE_CREATE_VIEW
85088**       SQLITE_DELETE
85089**       SQLITE_DROP_INDEX
85090**       SQLITE_DROP_TABLE
85091**       SQLITE_DROP_TEMP_INDEX
85092**       SQLITE_DROP_TEMP_TABLE
85093**       SQLITE_DROP_TEMP_TRIGGER
85094**       SQLITE_DROP_TEMP_VIEW
85095**       SQLITE_DROP_TRIGGER
85096**       SQLITE_DROP_VIEW
85097**       SQLITE_INSERT
85098**       SQLITE_PRAGMA
85099**       SQLITE_READ
85100**       SQLITE_SELECT
85101**       SQLITE_TRANSACTION
85102**       SQLITE_UPDATE
85103**
85104** The third and fourth arguments to the auth function are the name of
85105** the table and the column that are being accessed.  The auth function
85106** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
85107** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
85108** means that the SQL statement will never-run - the sqlite3_exec() call
85109** will return with an error.  SQLITE_IGNORE means that the SQL statement
85110** should run but attempts to read the specified column will return NULL
85111** and attempts to write the column will be ignored.
85112**
85113** Setting the auth function to NULL disables this hook.  The default
85114** setting of the auth function is NULL.
85115*/
85116SQLITE_API int sqlite3_set_authorizer(
85117  sqlite3 *db,
85118  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
85119  void *pArg
85120){
85121  sqlite3_mutex_enter(db->mutex);
85122  db->xAuth = xAuth;
85123  db->pAuthArg = pArg;
85124  sqlite3ExpirePreparedStatements(db);
85125  sqlite3_mutex_leave(db->mutex);
85126  return SQLITE_OK;
85127}
85128
85129/*
85130** Write an error message into pParse->zErrMsg that explains that the
85131** user-supplied authorization function returned an illegal value.
85132*/
85133static void sqliteAuthBadReturnCode(Parse *pParse){
85134  sqlite3ErrorMsg(pParse, "authorizer malfunction");
85135  pParse->rc = SQLITE_ERROR;
85136}
85137
85138/*
85139** Invoke the authorization callback for permission to read column zCol from
85140** table zTab in database zDb. This function assumes that an authorization
85141** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
85142**
85143** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
85144** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
85145** is treated as SQLITE_DENY. In this case an error is left in pParse.
85146*/
85147SQLITE_PRIVATE int sqlite3AuthReadCol(
85148  Parse *pParse,                  /* The parser context */
85149  const char *zTab,               /* Table name */
85150  const char *zCol,               /* Column name */
85151  int iDb                         /* Index of containing database. */
85152){
85153  sqlite3 *db = pParse->db;       /* Database handle */
85154  char *zDb = db->aDb[iDb].zName; /* Name of attached database */
85155  int rc;                         /* Auth callback return code */
85156
85157  rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
85158  if( rc==SQLITE_DENY ){
85159    if( db->nDb>2 || iDb!=0 ){
85160      sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
85161    }else{
85162      sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
85163    }
85164    pParse->rc = SQLITE_AUTH;
85165  }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
85166    sqliteAuthBadReturnCode(pParse);
85167  }
85168  return rc;
85169}
85170
85171/*
85172** The pExpr should be a TK_COLUMN expression.  The table referred to
85173** is in pTabList or else it is the NEW or OLD table of a trigger.
85174** Check to see if it is OK to read this particular column.
85175**
85176** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
85177** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
85178** then generate an error.
85179*/
85180SQLITE_PRIVATE void sqlite3AuthRead(
85181  Parse *pParse,        /* The parser context */
85182  Expr *pExpr,          /* The expression to check authorization on */
85183  Schema *pSchema,      /* The schema of the expression */
85184  SrcList *pTabList     /* All table that pExpr might refer to */
85185){
85186  sqlite3 *db = pParse->db;
85187  Table *pTab = 0;      /* The table being read */
85188  const char *zCol;     /* Name of the column of the table */
85189  int iSrc;             /* Index in pTabList->a[] of table being read */
85190  int iDb;              /* The index of the database the expression refers to */
85191  int iCol;             /* Index of column in table */
85192
85193  if( db->xAuth==0 ) return;
85194  iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
85195  if( iDb<0 ){
85196    /* An attempt to read a column out of a subquery or other
85197    ** temporary table. */
85198    return;
85199  }
85200
85201  assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
85202  if( pExpr->op==TK_TRIGGER ){
85203    pTab = pParse->pTriggerTab;
85204  }else{
85205    assert( pTabList );
85206    for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
85207      if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
85208        pTab = pTabList->a[iSrc].pTab;
85209        break;
85210      }
85211    }
85212  }
85213  iCol = pExpr->iColumn;
85214  if( NEVER(pTab==0) ) return;
85215
85216  if( iCol>=0 ){
85217    assert( iCol<pTab->nCol );
85218    zCol = pTab->aCol[iCol].zName;
85219  }else if( pTab->iPKey>=0 ){
85220    assert( pTab->iPKey<pTab->nCol );
85221    zCol = pTab->aCol[pTab->iPKey].zName;
85222  }else{
85223    zCol = "ROWID";
85224  }
85225  assert( iDb>=0 && iDb<db->nDb );
85226  if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
85227    pExpr->op = TK_NULL;
85228  }
85229}
85230
85231/*
85232** Do an authorization check using the code and arguments given.  Return
85233** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
85234** is returned, then the error count and error message in pParse are
85235** modified appropriately.
85236*/
85237SQLITE_PRIVATE int sqlite3AuthCheck(
85238  Parse *pParse,
85239  int code,
85240  const char *zArg1,
85241  const char *zArg2,
85242  const char *zArg3
85243){
85244  sqlite3 *db = pParse->db;
85245  int rc;
85246
85247  /* Don't do any authorization checks if the database is initialising
85248  ** or if the parser is being invoked from within sqlite3_declare_vtab.
85249  */
85250  if( db->init.busy || IN_DECLARE_VTAB ){
85251    return SQLITE_OK;
85252  }
85253
85254  if( db->xAuth==0 ){
85255    return SQLITE_OK;
85256  }
85257  rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
85258  if( rc==SQLITE_DENY ){
85259    sqlite3ErrorMsg(pParse, "not authorized");
85260    pParse->rc = SQLITE_AUTH;
85261  }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
85262    rc = SQLITE_DENY;
85263    sqliteAuthBadReturnCode(pParse);
85264  }
85265  return rc;
85266}
85267
85268/*
85269** Push an authorization context.  After this routine is called, the
85270** zArg3 argument to authorization callbacks will be zContext until
85271** popped.  Or if pParse==0, this routine is a no-op.
85272*/
85273SQLITE_PRIVATE void sqlite3AuthContextPush(
85274  Parse *pParse,
85275  AuthContext *pContext,
85276  const char *zContext
85277){
85278  assert( pParse );
85279  pContext->pParse = pParse;
85280  pContext->zAuthContext = pParse->zAuthContext;
85281  pParse->zAuthContext = zContext;
85282}
85283
85284/*
85285** Pop an authorization context that was previously pushed
85286** by sqlite3AuthContextPush
85287*/
85288SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
85289  if( pContext->pParse ){
85290    pContext->pParse->zAuthContext = pContext->zAuthContext;
85291    pContext->pParse = 0;
85292  }
85293}
85294
85295#endif /* SQLITE_OMIT_AUTHORIZATION */
85296
85297/************** End of auth.c ************************************************/
85298/************** Begin file build.c *******************************************/
85299/*
85300** 2001 September 15
85301**
85302** The author disclaims copyright to this source code.  In place of
85303** a legal notice, here is a blessing:
85304**
85305**    May you do good and not evil.
85306**    May you find forgiveness for yourself and forgive others.
85307**    May you share freely, never taking more than you give.
85308**
85309*************************************************************************
85310** This file contains C code routines that are called by the SQLite parser
85311** when syntax rules are reduced.  The routines in this file handle the
85312** following kinds of SQL syntax:
85313**
85314**     CREATE TABLE
85315**     DROP TABLE
85316**     CREATE INDEX
85317**     DROP INDEX
85318**     creating ID lists
85319**     BEGIN TRANSACTION
85320**     COMMIT
85321**     ROLLBACK
85322*/
85323
85324/*
85325** This routine is called when a new SQL statement is beginning to
85326** be parsed.  Initialize the pParse structure as needed.
85327*/
85328SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
85329  pParse->explain = (u8)explainFlag;
85330  pParse->nVar = 0;
85331}
85332
85333#ifndef SQLITE_OMIT_SHARED_CACHE
85334/*
85335** The TableLock structure is only used by the sqlite3TableLock() and
85336** codeTableLocks() functions.
85337*/
85338struct TableLock {
85339  int iDb;             /* The database containing the table to be locked */
85340  int iTab;            /* The root page of the table to be locked */
85341  u8 isWriteLock;      /* True for write lock.  False for a read lock */
85342  const char *zName;   /* Name of the table */
85343};
85344
85345/*
85346** Record the fact that we want to lock a table at run-time.
85347**
85348** The table to be locked has root page iTab and is found in database iDb.
85349** A read or a write lock can be taken depending on isWritelock.
85350**
85351** This routine just records the fact that the lock is desired.  The
85352** code to make the lock occur is generated by a later call to
85353** codeTableLocks() which occurs during sqlite3FinishCoding().
85354*/
85355SQLITE_PRIVATE void sqlite3TableLock(
85356  Parse *pParse,     /* Parsing context */
85357  int iDb,           /* Index of the database containing the table to lock */
85358  int iTab,          /* Root page number of the table to be locked */
85359  u8 isWriteLock,    /* True for a write lock */
85360  const char *zName  /* Name of the table to be locked */
85361){
85362  Parse *pToplevel = sqlite3ParseToplevel(pParse);
85363  int i;
85364  int nBytes;
85365  TableLock *p;
85366  assert( iDb>=0 );
85367
85368  for(i=0; i<pToplevel->nTableLock; i++){
85369    p = &pToplevel->aTableLock[i];
85370    if( p->iDb==iDb && p->iTab==iTab ){
85371      p->isWriteLock = (p->isWriteLock || isWriteLock);
85372      return;
85373    }
85374  }
85375
85376  nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
85377  pToplevel->aTableLock =
85378      sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
85379  if( pToplevel->aTableLock ){
85380    p = &pToplevel->aTableLock[pToplevel->nTableLock++];
85381    p->iDb = iDb;
85382    p->iTab = iTab;
85383    p->isWriteLock = isWriteLock;
85384    p->zName = zName;
85385  }else{
85386    pToplevel->nTableLock = 0;
85387    pToplevel->db->mallocFailed = 1;
85388  }
85389}
85390
85391/*
85392** Code an OP_TableLock instruction for each table locked by the
85393** statement (configured by calls to sqlite3TableLock()).
85394*/
85395static void codeTableLocks(Parse *pParse){
85396  int i;
85397  Vdbe *pVdbe;
85398
85399  pVdbe = sqlite3GetVdbe(pParse);
85400  assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
85401
85402  for(i=0; i<pParse->nTableLock; i++){
85403    TableLock *p = &pParse->aTableLock[i];
85404    int p1 = p->iDb;
85405    sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
85406                      p->zName, P4_STATIC);
85407  }
85408}
85409#else
85410  #define codeTableLocks(x)
85411#endif
85412
85413/*
85414** This routine is called after a single SQL statement has been
85415** parsed and a VDBE program to execute that statement has been
85416** prepared.  This routine puts the finishing touches on the
85417** VDBE program and resets the pParse structure for the next
85418** parse.
85419**
85420** Note that if an error occurred, it might be the case that
85421** no VDBE code was generated.
85422*/
85423SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
85424  sqlite3 *db;
85425  Vdbe *v;
85426
85427  assert( pParse->pToplevel==0 );
85428  db = pParse->db;
85429  if( db->mallocFailed ) return;
85430  if( pParse->nested ) return;
85431  if( pParse->nErr ) return;
85432
85433  /* Begin by generating some termination code at the end of the
85434  ** vdbe program
85435  */
85436  v = sqlite3GetVdbe(pParse);
85437  assert( !pParse->isMultiWrite
85438       || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
85439  if( v ){
85440    while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
85441    sqlite3VdbeAddOp0(v, OP_Halt);
85442
85443    /* The cookie mask contains one bit for each database file open.
85444    ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
85445    ** set for each database that is used.  Generate code to start a
85446    ** transaction on each used database and to verify the schema cookie
85447    ** on each used database.
85448    */
85449    if( db->mallocFailed==0 && (pParse->cookieMask || pParse->pConstExpr) ){
85450      yDbMask mask;
85451      int iDb, i;
85452      assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
85453      sqlite3VdbeJumpHere(v, 0);
85454      for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
85455        if( (mask & pParse->cookieMask)==0 ) continue;
85456        sqlite3VdbeUsesBtree(v, iDb);
85457        sqlite3VdbeAddOp4Int(v,
85458          OP_Transaction,                    /* Opcode */
85459          iDb,                               /* P1 */
85460          (mask & pParse->writeMask)!=0,     /* P2 */
85461          pParse->cookieValue[iDb],          /* P3 */
85462          db->aDb[iDb].pSchema->iGeneration  /* P4 */
85463        );
85464        if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
85465      }
85466#ifndef SQLITE_OMIT_VIRTUALTABLE
85467      for(i=0; i<pParse->nVtabLock; i++){
85468        char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
85469        sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
85470      }
85471      pParse->nVtabLock = 0;
85472#endif
85473
85474      /* Once all the cookies have been verified and transactions opened,
85475      ** obtain the required table-locks. This is a no-op unless the
85476      ** shared-cache feature is enabled.
85477      */
85478      codeTableLocks(pParse);
85479
85480      /* Initialize any AUTOINCREMENT data structures required.
85481      */
85482      sqlite3AutoincrementBegin(pParse);
85483
85484      /* Code constant expressions that where factored out of inner loops */
85485      if( pParse->pConstExpr ){
85486        ExprList *pEL = pParse->pConstExpr;
85487        pParse->okConstFactor = 0;
85488        for(i=0; i<pEL->nExpr; i++){
85489          sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
85490        }
85491      }
85492
85493      /* Finally, jump back to the beginning of the executable code. */
85494      sqlite3VdbeAddOp2(v, OP_Goto, 0, 1);
85495    }
85496  }
85497
85498
85499  /* Get the VDBE program ready for execution
85500  */
85501  if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
85502    assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
85503    /* A minimum of one cursor is required if autoincrement is used
85504    *  See ticket [a696379c1f08866] */
85505    if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
85506    sqlite3VdbeMakeReady(v, pParse);
85507    pParse->rc = SQLITE_DONE;
85508    pParse->colNamesSet = 0;
85509  }else{
85510    pParse->rc = SQLITE_ERROR;
85511  }
85512  pParse->nTab = 0;
85513  pParse->nMem = 0;
85514  pParse->nSet = 0;
85515  pParse->nVar = 0;
85516  pParse->cookieMask = 0;
85517}
85518
85519/*
85520** Run the parser and code generator recursively in order to generate
85521** code for the SQL statement given onto the end of the pParse context
85522** currently under construction.  When the parser is run recursively
85523** this way, the final OP_Halt is not appended and other initialization
85524** and finalization steps are omitted because those are handling by the
85525** outermost parser.
85526**
85527** Not everything is nestable.  This facility is designed to permit
85528** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
85529** care if you decide to try to use this routine for some other purposes.
85530*/
85531SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
85532  va_list ap;
85533  char *zSql;
85534  char *zErrMsg = 0;
85535  sqlite3 *db = pParse->db;
85536# define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
85537  char saveBuf[SAVE_SZ];
85538
85539  if( pParse->nErr ) return;
85540  assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
85541  va_start(ap, zFormat);
85542  zSql = sqlite3VMPrintf(db, zFormat, ap);
85543  va_end(ap);
85544  if( zSql==0 ){
85545    return;   /* A malloc must have failed */
85546  }
85547  pParse->nested++;
85548  memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
85549  memset(&pParse->nVar, 0, SAVE_SZ);
85550  sqlite3RunParser(pParse, zSql, &zErrMsg);
85551  sqlite3DbFree(db, zErrMsg);
85552  sqlite3DbFree(db, zSql);
85553  memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
85554  pParse->nested--;
85555}
85556
85557/*
85558** Locate the in-memory structure that describes a particular database
85559** table given the name of that table and (optionally) the name of the
85560** database containing the table.  Return NULL if not found.
85561**
85562** If zDatabase is 0, all databases are searched for the table and the
85563** first matching table is returned.  (No checking for duplicate table
85564** names is done.)  The search order is TEMP first, then MAIN, then any
85565** auxiliary databases added using the ATTACH command.
85566**
85567** See also sqlite3LocateTable().
85568*/
85569SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
85570  Table *p = 0;
85571  int i;
85572  int nName;
85573  assert( zName!=0 );
85574  nName = sqlite3Strlen30(zName);
85575  /* All mutexes are required for schema access.  Make sure we hold them. */
85576  assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
85577  for(i=OMIT_TEMPDB; i<db->nDb; i++){
85578    int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
85579    if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
85580    assert( sqlite3SchemaMutexHeld(db, j, 0) );
85581    p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
85582    if( p ) break;
85583  }
85584  return p;
85585}
85586
85587/*
85588** Locate the in-memory structure that describes a particular database
85589** table given the name of that table and (optionally) the name of the
85590** database containing the table.  Return NULL if not found.  Also leave an
85591** error message in pParse->zErrMsg.
85592**
85593** The difference between this routine and sqlite3FindTable() is that this
85594** routine leaves an error message in pParse->zErrMsg where
85595** sqlite3FindTable() does not.
85596*/
85597SQLITE_PRIVATE Table *sqlite3LocateTable(
85598  Parse *pParse,         /* context in which to report errors */
85599  int isView,            /* True if looking for a VIEW rather than a TABLE */
85600  const char *zName,     /* Name of the table we are looking for */
85601  const char *zDbase     /* Name of the database.  Might be NULL */
85602){
85603  Table *p;
85604
85605  /* Read the database schema. If an error occurs, leave an error message
85606  ** and code in pParse and return NULL. */
85607  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
85608    return 0;
85609  }
85610
85611  p = sqlite3FindTable(pParse->db, zName, zDbase);
85612  if( p==0 ){
85613    const char *zMsg = isView ? "no such view" : "no such table";
85614    if( zDbase ){
85615      sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
85616    }else{
85617      sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
85618    }
85619    pParse->checkSchema = 1;
85620  }
85621  return p;
85622}
85623
85624/*
85625** Locate the table identified by *p.
85626**
85627** This is a wrapper around sqlite3LocateTable(). The difference between
85628** sqlite3LocateTable() and this function is that this function restricts
85629** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
85630** non-NULL if it is part of a view or trigger program definition. See
85631** sqlite3FixSrcList() for details.
85632*/
85633SQLITE_PRIVATE Table *sqlite3LocateTableItem(
85634  Parse *pParse,
85635  int isView,
85636  struct SrcList_item *p
85637){
85638  const char *zDb;
85639  assert( p->pSchema==0 || p->zDatabase==0 );
85640  if( p->pSchema ){
85641    int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
85642    zDb = pParse->db->aDb[iDb].zName;
85643  }else{
85644    zDb = p->zDatabase;
85645  }
85646  return sqlite3LocateTable(pParse, isView, p->zName, zDb);
85647}
85648
85649/*
85650** Locate the in-memory structure that describes
85651** a particular index given the name of that index
85652** and the name of the database that contains the index.
85653** Return NULL if not found.
85654**
85655** If zDatabase is 0, all databases are searched for the
85656** table and the first matching index is returned.  (No checking
85657** for duplicate index names is done.)  The search order is
85658** TEMP first, then MAIN, then any auxiliary databases added
85659** using the ATTACH command.
85660*/
85661SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
85662  Index *p = 0;
85663  int i;
85664  int nName = sqlite3Strlen30(zName);
85665  /* All mutexes are required for schema access.  Make sure we hold them. */
85666  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
85667  for(i=OMIT_TEMPDB; i<db->nDb; i++){
85668    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
85669    Schema *pSchema = db->aDb[j].pSchema;
85670    assert( pSchema );
85671    if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
85672    assert( sqlite3SchemaMutexHeld(db, j, 0) );
85673    p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
85674    if( p ) break;
85675  }
85676  return p;
85677}
85678
85679/*
85680** Reclaim the memory used by an index
85681*/
85682static void freeIndex(sqlite3 *db, Index *p){
85683#ifndef SQLITE_OMIT_ANALYZE
85684  sqlite3DeleteIndexSamples(db, p);
85685#endif
85686  if( db==0 || db->pnBytesFreed==0 ) sqlite3KeyInfoUnref(p->pKeyInfo);
85687  sqlite3ExprDelete(db, p->pPartIdxWhere);
85688  sqlite3DbFree(db, p->zColAff);
85689  if( p->isResized ) sqlite3DbFree(db, p->azColl);
85690  sqlite3DbFree(db, p);
85691}
85692
85693/*
85694** For the index called zIdxName which is found in the database iDb,
85695** unlike that index from its Table then remove the index from
85696** the index hash table and free all memory structures associated
85697** with the index.
85698*/
85699SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
85700  Index *pIndex;
85701  int len;
85702  Hash *pHash;
85703
85704  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
85705  pHash = &db->aDb[iDb].pSchema->idxHash;
85706  len = sqlite3Strlen30(zIdxName);
85707  pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
85708  if( ALWAYS(pIndex) ){
85709    if( pIndex->pTable->pIndex==pIndex ){
85710      pIndex->pTable->pIndex = pIndex->pNext;
85711    }else{
85712      Index *p;
85713      /* Justification of ALWAYS();  The index must be on the list of
85714      ** indices. */
85715      p = pIndex->pTable->pIndex;
85716      while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
85717      if( ALWAYS(p && p->pNext==pIndex) ){
85718        p->pNext = pIndex->pNext;
85719      }
85720    }
85721    freeIndex(db, pIndex);
85722  }
85723  db->flags |= SQLITE_InternChanges;
85724}
85725
85726/*
85727** Look through the list of open database files in db->aDb[] and if
85728** any have been closed, remove them from the list.  Reallocate the
85729** db->aDb[] structure to a smaller size, if possible.
85730**
85731** Entry 0 (the "main" database) and entry 1 (the "temp" database)
85732** are never candidates for being collapsed.
85733*/
85734SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
85735  int i, j;
85736  for(i=j=2; i<db->nDb; i++){
85737    struct Db *pDb = &db->aDb[i];
85738    if( pDb->pBt==0 ){
85739      sqlite3DbFree(db, pDb->zName);
85740      pDb->zName = 0;
85741      continue;
85742    }
85743    if( j<i ){
85744      db->aDb[j] = db->aDb[i];
85745    }
85746    j++;
85747  }
85748  memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
85749  db->nDb = j;
85750  if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
85751    memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
85752    sqlite3DbFree(db, db->aDb);
85753    db->aDb = db->aDbStatic;
85754  }
85755}
85756
85757/*
85758** Reset the schema for the database at index iDb.  Also reset the
85759** TEMP schema.
85760*/
85761SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
85762  Db *pDb;
85763  assert( iDb<db->nDb );
85764
85765  /* Case 1:  Reset the single schema identified by iDb */
85766  pDb = &db->aDb[iDb];
85767  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
85768  assert( pDb->pSchema!=0 );
85769  sqlite3SchemaClear(pDb->pSchema);
85770
85771  /* If any database other than TEMP is reset, then also reset TEMP
85772  ** since TEMP might be holding triggers that reference tables in the
85773  ** other database.
85774  */
85775  if( iDb!=1 ){
85776    pDb = &db->aDb[1];
85777    assert( pDb->pSchema!=0 );
85778    sqlite3SchemaClear(pDb->pSchema);
85779  }
85780  return;
85781}
85782
85783/*
85784** Erase all schema information from all attached databases (including
85785** "main" and "temp") for a single database connection.
85786*/
85787SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
85788  int i;
85789  sqlite3BtreeEnterAll(db);
85790  for(i=0; i<db->nDb; i++){
85791    Db *pDb = &db->aDb[i];
85792    if( pDb->pSchema ){
85793      sqlite3SchemaClear(pDb->pSchema);
85794    }
85795  }
85796  db->flags &= ~SQLITE_InternChanges;
85797  sqlite3VtabUnlockList(db);
85798  sqlite3BtreeLeaveAll(db);
85799  sqlite3CollapseDatabaseArray(db);
85800}
85801
85802/*
85803** This routine is called when a commit occurs.
85804*/
85805SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
85806  db->flags &= ~SQLITE_InternChanges;
85807}
85808
85809/*
85810** Delete memory allocated for the column names of a table or view (the
85811** Table.aCol[] array).
85812*/
85813static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
85814  int i;
85815  Column *pCol;
85816  assert( pTable!=0 );
85817  if( (pCol = pTable->aCol)!=0 ){
85818    for(i=0; i<pTable->nCol; i++, pCol++){
85819      sqlite3DbFree(db, pCol->zName);
85820      sqlite3ExprDelete(db, pCol->pDflt);
85821      sqlite3DbFree(db, pCol->zDflt);
85822      sqlite3DbFree(db, pCol->zType);
85823      sqlite3DbFree(db, pCol->zColl);
85824    }
85825    sqlite3DbFree(db, pTable->aCol);
85826  }
85827}
85828
85829/*
85830** Remove the memory data structures associated with the given
85831** Table.  No changes are made to disk by this routine.
85832**
85833** This routine just deletes the data structure.  It does not unlink
85834** the table data structure from the hash table.  But it does destroy
85835** memory structures of the indices and foreign keys associated with
85836** the table.
85837**
85838** The db parameter is optional.  It is needed if the Table object
85839** contains lookaside memory.  (Table objects in the schema do not use
85840** lookaside memory, but some ephemeral Table objects do.)  Or the
85841** db parameter can be used with db->pnBytesFreed to measure the memory
85842** used by the Table object.
85843*/
85844SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
85845  Index *pIndex, *pNext;
85846  TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
85847
85848  assert( !pTable || pTable->nRef>0 );
85849
85850  /* Do not delete the table until the reference count reaches zero. */
85851  if( !pTable ) return;
85852  if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
85853
85854  /* Record the number of outstanding lookaside allocations in schema Tables
85855  ** prior to doing any free() operations.  Since schema Tables do not use
85856  ** lookaside, this number should not change. */
85857  TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
85858                         db->lookaside.nOut : 0 );
85859
85860  /* Delete all indices associated with this table. */
85861  for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
85862    pNext = pIndex->pNext;
85863    assert( pIndex->pSchema==pTable->pSchema );
85864    if( !db || db->pnBytesFreed==0 ){
85865      char *zName = pIndex->zName;
85866      TESTONLY ( Index *pOld = ) sqlite3HashInsert(
85867         &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
85868      );
85869      assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
85870      assert( pOld==pIndex || pOld==0 );
85871    }
85872    freeIndex(db, pIndex);
85873  }
85874
85875  /* Delete any foreign keys attached to this table. */
85876  sqlite3FkDelete(db, pTable);
85877
85878  /* Delete the Table structure itself.
85879  */
85880  sqliteDeleteColumnNames(db, pTable);
85881  sqlite3DbFree(db, pTable->zName);
85882  sqlite3DbFree(db, pTable->zColAff);
85883  sqlite3SelectDelete(db, pTable->pSelect);
85884#ifndef SQLITE_OMIT_CHECK
85885  sqlite3ExprListDelete(db, pTable->pCheck);
85886#endif
85887#ifndef SQLITE_OMIT_VIRTUALTABLE
85888  sqlite3VtabClear(db, pTable);
85889#endif
85890  sqlite3DbFree(db, pTable);
85891
85892  /* Verify that no lookaside memory was used by schema tables */
85893  assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
85894}
85895
85896/*
85897** Unlink the given table from the hash tables and the delete the
85898** table structure with all its indices and foreign keys.
85899*/
85900SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
85901  Table *p;
85902  Db *pDb;
85903
85904  assert( db!=0 );
85905  assert( iDb>=0 && iDb<db->nDb );
85906  assert( zTabName );
85907  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
85908  testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
85909  pDb = &db->aDb[iDb];
85910  p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
85911                        sqlite3Strlen30(zTabName),0);
85912  sqlite3DeleteTable(db, p);
85913  db->flags |= SQLITE_InternChanges;
85914}
85915
85916/*
85917** Given a token, return a string that consists of the text of that
85918** token.  Space to hold the returned string
85919** is obtained from sqliteMalloc() and must be freed by the calling
85920** function.
85921**
85922** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
85923** surround the body of the token are removed.
85924**
85925** Tokens are often just pointers into the original SQL text and so
85926** are not \000 terminated and are not persistent.  The returned string
85927** is \000 terminated and is persistent.
85928*/
85929SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
85930  char *zName;
85931  if( pName ){
85932    zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
85933    sqlite3Dequote(zName);
85934  }else{
85935    zName = 0;
85936  }
85937  return zName;
85938}
85939
85940/*
85941** Open the sqlite_master table stored in database number iDb for
85942** writing. The table is opened using cursor 0.
85943*/
85944SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
85945  Vdbe *v = sqlite3GetVdbe(p);
85946  sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
85947  sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
85948  if( p->nTab==0 ){
85949    p->nTab = 1;
85950  }
85951}
85952
85953/*
85954** Parameter zName points to a nul-terminated buffer containing the name
85955** of a database ("main", "temp" or the name of an attached db). This
85956** function returns the index of the named database in db->aDb[], or
85957** -1 if the named db cannot be found.
85958*/
85959SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
85960  int i = -1;         /* Database number */
85961  if( zName ){
85962    Db *pDb;
85963    int n = sqlite3Strlen30(zName);
85964    for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
85965      if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
85966          0==sqlite3StrICmp(pDb->zName, zName) ){
85967        break;
85968      }
85969    }
85970  }
85971  return i;
85972}
85973
85974/*
85975** The token *pName contains the name of a database (either "main" or
85976** "temp" or the name of an attached db). This routine returns the
85977** index of the named database in db->aDb[], or -1 if the named db
85978** does not exist.
85979*/
85980SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
85981  int i;                               /* Database number */
85982  char *zName;                         /* Name we are searching for */
85983  zName = sqlite3NameFromToken(db, pName);
85984  i = sqlite3FindDbName(db, zName);
85985  sqlite3DbFree(db, zName);
85986  return i;
85987}
85988
85989/* The table or view or trigger name is passed to this routine via tokens
85990** pName1 and pName2. If the table name was fully qualified, for example:
85991**
85992** CREATE TABLE xxx.yyy (...);
85993**
85994** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
85995** the table name is not fully qualified, i.e.:
85996**
85997** CREATE TABLE yyy(...);
85998**
85999** Then pName1 is set to "yyy" and pName2 is "".
86000**
86001** This routine sets the *ppUnqual pointer to point at the token (pName1 or
86002** pName2) that stores the unqualified table name.  The index of the
86003** database "xxx" is returned.
86004*/
86005SQLITE_PRIVATE int sqlite3TwoPartName(
86006  Parse *pParse,      /* Parsing and code generating context */
86007  Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
86008  Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
86009  Token **pUnqual     /* Write the unqualified object name here */
86010){
86011  int iDb;                    /* Database holding the object */
86012  sqlite3 *db = pParse->db;
86013
86014  if( ALWAYS(pName2!=0) && pName2->n>0 ){
86015    if( db->init.busy ) {
86016      sqlite3ErrorMsg(pParse, "corrupt database");
86017      pParse->nErr++;
86018      return -1;
86019    }
86020    *pUnqual = pName2;
86021    iDb = sqlite3FindDb(db, pName1);
86022    if( iDb<0 ){
86023      sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
86024      pParse->nErr++;
86025      return -1;
86026    }
86027  }else{
86028    assert( db->init.iDb==0 || db->init.busy );
86029    iDb = db->init.iDb;
86030    *pUnqual = pName1;
86031  }
86032  return iDb;
86033}
86034
86035/*
86036** This routine is used to check if the UTF-8 string zName is a legal
86037** unqualified name for a new schema object (table, index, view or
86038** trigger). All names are legal except those that begin with the string
86039** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
86040** is reserved for internal use.
86041*/
86042SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
86043  if( !pParse->db->init.busy && pParse->nested==0
86044          && (pParse->db->flags & SQLITE_WriteSchema)==0
86045          && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
86046    sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
86047    return SQLITE_ERROR;
86048  }
86049  return SQLITE_OK;
86050}
86051
86052/*
86053** Return the PRIMARY KEY index of a table
86054*/
86055SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
86056  Index *p;
86057  for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
86058  return p;
86059}
86060
86061/*
86062** Return the column of index pIdx that corresponds to table
86063** column iCol.  Return -1 if not found.
86064*/
86065SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
86066  int i;
86067  for(i=0; i<pIdx->nColumn; i++){
86068    if( iCol==pIdx->aiColumn[i] ) return i;
86069  }
86070  return -1;
86071}
86072
86073/*
86074** Begin constructing a new table representation in memory.  This is
86075** the first of several action routines that get called in response
86076** to a CREATE TABLE statement.  In particular, this routine is called
86077** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
86078** flag is true if the table should be stored in the auxiliary database
86079** file instead of in the main database file.  This is normally the case
86080** when the "TEMP" or "TEMPORARY" keyword occurs in between
86081** CREATE and TABLE.
86082**
86083** The new table record is initialized and put in pParse->pNewTable.
86084** As more of the CREATE TABLE statement is parsed, additional action
86085** routines will be called to add more information to this record.
86086** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
86087** is called to complete the construction of the new table record.
86088*/
86089SQLITE_PRIVATE void sqlite3StartTable(
86090  Parse *pParse,   /* Parser context */
86091  Token *pName1,   /* First part of the name of the table or view */
86092  Token *pName2,   /* Second part of the name of the table or view */
86093  int isTemp,      /* True if this is a TEMP table */
86094  int isView,      /* True if this is a VIEW */
86095  int isVirtual,   /* True if this is a VIRTUAL table */
86096  int noErr        /* Do nothing if table already exists */
86097){
86098  Table *pTable;
86099  char *zName = 0; /* The name of the new table */
86100  sqlite3 *db = pParse->db;
86101  Vdbe *v;
86102  int iDb;         /* Database number to create the table in */
86103  Token *pName;    /* Unqualified name of the table to create */
86104
86105  /* The table or view name to create is passed to this routine via tokens
86106  ** pName1 and pName2. If the table name was fully qualified, for example:
86107  **
86108  ** CREATE TABLE xxx.yyy (...);
86109  **
86110  ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
86111  ** the table name is not fully qualified, i.e.:
86112  **
86113  ** CREATE TABLE yyy(...);
86114  **
86115  ** Then pName1 is set to "yyy" and pName2 is "".
86116  **
86117  ** The call below sets the pName pointer to point at the token (pName1 or
86118  ** pName2) that stores the unqualified table name. The variable iDb is
86119  ** set to the index of the database that the table or view is to be
86120  ** created in.
86121  */
86122  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
86123  if( iDb<0 ) return;
86124  if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
86125    /* If creating a temp table, the name may not be qualified. Unless
86126    ** the database name is "temp" anyway.  */
86127    sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
86128    return;
86129  }
86130  if( !OMIT_TEMPDB && isTemp ) iDb = 1;
86131
86132  pParse->sNameToken = *pName;
86133  zName = sqlite3NameFromToken(db, pName);
86134  if( zName==0 ) return;
86135  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
86136    goto begin_table_error;
86137  }
86138  if( db->init.iDb==1 ) isTemp = 1;
86139#ifndef SQLITE_OMIT_AUTHORIZATION
86140  assert( (isTemp & 1)==isTemp );
86141  {
86142    int code;
86143    char *zDb = db->aDb[iDb].zName;
86144    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
86145      goto begin_table_error;
86146    }
86147    if( isView ){
86148      if( !OMIT_TEMPDB && isTemp ){
86149        code = SQLITE_CREATE_TEMP_VIEW;
86150      }else{
86151        code = SQLITE_CREATE_VIEW;
86152      }
86153    }else{
86154      if( !OMIT_TEMPDB && isTemp ){
86155        code = SQLITE_CREATE_TEMP_TABLE;
86156      }else{
86157        code = SQLITE_CREATE_TABLE;
86158      }
86159    }
86160    if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
86161      goto begin_table_error;
86162    }
86163  }
86164#endif
86165
86166  /* Make sure the new table name does not collide with an existing
86167  ** index or table name in the same database.  Issue an error message if
86168  ** it does. The exception is if the statement being parsed was passed
86169  ** to an sqlite3_declare_vtab() call. In that case only the column names
86170  ** and types will be used, so there is no need to test for namespace
86171  ** collisions.
86172  */
86173  if( !IN_DECLARE_VTAB ){
86174    char *zDb = db->aDb[iDb].zName;
86175    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
86176      goto begin_table_error;
86177    }
86178    pTable = sqlite3FindTable(db, zName, zDb);
86179    if( pTable ){
86180      if( !noErr ){
86181        sqlite3ErrorMsg(pParse, "table %T already exists", pName);
86182      }else{
86183        assert( !db->init.busy );
86184        sqlite3CodeVerifySchema(pParse, iDb);
86185      }
86186      goto begin_table_error;
86187    }
86188    if( sqlite3FindIndex(db, zName, zDb)!=0 ){
86189      sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
86190      goto begin_table_error;
86191    }
86192  }
86193
86194  pTable = sqlite3DbMallocZero(db, sizeof(Table));
86195  if( pTable==0 ){
86196    db->mallocFailed = 1;
86197    pParse->rc = SQLITE_NOMEM;
86198    pParse->nErr++;
86199    goto begin_table_error;
86200  }
86201  pTable->zName = zName;
86202  pTable->iPKey = -1;
86203  pTable->pSchema = db->aDb[iDb].pSchema;
86204  pTable->nRef = 1;
86205  pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
86206  assert( pParse->pNewTable==0 );
86207  pParse->pNewTable = pTable;
86208
86209  /* If this is the magic sqlite_sequence table used by autoincrement,
86210  ** then record a pointer to this table in the main database structure
86211  ** so that INSERT can find the table easily.
86212  */
86213#ifndef SQLITE_OMIT_AUTOINCREMENT
86214  if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
86215    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
86216    pTable->pSchema->pSeqTab = pTable;
86217  }
86218#endif
86219
86220  /* Begin generating the code that will insert the table record into
86221  ** the SQLITE_MASTER table.  Note in particular that we must go ahead
86222  ** and allocate the record number for the table entry now.  Before any
86223  ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
86224  ** indices to be created and the table record must come before the
86225  ** indices.  Hence, the record number for the table must be allocated
86226  ** now.
86227  */
86228  if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
86229    int j1;
86230    int fileFormat;
86231    int reg1, reg2, reg3;
86232    sqlite3BeginWriteOperation(pParse, 0, iDb);
86233
86234#ifndef SQLITE_OMIT_VIRTUALTABLE
86235    if( isVirtual ){
86236      sqlite3VdbeAddOp0(v, OP_VBegin);
86237    }
86238#endif
86239
86240    /* If the file format and encoding in the database have not been set,
86241    ** set them now.
86242    */
86243    reg1 = pParse->regRowid = ++pParse->nMem;
86244    reg2 = pParse->regRoot = ++pParse->nMem;
86245    reg3 = ++pParse->nMem;
86246    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
86247    sqlite3VdbeUsesBtree(v, iDb);
86248    j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
86249    fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
86250                  1 : SQLITE_MAX_FILE_FORMAT;
86251    sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
86252    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
86253    sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
86254    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
86255    sqlite3VdbeJumpHere(v, j1);
86256
86257    /* This just creates a place-holder record in the sqlite_master table.
86258    ** The record created does not contain anything yet.  It will be replaced
86259    ** by the real entry in code generated at sqlite3EndTable().
86260    **
86261    ** The rowid for the new entry is left in register pParse->regRowid.
86262    ** The root page number of the new table is left in reg pParse->regRoot.
86263    ** The rowid and root page number values are needed by the code that
86264    ** sqlite3EndTable will generate.
86265    */
86266#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
86267    if( isView || isVirtual ){
86268      sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
86269    }else
86270#endif
86271    {
86272      pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
86273    }
86274    sqlite3OpenMasterTable(pParse, iDb);
86275    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
86276    sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
86277    sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
86278    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
86279    sqlite3VdbeAddOp0(v, OP_Close);
86280  }
86281
86282  /* Normal (non-error) return. */
86283  return;
86284
86285  /* If an error occurs, we jump here */
86286begin_table_error:
86287  sqlite3DbFree(db, zName);
86288  return;
86289}
86290
86291/*
86292** This macro is used to compare two strings in a case-insensitive manner.
86293** It is slightly faster than calling sqlite3StrICmp() directly, but
86294** produces larger code.
86295**
86296** WARNING: This macro is not compatible with the strcmp() family. It
86297** returns true if the two strings are equal, otherwise false.
86298*/
86299#define STRICMP(x, y) (\
86300sqlite3UpperToLower[*(unsigned char *)(x)]==   \
86301sqlite3UpperToLower[*(unsigned char *)(y)]     \
86302&& sqlite3StrICmp((x)+1,(y)+1)==0 )
86303
86304/*
86305** Add a new column to the table currently being constructed.
86306**
86307** The parser calls this routine once for each column declaration
86308** in a CREATE TABLE statement.  sqlite3StartTable() gets called
86309** first to get things going.  Then this routine is called for each
86310** column.
86311*/
86312SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
86313  Table *p;
86314  int i;
86315  char *z;
86316  Column *pCol;
86317  sqlite3 *db = pParse->db;
86318  if( (p = pParse->pNewTable)==0 ) return;
86319#if SQLITE_MAX_COLUMN
86320  if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
86321    sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
86322    return;
86323  }
86324#endif
86325  z = sqlite3NameFromToken(db, pName);
86326  if( z==0 ) return;
86327  for(i=0; i<p->nCol; i++){
86328    if( STRICMP(z, p->aCol[i].zName) ){
86329      sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
86330      sqlite3DbFree(db, z);
86331      return;
86332    }
86333  }
86334  if( (p->nCol & 0x7)==0 ){
86335    Column *aNew;
86336    aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
86337    if( aNew==0 ){
86338      sqlite3DbFree(db, z);
86339      return;
86340    }
86341    p->aCol = aNew;
86342  }
86343  pCol = &p->aCol[p->nCol];
86344  memset(pCol, 0, sizeof(p->aCol[0]));
86345  pCol->zName = z;
86346
86347  /* If there is no type specified, columns have the default affinity
86348  ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
86349  ** be called next to set pCol->affinity correctly.
86350  */
86351  pCol->affinity = SQLITE_AFF_NONE;
86352  pCol->szEst = 1;
86353  p->nCol++;
86354}
86355
86356/*
86357** This routine is called by the parser while in the middle of
86358** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
86359** been seen on a column.  This routine sets the notNull flag on
86360** the column currently under construction.
86361*/
86362SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
86363  Table *p;
86364  p = pParse->pNewTable;
86365  if( p==0 || NEVER(p->nCol<1) ) return;
86366  p->aCol[p->nCol-1].notNull = (u8)onError;
86367}
86368
86369/*
86370** Scan the column type name zType (length nType) and return the
86371** associated affinity type.
86372**
86373** This routine does a case-independent search of zType for the
86374** substrings in the following table. If one of the substrings is
86375** found, the corresponding affinity is returned. If zType contains
86376** more than one of the substrings, entries toward the top of
86377** the table take priority. For example, if zType is 'BLOBINT',
86378** SQLITE_AFF_INTEGER is returned.
86379**
86380** Substring     | Affinity
86381** --------------------------------
86382** 'INT'         | SQLITE_AFF_INTEGER
86383** 'CHAR'        | SQLITE_AFF_TEXT
86384** 'CLOB'        | SQLITE_AFF_TEXT
86385** 'TEXT'        | SQLITE_AFF_TEXT
86386** 'BLOB'        | SQLITE_AFF_NONE
86387** 'REAL'        | SQLITE_AFF_REAL
86388** 'FLOA'        | SQLITE_AFF_REAL
86389** 'DOUB'        | SQLITE_AFF_REAL
86390**
86391** If none of the substrings in the above table are found,
86392** SQLITE_AFF_NUMERIC is returned.
86393*/
86394SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
86395  u32 h = 0;
86396  char aff = SQLITE_AFF_NUMERIC;
86397  const char *zChar = 0;
86398
86399  if( zIn==0 ) return aff;
86400  while( zIn[0] ){
86401    h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
86402    zIn++;
86403    if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
86404      aff = SQLITE_AFF_TEXT;
86405      zChar = zIn;
86406    }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
86407      aff = SQLITE_AFF_TEXT;
86408    }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
86409      aff = SQLITE_AFF_TEXT;
86410    }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
86411        && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
86412      aff = SQLITE_AFF_NONE;
86413      if( zIn[0]=='(' ) zChar = zIn;
86414#ifndef SQLITE_OMIT_FLOATING_POINT
86415    }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
86416        && aff==SQLITE_AFF_NUMERIC ){
86417      aff = SQLITE_AFF_REAL;
86418    }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
86419        && aff==SQLITE_AFF_NUMERIC ){
86420      aff = SQLITE_AFF_REAL;
86421    }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
86422        && aff==SQLITE_AFF_NUMERIC ){
86423      aff = SQLITE_AFF_REAL;
86424#endif
86425    }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
86426      aff = SQLITE_AFF_INTEGER;
86427      break;
86428    }
86429  }
86430
86431  /* If pszEst is not NULL, store an estimate of the field size.  The
86432  ** estimate is scaled so that the size of an integer is 1.  */
86433  if( pszEst ){
86434    *pszEst = 1;   /* default size is approx 4 bytes */
86435    if( aff<=SQLITE_AFF_NONE ){
86436      if( zChar ){
86437        while( zChar[0] ){
86438          if( sqlite3Isdigit(zChar[0]) ){
86439            int v = 0;
86440            sqlite3GetInt32(zChar, &v);
86441            v = v/4 + 1;
86442            if( v>255 ) v = 255;
86443            *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
86444            break;
86445          }
86446          zChar++;
86447        }
86448      }else{
86449        *pszEst = 5;   /* BLOB, TEXT, CLOB -> r=5  (approx 20 bytes)*/
86450      }
86451    }
86452  }
86453  return aff;
86454}
86455
86456/*
86457** This routine is called by the parser while in the middle of
86458** parsing a CREATE TABLE statement.  The pFirst token is the first
86459** token in the sequence of tokens that describe the type of the
86460** column currently under construction.   pLast is the last token
86461** in the sequence.  Use this information to construct a string
86462** that contains the typename of the column and store that string
86463** in zType.
86464*/
86465SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
86466  Table *p;
86467  Column *pCol;
86468
86469  p = pParse->pNewTable;
86470  if( p==0 || NEVER(p->nCol<1) ) return;
86471  pCol = &p->aCol[p->nCol-1];
86472  assert( pCol->zType==0 );
86473  pCol->zType = sqlite3NameFromToken(pParse->db, pType);
86474  pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
86475}
86476
86477/*
86478** The expression is the default value for the most recently added column
86479** of the table currently under construction.
86480**
86481** Default value expressions must be constant.  Raise an exception if this
86482** is not the case.
86483**
86484** This routine is called by the parser while in the middle of
86485** parsing a CREATE TABLE statement.
86486*/
86487SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
86488  Table *p;
86489  Column *pCol;
86490  sqlite3 *db = pParse->db;
86491  p = pParse->pNewTable;
86492  if( p!=0 ){
86493    pCol = &(p->aCol[p->nCol-1]);
86494    if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
86495      sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
86496          pCol->zName);
86497    }else{
86498      /* A copy of pExpr is used instead of the original, as pExpr contains
86499      ** tokens that point to volatile memory. The 'span' of the expression
86500      ** is required by pragma table_info.
86501      */
86502      sqlite3ExprDelete(db, pCol->pDflt);
86503      pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
86504      sqlite3DbFree(db, pCol->zDflt);
86505      pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
86506                                     (int)(pSpan->zEnd - pSpan->zStart));
86507    }
86508  }
86509  sqlite3ExprDelete(db, pSpan->pExpr);
86510}
86511
86512/*
86513** Designate the PRIMARY KEY for the table.  pList is a list of names
86514** of columns that form the primary key.  If pList is NULL, then the
86515** most recently added column of the table is the primary key.
86516**
86517** A table can have at most one primary key.  If the table already has
86518** a primary key (and this is the second primary key) then create an
86519** error.
86520**
86521** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
86522** then we will try to use that column as the rowid.  Set the Table.iPKey
86523** field of the table under construction to be the index of the
86524** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
86525** no INTEGER PRIMARY KEY.
86526**
86527** If the key is not an INTEGER PRIMARY KEY, then create a unique
86528** index for the key.  No index is created for INTEGER PRIMARY KEYs.
86529*/
86530SQLITE_PRIVATE void sqlite3AddPrimaryKey(
86531  Parse *pParse,    /* Parsing context */
86532  ExprList *pList,  /* List of field names to be indexed */
86533  int onError,      /* What to do with a uniqueness conflict */
86534  int autoInc,      /* True if the AUTOINCREMENT keyword is present */
86535  int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
86536){
86537  Table *pTab = pParse->pNewTable;
86538  char *zType = 0;
86539  int iCol = -1, i;
86540  int nTerm;
86541  if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
86542  if( pTab->tabFlags & TF_HasPrimaryKey ){
86543    sqlite3ErrorMsg(pParse,
86544      "table \"%s\" has more than one primary key", pTab->zName);
86545    goto primary_key_exit;
86546  }
86547  pTab->tabFlags |= TF_HasPrimaryKey;
86548  if( pList==0 ){
86549    iCol = pTab->nCol - 1;
86550    pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
86551    zType = pTab->aCol[iCol].zType;
86552    nTerm = 1;
86553  }else{
86554    nTerm = pList->nExpr;
86555    for(i=0; i<nTerm; i++){
86556      for(iCol=0; iCol<pTab->nCol; iCol++){
86557        if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
86558          pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
86559          zType = pTab->aCol[iCol].zType;
86560          break;
86561        }
86562      }
86563    }
86564  }
86565  if( nTerm==1
86566   && zType && sqlite3StrICmp(zType, "INTEGER")==0
86567   && sortOrder==SQLITE_SO_ASC
86568  ){
86569    pTab->iPKey = iCol;
86570    pTab->keyConf = (u8)onError;
86571    assert( autoInc==0 || autoInc==1 );
86572    pTab->tabFlags |= autoInc*TF_Autoincrement;
86573    if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
86574  }else if( autoInc ){
86575#ifndef SQLITE_OMIT_AUTOINCREMENT
86576    sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
86577       "INTEGER PRIMARY KEY");
86578#endif
86579  }else{
86580    Vdbe *v = pParse->pVdbe;
86581    Index *p;
86582    if( v ) pParse->addrSkipPK = sqlite3VdbeAddOp0(v, OP_Noop);
86583    p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
86584                           0, sortOrder, 0);
86585    if( p ){
86586      p->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
86587      if( v ) sqlite3VdbeJumpHere(v, pParse->addrSkipPK);
86588    }
86589    pList = 0;
86590  }
86591
86592primary_key_exit:
86593  sqlite3ExprListDelete(pParse->db, pList);
86594  return;
86595}
86596
86597/*
86598** Add a new CHECK constraint to the table currently under construction.
86599*/
86600SQLITE_PRIVATE void sqlite3AddCheckConstraint(
86601  Parse *pParse,    /* Parsing context */
86602  Expr *pCheckExpr  /* The check expression */
86603){
86604#ifndef SQLITE_OMIT_CHECK
86605  Table *pTab = pParse->pNewTable;
86606  sqlite3 *db = pParse->db;
86607  if( pTab && !IN_DECLARE_VTAB
86608   && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
86609  ){
86610    pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
86611    if( pParse->constraintName.n ){
86612      sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
86613    }
86614  }else
86615#endif
86616  {
86617    sqlite3ExprDelete(pParse->db, pCheckExpr);
86618  }
86619}
86620
86621/*
86622** Set the collation function of the most recently parsed table column
86623** to the CollSeq given.
86624*/
86625SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
86626  Table *p;
86627  int i;
86628  char *zColl;              /* Dequoted name of collation sequence */
86629  sqlite3 *db;
86630
86631  if( (p = pParse->pNewTable)==0 ) return;
86632  i = p->nCol-1;
86633  db = pParse->db;
86634  zColl = sqlite3NameFromToken(db, pToken);
86635  if( !zColl ) return;
86636
86637  if( sqlite3LocateCollSeq(pParse, zColl) ){
86638    Index *pIdx;
86639    sqlite3DbFree(db, p->aCol[i].zColl);
86640    p->aCol[i].zColl = zColl;
86641
86642    /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
86643    ** then an index may have been created on this column before the
86644    ** collation type was added. Correct this if it is the case.
86645    */
86646    for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
86647      assert( pIdx->nKeyCol==1 );
86648      if( pIdx->aiColumn[0]==i ){
86649        pIdx->azColl[0] = p->aCol[i].zColl;
86650      }
86651    }
86652  }else{
86653    sqlite3DbFree(db, zColl);
86654  }
86655}
86656
86657/*
86658** This function returns the collation sequence for database native text
86659** encoding identified by the string zName, length nName.
86660**
86661** If the requested collation sequence is not available, or not available
86662** in the database native encoding, the collation factory is invoked to
86663** request it. If the collation factory does not supply such a sequence,
86664** and the sequence is available in another text encoding, then that is
86665** returned instead.
86666**
86667** If no versions of the requested collations sequence are available, or
86668** another error occurs, NULL is returned and an error message written into
86669** pParse.
86670**
86671** This routine is a wrapper around sqlite3FindCollSeq().  This routine
86672** invokes the collation factory if the named collation cannot be found
86673** and generates an error message.
86674**
86675** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
86676*/
86677SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
86678  sqlite3 *db = pParse->db;
86679  u8 enc = ENC(db);
86680  u8 initbusy = db->init.busy;
86681  CollSeq *pColl;
86682
86683  pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
86684  if( !initbusy && (!pColl || !pColl->xCmp) ){
86685    pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
86686  }
86687
86688  return pColl;
86689}
86690
86691
86692/*
86693** Generate code that will increment the schema cookie.
86694**
86695** The schema cookie is used to determine when the schema for the
86696** database changes.  After each schema change, the cookie value
86697** changes.  When a process first reads the schema it records the
86698** cookie.  Thereafter, whenever it goes to access the database,
86699** it checks the cookie to make sure the schema has not changed
86700** since it was last read.
86701**
86702** This plan is not completely bullet-proof.  It is possible for
86703** the schema to change multiple times and for the cookie to be
86704** set back to prior value.  But schema changes are infrequent
86705** and the probability of hitting the same cookie value is only
86706** 1 chance in 2^32.  So we're safe enough.
86707*/
86708SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
86709  int r1 = sqlite3GetTempReg(pParse);
86710  sqlite3 *db = pParse->db;
86711  Vdbe *v = pParse->pVdbe;
86712  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
86713  sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
86714  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
86715  sqlite3ReleaseTempReg(pParse, r1);
86716}
86717
86718/*
86719** Measure the number of characters needed to output the given
86720** identifier.  The number returned includes any quotes used
86721** but does not include the null terminator.
86722**
86723** The estimate is conservative.  It might be larger that what is
86724** really needed.
86725*/
86726static int identLength(const char *z){
86727  int n;
86728  for(n=0; *z; n++, z++){
86729    if( *z=='"' ){ n++; }
86730  }
86731  return n + 2;
86732}
86733
86734/*
86735** The first parameter is a pointer to an output buffer. The second
86736** parameter is a pointer to an integer that contains the offset at
86737** which to write into the output buffer. This function copies the
86738** nul-terminated string pointed to by the third parameter, zSignedIdent,
86739** to the specified offset in the buffer and updates *pIdx to refer
86740** to the first byte after the last byte written before returning.
86741**
86742** If the string zSignedIdent consists entirely of alpha-numeric
86743** characters, does not begin with a digit and is not an SQL keyword,
86744** then it is copied to the output buffer exactly as it is. Otherwise,
86745** it is quoted using double-quotes.
86746*/
86747static void identPut(char *z, int *pIdx, char *zSignedIdent){
86748  unsigned char *zIdent = (unsigned char*)zSignedIdent;
86749  int i, j, needQuote;
86750  i = *pIdx;
86751
86752  for(j=0; zIdent[j]; j++){
86753    if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
86754  }
86755  needQuote = sqlite3Isdigit(zIdent[0])
86756            || sqlite3KeywordCode(zIdent, j)!=TK_ID
86757            || zIdent[j]!=0
86758            || j==0;
86759
86760  if( needQuote ) z[i++] = '"';
86761  for(j=0; zIdent[j]; j++){
86762    z[i++] = zIdent[j];
86763    if( zIdent[j]=='"' ) z[i++] = '"';
86764  }
86765  if( needQuote ) z[i++] = '"';
86766  z[i] = 0;
86767  *pIdx = i;
86768}
86769
86770/*
86771** Generate a CREATE TABLE statement appropriate for the given
86772** table.  Memory to hold the text of the statement is obtained
86773** from sqliteMalloc() and must be freed by the calling function.
86774*/
86775static char *createTableStmt(sqlite3 *db, Table *p){
86776  int i, k, n;
86777  char *zStmt;
86778  char *zSep, *zSep2, *zEnd;
86779  Column *pCol;
86780  n = 0;
86781  for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
86782    n += identLength(pCol->zName) + 5;
86783  }
86784  n += identLength(p->zName);
86785  if( n<50 ){
86786    zSep = "";
86787    zSep2 = ",";
86788    zEnd = ")";
86789  }else{
86790    zSep = "\n  ";
86791    zSep2 = ",\n  ";
86792    zEnd = "\n)";
86793  }
86794  n += 35 + 6*p->nCol;
86795  zStmt = sqlite3DbMallocRaw(0, n);
86796  if( zStmt==0 ){
86797    db->mallocFailed = 1;
86798    return 0;
86799  }
86800  sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
86801  k = sqlite3Strlen30(zStmt);
86802  identPut(zStmt, &k, p->zName);
86803  zStmt[k++] = '(';
86804  for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
86805    static const char * const azType[] = {
86806        /* SQLITE_AFF_TEXT    */ " TEXT",
86807        /* SQLITE_AFF_NONE    */ "",
86808        /* SQLITE_AFF_NUMERIC */ " NUM",
86809        /* SQLITE_AFF_INTEGER */ " INT",
86810        /* SQLITE_AFF_REAL    */ " REAL"
86811    };
86812    int len;
86813    const char *zType;
86814
86815    sqlite3_snprintf(n-k, &zStmt[k], zSep);
86816    k += sqlite3Strlen30(&zStmt[k]);
86817    zSep = zSep2;
86818    identPut(zStmt, &k, pCol->zName);
86819    assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
86820    assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
86821    testcase( pCol->affinity==SQLITE_AFF_TEXT );
86822    testcase( pCol->affinity==SQLITE_AFF_NONE );
86823    testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
86824    testcase( pCol->affinity==SQLITE_AFF_INTEGER );
86825    testcase( pCol->affinity==SQLITE_AFF_REAL );
86826
86827    zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
86828    len = sqlite3Strlen30(zType);
86829    assert( pCol->affinity==SQLITE_AFF_NONE
86830            || pCol->affinity==sqlite3AffinityType(zType, 0) );
86831    memcpy(&zStmt[k], zType, len);
86832    k += len;
86833    assert( k<=n );
86834  }
86835  sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
86836  return zStmt;
86837}
86838
86839/*
86840** Resize an Index object to hold N columns total.  Return SQLITE_OK
86841** on success and SQLITE_NOMEM on an OOM error.
86842*/
86843static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
86844  char *zExtra;
86845  int nByte;
86846  if( pIdx->nColumn>=N ) return SQLITE_OK;
86847  assert( pIdx->isResized==0 );
86848  nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
86849  zExtra = sqlite3DbMallocZero(db, nByte);
86850  if( zExtra==0 ) return SQLITE_NOMEM;
86851  memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
86852  pIdx->azColl = (char**)zExtra;
86853  zExtra += sizeof(char*)*N;
86854  memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
86855  pIdx->aiColumn = (i16*)zExtra;
86856  zExtra += sizeof(i16)*N;
86857  memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
86858  pIdx->aSortOrder = (u8*)zExtra;
86859  pIdx->nColumn = N;
86860  pIdx->isResized = 1;
86861  return SQLITE_OK;
86862}
86863
86864/*
86865** Estimate the total row width for a table.
86866*/
86867static void estimateTableWidth(Table *pTab){
86868  unsigned wTable = 0;
86869  const Column *pTabCol;
86870  int i;
86871  for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
86872    wTable += pTabCol->szEst;
86873  }
86874  if( pTab->iPKey<0 ) wTable++;
86875  pTab->szTabRow = sqlite3LogEst(wTable*4);
86876}
86877
86878/*
86879** Estimate the average size of a row for an index.
86880*/
86881static void estimateIndexWidth(Index *pIdx){
86882  unsigned wIndex = 0;
86883  int i;
86884  const Column *aCol = pIdx->pTable->aCol;
86885  for(i=0; i<pIdx->nColumn; i++){
86886    i16 x = pIdx->aiColumn[i];
86887    assert( x<pIdx->pTable->nCol );
86888    wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
86889  }
86890  pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
86891}
86892
86893/* Return true if value x is found any of the first nCol entries of aiCol[]
86894*/
86895static int hasColumn(const i16 *aiCol, int nCol, int x){
86896  while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
86897  return 0;
86898}
86899
86900/*
86901** This routine runs at the end of parsing a CREATE TABLE statement that
86902** has a WITHOUT ROWID clause.  The job of this routine is to convert both
86903** internal schema data structures and the generated VDBE code so that they
86904** are appropriate for a WITHOUT ROWID table instead of a rowid table.
86905** Changes include:
86906**
86907**     (1)  Convert the OP_CreateTable into an OP_CreateIndex.  There is
86908**          no rowid btree for a WITHOUT ROWID.  Instead, the canonical
86909**          data storage is a covering index btree.
86910**     (2)  Bypass the creation of the sqlite_master table entry
86911**          for the PRIMARY KEY as the the primary key index is now
86912**          identified by the sqlite_master table entry of the table itself.
86913**     (3)  Set the Index.tnum of the PRIMARY KEY Index object in the
86914**          schema to the rootpage from the main table.
86915**     (4)  Set all columns of the PRIMARY KEY schema object to be NOT NULL.
86916**     (5)  Add all table columns to the PRIMARY KEY Index object
86917**          so that the PRIMARY KEY is a covering index.  The surplus
86918**          columns are part of KeyInfo.nXField and are not used for
86919**          sorting or lookup or uniqueness checks.
86920**     (6)  Replace the rowid tail on all automatically generated UNIQUE
86921**          indices with the PRIMARY KEY columns.
86922*/
86923static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
86924  Index *pIdx;
86925  Index *pPk;
86926  int nPk;
86927  int i, j;
86928  sqlite3 *db = pParse->db;
86929  Vdbe *v = pParse->pVdbe;
86930
86931  /* Convert the OP_CreateTable opcode that would normally create the
86932  ** root-page for the table into a OP_CreateIndex opcode.  The index
86933  ** created will become the PRIMARY KEY index.
86934  */
86935  if( pParse->addrCrTab ){
86936    assert( v );
86937    sqlite3VdbeGetOp(v, pParse->addrCrTab)->opcode = OP_CreateIndex;
86938  }
86939
86940  /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
86941  ** table entry.
86942  */
86943  if( pParse->addrSkipPK ){
86944    assert( v );
86945    sqlite3VdbeGetOp(v, pParse->addrSkipPK)->opcode = OP_Goto;
86946  }
86947
86948  /* Locate the PRIMARY KEY index.  Or, if this table was originally
86949  ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
86950  */
86951  if( pTab->iPKey>=0 ){
86952    ExprList *pList;
86953    pList = sqlite3ExprListAppend(pParse, 0, 0);
86954    if( pList==0 ) return;
86955    pList->a[0].zName = sqlite3DbStrDup(pParse->db,
86956                                        pTab->aCol[pTab->iPKey].zName);
86957    pList->a[0].sortOrder = pParse->iPkSortOrder;
86958    assert( pParse->pNewTable==pTab );
86959    pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
86960    if( pPk==0 ) return;
86961    pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
86962    pTab->iPKey = -1;
86963  }else{
86964    pPk = sqlite3PrimaryKeyIndex(pTab);
86965  }
86966  pPk->isCovering = 1;
86967  assert( pPk!=0 );
86968  nPk = pPk->nKeyCol;
86969
86970  /* Make sure every column of the PRIMARY KEY is NOT NULL */
86971  for(i=0; i<nPk; i++){
86972    pTab->aCol[pPk->aiColumn[i]].notNull = 1;
86973  }
86974  pPk->uniqNotNull = 1;
86975
86976  /* The root page of the PRIMARY KEY is the table root page */
86977  pPk->tnum = pTab->tnum;
86978
86979  /* Update the in-memory representation of all UNIQUE indices by converting
86980  ** the final rowid column into one or more columns of the PRIMARY KEY.
86981  */
86982  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
86983    int n;
86984    if( IsPrimaryKeyIndex(pIdx) ) continue;
86985    for(i=n=0; i<nPk; i++){
86986      if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
86987    }
86988    if( n==0 ){
86989      /* This index is a superset of the primary key */
86990      pIdx->nColumn = pIdx->nKeyCol;
86991      continue;
86992    }
86993    if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
86994    for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
86995      if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
86996        pIdx->aiColumn[j] = pPk->aiColumn[i];
86997        pIdx->azColl[j] = pPk->azColl[i];
86998        j++;
86999      }
87000    }
87001    assert( pIdx->nColumn>=pIdx->nKeyCol+n );
87002    assert( pIdx->nColumn>=j );
87003  }
87004
87005  /* Add all table columns to the PRIMARY KEY index
87006  */
87007  if( nPk<pTab->nCol ){
87008    if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
87009    for(i=0, j=nPk; i<pTab->nCol; i++){
87010      if( !hasColumn(pPk->aiColumn, j, i) ){
87011        assert( j<pPk->nColumn );
87012        pPk->aiColumn[j] = i;
87013        pPk->azColl[j] = "BINARY";
87014        j++;
87015      }
87016    }
87017    assert( pPk->nColumn==j );
87018    assert( pTab->nCol==j );
87019  }else{
87020    pPk->nColumn = pTab->nCol;
87021  }
87022}
87023
87024/*
87025** This routine is called to report the final ")" that terminates
87026** a CREATE TABLE statement.
87027**
87028** The table structure that other action routines have been building
87029** is added to the internal hash tables, assuming no errors have
87030** occurred.
87031**
87032** An entry for the table is made in the master table on disk, unless
87033** this is a temporary table or db->init.busy==1.  When db->init.busy==1
87034** it means we are reading the sqlite_master table because we just
87035** connected to the database or because the sqlite_master table has
87036** recently changed, so the entry for this table already exists in
87037** the sqlite_master table.  We do not want to create it again.
87038**
87039** If the pSelect argument is not NULL, it means that this routine
87040** was called to create a table generated from a
87041** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
87042** the new table will match the result set of the SELECT.
87043*/
87044SQLITE_PRIVATE void sqlite3EndTable(
87045  Parse *pParse,          /* Parse context */
87046  Token *pCons,           /* The ',' token after the last column defn. */
87047  Token *pEnd,            /* The ')' before options in the CREATE TABLE */
87048  u8 tabOpts,             /* Extra table options. Usually 0. */
87049  Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
87050){
87051  Table *p;                 /* The new table */
87052  sqlite3 *db = pParse->db; /* The database connection */
87053  int iDb;                  /* Database in which the table lives */
87054  Index *pIdx;              /* An implied index of the table */
87055
87056  if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
87057    return;
87058  }
87059  p = pParse->pNewTable;
87060  if( p==0 ) return;
87061
87062  assert( !db->init.busy || !pSelect );
87063
87064  /* If the db->init.busy is 1 it means we are reading the SQL off the
87065  ** "sqlite_master" or "sqlite_temp_master" table on the disk.
87066  ** So do not write to the disk again.  Extract the root page number
87067  ** for the table from the db->init.newTnum field.  (The page number
87068  ** should have been put there by the sqliteOpenCb routine.)
87069  */
87070  if( db->init.busy ){
87071    p->tnum = db->init.newTnum;
87072  }
87073
87074  /* Special processing for WITHOUT ROWID Tables */
87075  if( tabOpts & TF_WithoutRowid ){
87076    if( (p->tabFlags & TF_Autoincrement) ){
87077      sqlite3ErrorMsg(pParse,
87078          "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
87079      return;
87080    }
87081    if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
87082      sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
87083    }else{
87084      p->tabFlags |= TF_WithoutRowid;
87085      convertToWithoutRowidTable(pParse, p);
87086    }
87087  }
87088
87089  iDb = sqlite3SchemaToIndex(db, p->pSchema);
87090
87091#ifndef SQLITE_OMIT_CHECK
87092  /* Resolve names in all CHECK constraint expressions.
87093  */
87094  if( p->pCheck ){
87095    sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
87096  }
87097#endif /* !defined(SQLITE_OMIT_CHECK) */
87098
87099  /* Estimate the average row size for the table and for all implied indices */
87100  estimateTableWidth(p);
87101  for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
87102    estimateIndexWidth(pIdx);
87103  }
87104
87105  /* If not initializing, then create a record for the new table
87106  ** in the SQLITE_MASTER table of the database.
87107  **
87108  ** If this is a TEMPORARY table, write the entry into the auxiliary
87109  ** file instead of into the main database file.
87110  */
87111  if( !db->init.busy ){
87112    int n;
87113    Vdbe *v;
87114    char *zType;    /* "view" or "table" */
87115    char *zType2;   /* "VIEW" or "TABLE" */
87116    char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
87117
87118    v = sqlite3GetVdbe(pParse);
87119    if( NEVER(v==0) ) return;
87120
87121    sqlite3VdbeAddOp1(v, OP_Close, 0);
87122
87123    /*
87124    ** Initialize zType for the new view or table.
87125    */
87126    if( p->pSelect==0 ){
87127      /* A regular table */
87128      zType = "table";
87129      zType2 = "TABLE";
87130#ifndef SQLITE_OMIT_VIEW
87131    }else{
87132      /* A view */
87133      zType = "view";
87134      zType2 = "VIEW";
87135#endif
87136    }
87137
87138    /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
87139    ** statement to populate the new table. The root-page number for the
87140    ** new table is in register pParse->regRoot.
87141    **
87142    ** Once the SELECT has been coded by sqlite3Select(), it is in a
87143    ** suitable state to query for the column names and types to be used
87144    ** by the new table.
87145    **
87146    ** A shared-cache write-lock is not required to write to the new table,
87147    ** as a schema-lock must have already been obtained to create it. Since
87148    ** a schema-lock excludes all other database users, the write-lock would
87149    ** be redundant.
87150    */
87151    if( pSelect ){
87152      SelectDest dest;
87153      Table *pSelTab;
87154
87155      assert(pParse->nTab==1);
87156      sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
87157      sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
87158      pParse->nTab = 2;
87159      sqlite3SelectDestInit(&dest, SRT_Table, 1);
87160      sqlite3Select(pParse, pSelect, &dest);
87161      sqlite3VdbeAddOp1(v, OP_Close, 1);
87162      if( pParse->nErr==0 ){
87163        pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
87164        if( pSelTab==0 ) return;
87165        assert( p->aCol==0 );
87166        p->nCol = pSelTab->nCol;
87167        p->aCol = pSelTab->aCol;
87168        pSelTab->nCol = 0;
87169        pSelTab->aCol = 0;
87170        sqlite3DeleteTable(db, pSelTab);
87171      }
87172    }
87173
87174    /* Compute the complete text of the CREATE statement */
87175    if( pSelect ){
87176      zStmt = createTableStmt(db, p);
87177    }else{
87178      Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
87179      n = (int)(pEnd2->z - pParse->sNameToken.z);
87180      if( pEnd2->z[0]!=';' ) n += pEnd2->n;
87181      zStmt = sqlite3MPrintf(db,
87182          "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
87183      );
87184    }
87185
87186    /* A slot for the record has already been allocated in the
87187    ** SQLITE_MASTER table.  We just need to update that slot with all
87188    ** the information we've collected.
87189    */
87190    sqlite3NestedParse(pParse,
87191      "UPDATE %Q.%s "
87192         "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
87193       "WHERE rowid=#%d",
87194      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
87195      zType,
87196      p->zName,
87197      p->zName,
87198      pParse->regRoot,
87199      zStmt,
87200      pParse->regRowid
87201    );
87202    sqlite3DbFree(db, zStmt);
87203    sqlite3ChangeCookie(pParse, iDb);
87204
87205#ifndef SQLITE_OMIT_AUTOINCREMENT
87206    /* Check to see if we need to create an sqlite_sequence table for
87207    ** keeping track of autoincrement keys.
87208    */
87209    if( p->tabFlags & TF_Autoincrement ){
87210      Db *pDb = &db->aDb[iDb];
87211      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
87212      if( pDb->pSchema->pSeqTab==0 ){
87213        sqlite3NestedParse(pParse,
87214          "CREATE TABLE %Q.sqlite_sequence(name,seq)",
87215          pDb->zName
87216        );
87217      }
87218    }
87219#endif
87220
87221    /* Reparse everything to update our internal data structures */
87222    sqlite3VdbeAddParseSchemaOp(v, iDb,
87223           sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
87224  }
87225
87226
87227  /* Add the table to the in-memory representation of the database.
87228  */
87229  if( db->init.busy ){
87230    Table *pOld;
87231    Schema *pSchema = p->pSchema;
87232    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
87233    pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
87234                             sqlite3Strlen30(p->zName),p);
87235    if( pOld ){
87236      assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
87237      db->mallocFailed = 1;
87238      return;
87239    }
87240    pParse->pNewTable = 0;
87241    db->flags |= SQLITE_InternChanges;
87242
87243#ifndef SQLITE_OMIT_ALTERTABLE
87244    if( !p->pSelect ){
87245      const char *zName = (const char *)pParse->sNameToken.z;
87246      int nName;
87247      assert( !pSelect && pCons && pEnd );
87248      if( pCons->z==0 ){
87249        pCons = pEnd;
87250      }
87251      nName = (int)((const char *)pCons->z - zName);
87252      p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
87253    }
87254#endif
87255  }
87256}
87257
87258#ifndef SQLITE_OMIT_VIEW
87259/*
87260** The parser calls this routine in order to create a new VIEW
87261*/
87262SQLITE_PRIVATE void sqlite3CreateView(
87263  Parse *pParse,     /* The parsing context */
87264  Token *pBegin,     /* The CREATE token that begins the statement */
87265  Token *pName1,     /* The token that holds the name of the view */
87266  Token *pName2,     /* The token that holds the name of the view */
87267  Select *pSelect,   /* A SELECT statement that will become the new view */
87268  int isTemp,        /* TRUE for a TEMPORARY view */
87269  int noErr          /* Suppress error messages if VIEW already exists */
87270){
87271  Table *p;
87272  int n;
87273  const char *z;
87274  Token sEnd;
87275  DbFixer sFix;
87276  Token *pName = 0;
87277  int iDb;
87278  sqlite3 *db = pParse->db;
87279
87280  if( pParse->nVar>0 ){
87281    sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
87282    sqlite3SelectDelete(db, pSelect);
87283    return;
87284  }
87285  sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
87286  p = pParse->pNewTable;
87287  if( p==0 || pParse->nErr ){
87288    sqlite3SelectDelete(db, pSelect);
87289    return;
87290  }
87291  sqlite3TwoPartName(pParse, pName1, pName2, &pName);
87292  iDb = sqlite3SchemaToIndex(db, p->pSchema);
87293  sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
87294  if( sqlite3FixSelect(&sFix, pSelect) ){
87295    sqlite3SelectDelete(db, pSelect);
87296    return;
87297  }
87298
87299  /* Make a copy of the entire SELECT statement that defines the view.
87300  ** This will force all the Expr.token.z values to be dynamically
87301  ** allocated rather than point to the input string - which means that
87302  ** they will persist after the current sqlite3_exec() call returns.
87303  */
87304  p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
87305  sqlite3SelectDelete(db, pSelect);
87306  if( db->mallocFailed ){
87307    return;
87308  }
87309  if( !db->init.busy ){
87310    sqlite3ViewGetColumnNames(pParse, p);
87311  }
87312
87313  /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
87314  ** the end.
87315  */
87316  sEnd = pParse->sLastToken;
87317  if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
87318    sEnd.z += sEnd.n;
87319  }
87320  sEnd.n = 0;
87321  n = (int)(sEnd.z - pBegin->z);
87322  z = pBegin->z;
87323  while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
87324  sEnd.z = &z[n-1];
87325  sEnd.n = 1;
87326
87327  /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
87328  sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
87329  return;
87330}
87331#endif /* SQLITE_OMIT_VIEW */
87332
87333#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
87334/*
87335** The Table structure pTable is really a VIEW.  Fill in the names of
87336** the columns of the view in the pTable structure.  Return the number
87337** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
87338*/
87339SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
87340  Table *pSelTab;   /* A fake table from which we get the result set */
87341  Select *pSel;     /* Copy of the SELECT that implements the view */
87342  int nErr = 0;     /* Number of errors encountered */
87343  int n;            /* Temporarily holds the number of cursors assigned */
87344  sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
87345  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
87346
87347  assert( pTable );
87348
87349#ifndef SQLITE_OMIT_VIRTUALTABLE
87350  if( sqlite3VtabCallConnect(pParse, pTable) ){
87351    return SQLITE_ERROR;
87352  }
87353  if( IsVirtual(pTable) ) return 0;
87354#endif
87355
87356#ifndef SQLITE_OMIT_VIEW
87357  /* A positive nCol means the columns names for this view are
87358  ** already known.
87359  */
87360  if( pTable->nCol>0 ) return 0;
87361
87362  /* A negative nCol is a special marker meaning that we are currently
87363  ** trying to compute the column names.  If we enter this routine with
87364  ** a negative nCol, it means two or more views form a loop, like this:
87365  **
87366  **     CREATE VIEW one AS SELECT * FROM two;
87367  **     CREATE VIEW two AS SELECT * FROM one;
87368  **
87369  ** Actually, the error above is now caught prior to reaching this point.
87370  ** But the following test is still important as it does come up
87371  ** in the following:
87372  **
87373  **     CREATE TABLE main.ex1(a);
87374  **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
87375  **     SELECT * FROM temp.ex1;
87376  */
87377  if( pTable->nCol<0 ){
87378    sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
87379    return 1;
87380  }
87381  assert( pTable->nCol>=0 );
87382
87383  /* If we get this far, it means we need to compute the table names.
87384  ** Note that the call to sqlite3ResultSetOfSelect() will expand any
87385  ** "*" elements in the results set of the view and will assign cursors
87386  ** to the elements of the FROM clause.  But we do not want these changes
87387  ** to be permanent.  So the computation is done on a copy of the SELECT
87388  ** statement that defines the view.
87389  */
87390  assert( pTable->pSelect );
87391  pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
87392  if( pSel ){
87393    u8 enableLookaside = db->lookaside.bEnabled;
87394    n = pParse->nTab;
87395    sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
87396    pTable->nCol = -1;
87397    db->lookaside.bEnabled = 0;
87398#ifndef SQLITE_OMIT_AUTHORIZATION
87399    xAuth = db->xAuth;
87400    db->xAuth = 0;
87401    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
87402    db->xAuth = xAuth;
87403#else
87404    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
87405#endif
87406    db->lookaside.bEnabled = enableLookaside;
87407    pParse->nTab = n;
87408    if( pSelTab ){
87409      assert( pTable->aCol==0 );
87410      pTable->nCol = pSelTab->nCol;
87411      pTable->aCol = pSelTab->aCol;
87412      pSelTab->nCol = 0;
87413      pSelTab->aCol = 0;
87414      sqlite3DeleteTable(db, pSelTab);
87415      assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
87416      pTable->pSchema->flags |= DB_UnresetViews;
87417    }else{
87418      pTable->nCol = 0;
87419      nErr++;
87420    }
87421    sqlite3SelectDelete(db, pSel);
87422  } else {
87423    nErr++;
87424  }
87425#endif /* SQLITE_OMIT_VIEW */
87426  return nErr;
87427}
87428#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
87429
87430#ifndef SQLITE_OMIT_VIEW
87431/*
87432** Clear the column names from every VIEW in database idx.
87433*/
87434static void sqliteViewResetAll(sqlite3 *db, int idx){
87435  HashElem *i;
87436  assert( sqlite3SchemaMutexHeld(db, idx, 0) );
87437  if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
87438  for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
87439    Table *pTab = sqliteHashData(i);
87440    if( pTab->pSelect ){
87441      sqliteDeleteColumnNames(db, pTab);
87442      pTab->aCol = 0;
87443      pTab->nCol = 0;
87444    }
87445  }
87446  DbClearProperty(db, idx, DB_UnresetViews);
87447}
87448#else
87449# define sqliteViewResetAll(A,B)
87450#endif /* SQLITE_OMIT_VIEW */
87451
87452/*
87453** This function is called by the VDBE to adjust the internal schema
87454** used by SQLite when the btree layer moves a table root page. The
87455** root-page of a table or index in database iDb has changed from iFrom
87456** to iTo.
87457**
87458** Ticket #1728:  The symbol table might still contain information
87459** on tables and/or indices that are the process of being deleted.
87460** If you are unlucky, one of those deleted indices or tables might
87461** have the same rootpage number as the real table or index that is
87462** being moved.  So we cannot stop searching after the first match
87463** because the first match might be for one of the deleted indices
87464** or tables and not the table/index that is actually being moved.
87465** We must continue looping until all tables and indices with
87466** rootpage==iFrom have been converted to have a rootpage of iTo
87467** in order to be certain that we got the right one.
87468*/
87469#ifndef SQLITE_OMIT_AUTOVACUUM
87470SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
87471  HashElem *pElem;
87472  Hash *pHash;
87473  Db *pDb;
87474
87475  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
87476  pDb = &db->aDb[iDb];
87477  pHash = &pDb->pSchema->tblHash;
87478  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
87479    Table *pTab = sqliteHashData(pElem);
87480    if( pTab->tnum==iFrom ){
87481      pTab->tnum = iTo;
87482    }
87483  }
87484  pHash = &pDb->pSchema->idxHash;
87485  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
87486    Index *pIdx = sqliteHashData(pElem);
87487    if( pIdx->tnum==iFrom ){
87488      pIdx->tnum = iTo;
87489    }
87490  }
87491}
87492#endif
87493
87494/*
87495** Write code to erase the table with root-page iTable from database iDb.
87496** Also write code to modify the sqlite_master table and internal schema
87497** if a root-page of another table is moved by the btree-layer whilst
87498** erasing iTable (this can happen with an auto-vacuum database).
87499*/
87500static void destroyRootPage(Parse *pParse, int iTable, int iDb){
87501  Vdbe *v = sqlite3GetVdbe(pParse);
87502  int r1 = sqlite3GetTempReg(pParse);
87503  sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
87504  sqlite3MayAbort(pParse);
87505#ifndef SQLITE_OMIT_AUTOVACUUM
87506  /* OP_Destroy stores an in integer r1. If this integer
87507  ** is non-zero, then it is the root page number of a table moved to
87508  ** location iTable. The following code modifies the sqlite_master table to
87509  ** reflect this.
87510  **
87511  ** The "#NNN" in the SQL is a special constant that means whatever value
87512  ** is in register NNN.  See grammar rules associated with the TK_REGISTER
87513  ** token for additional information.
87514  */
87515  sqlite3NestedParse(pParse,
87516     "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
87517     pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
87518#endif
87519  sqlite3ReleaseTempReg(pParse, r1);
87520}
87521
87522/*
87523** Write VDBE code to erase table pTab and all associated indices on disk.
87524** Code to update the sqlite_master tables and internal schema definitions
87525** in case a root-page belonging to another table is moved by the btree layer
87526** is also added (this can happen with an auto-vacuum database).
87527*/
87528static void destroyTable(Parse *pParse, Table *pTab){
87529#ifdef SQLITE_OMIT_AUTOVACUUM
87530  Index *pIdx;
87531  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
87532  destroyRootPage(pParse, pTab->tnum, iDb);
87533  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
87534    destroyRootPage(pParse, pIdx->tnum, iDb);
87535  }
87536#else
87537  /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
87538  ** is not defined), then it is important to call OP_Destroy on the
87539  ** table and index root-pages in order, starting with the numerically
87540  ** largest root-page number. This guarantees that none of the root-pages
87541  ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
87542  ** following were coded:
87543  **
87544  ** OP_Destroy 4 0
87545  ** ...
87546  ** OP_Destroy 5 0
87547  **
87548  ** and root page 5 happened to be the largest root-page number in the
87549  ** database, then root page 5 would be moved to page 4 by the
87550  ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
87551  ** a free-list page.
87552  */
87553  int iTab = pTab->tnum;
87554  int iDestroyed = 0;
87555
87556  while( 1 ){
87557    Index *pIdx;
87558    int iLargest = 0;
87559
87560    if( iDestroyed==0 || iTab<iDestroyed ){
87561      iLargest = iTab;
87562    }
87563    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
87564      int iIdx = pIdx->tnum;
87565      assert( pIdx->pSchema==pTab->pSchema );
87566      if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
87567        iLargest = iIdx;
87568      }
87569    }
87570    if( iLargest==0 ){
87571      return;
87572    }else{
87573      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
87574      assert( iDb>=0 && iDb<pParse->db->nDb );
87575      destroyRootPage(pParse, iLargest, iDb);
87576      iDestroyed = iLargest;
87577    }
87578  }
87579#endif
87580}
87581
87582/*
87583** Remove entries from the sqlite_statN tables (for N in (1,2,3))
87584** after a DROP INDEX or DROP TABLE command.
87585*/
87586static void sqlite3ClearStatTables(
87587  Parse *pParse,         /* The parsing context */
87588  int iDb,               /* The database number */
87589  const char *zType,     /* "idx" or "tbl" */
87590  const char *zName      /* Name of index or table */
87591){
87592  int i;
87593  const char *zDbName = pParse->db->aDb[iDb].zName;
87594  for(i=1; i<=4; i++){
87595    char zTab[24];
87596    sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
87597    if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
87598      sqlite3NestedParse(pParse,
87599        "DELETE FROM %Q.%s WHERE %s=%Q",
87600        zDbName, zTab, zType, zName
87601      );
87602    }
87603  }
87604}
87605
87606/*
87607** Generate code to drop a table.
87608*/
87609SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
87610  Vdbe *v;
87611  sqlite3 *db = pParse->db;
87612  Trigger *pTrigger;
87613  Db *pDb = &db->aDb[iDb];
87614
87615  v = sqlite3GetVdbe(pParse);
87616  assert( v!=0 );
87617  sqlite3BeginWriteOperation(pParse, 1, iDb);
87618
87619#ifndef SQLITE_OMIT_VIRTUALTABLE
87620  if( IsVirtual(pTab) ){
87621    sqlite3VdbeAddOp0(v, OP_VBegin);
87622  }
87623#endif
87624
87625  /* Drop all triggers associated with the table being dropped. Code
87626  ** is generated to remove entries from sqlite_master and/or
87627  ** sqlite_temp_master if required.
87628  */
87629  pTrigger = sqlite3TriggerList(pParse, pTab);
87630  while( pTrigger ){
87631    assert( pTrigger->pSchema==pTab->pSchema ||
87632        pTrigger->pSchema==db->aDb[1].pSchema );
87633    sqlite3DropTriggerPtr(pParse, pTrigger);
87634    pTrigger = pTrigger->pNext;
87635  }
87636
87637#ifndef SQLITE_OMIT_AUTOINCREMENT
87638  /* Remove any entries of the sqlite_sequence table associated with
87639  ** the table being dropped. This is done before the table is dropped
87640  ** at the btree level, in case the sqlite_sequence table needs to
87641  ** move as a result of the drop (can happen in auto-vacuum mode).
87642  */
87643  if( pTab->tabFlags & TF_Autoincrement ){
87644    sqlite3NestedParse(pParse,
87645      "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
87646      pDb->zName, pTab->zName
87647    );
87648  }
87649#endif
87650
87651  /* Drop all SQLITE_MASTER table and index entries that refer to the
87652  ** table. The program name loops through the master table and deletes
87653  ** every row that refers to a table of the same name as the one being
87654  ** dropped. Triggers are handled separately because a trigger can be
87655  ** created in the temp database that refers to a table in another
87656  ** database.
87657  */
87658  sqlite3NestedParse(pParse,
87659      "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
87660      pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
87661  if( !isView && !IsVirtual(pTab) ){
87662    destroyTable(pParse, pTab);
87663  }
87664
87665  /* Remove the table entry from SQLite's internal schema and modify
87666  ** the schema cookie.
87667  */
87668  if( IsVirtual(pTab) ){
87669    sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
87670  }
87671  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
87672  sqlite3ChangeCookie(pParse, iDb);
87673  sqliteViewResetAll(db, iDb);
87674}
87675
87676/*
87677** This routine is called to do the work of a DROP TABLE statement.
87678** pName is the name of the table to be dropped.
87679*/
87680SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
87681  Table *pTab;
87682  Vdbe *v;
87683  sqlite3 *db = pParse->db;
87684  int iDb;
87685
87686  if( db->mallocFailed ){
87687    goto exit_drop_table;
87688  }
87689  assert( pParse->nErr==0 );
87690  assert( pName->nSrc==1 );
87691  if( noErr ) db->suppressErr++;
87692  pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
87693  if( noErr ) db->suppressErr--;
87694
87695  if( pTab==0 ){
87696    if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
87697    goto exit_drop_table;
87698  }
87699  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
87700  assert( iDb>=0 && iDb<db->nDb );
87701
87702  /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
87703  ** it is initialized.
87704  */
87705  if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
87706    goto exit_drop_table;
87707  }
87708#ifndef SQLITE_OMIT_AUTHORIZATION
87709  {
87710    int code;
87711    const char *zTab = SCHEMA_TABLE(iDb);
87712    const char *zDb = db->aDb[iDb].zName;
87713    const char *zArg2 = 0;
87714    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
87715      goto exit_drop_table;
87716    }
87717    if( isView ){
87718      if( !OMIT_TEMPDB && iDb==1 ){
87719        code = SQLITE_DROP_TEMP_VIEW;
87720      }else{
87721        code = SQLITE_DROP_VIEW;
87722      }
87723#ifndef SQLITE_OMIT_VIRTUALTABLE
87724    }else if( IsVirtual(pTab) ){
87725      code = SQLITE_DROP_VTABLE;
87726      zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
87727#endif
87728    }else{
87729      if( !OMIT_TEMPDB && iDb==1 ){
87730        code = SQLITE_DROP_TEMP_TABLE;
87731      }else{
87732        code = SQLITE_DROP_TABLE;
87733      }
87734    }
87735    if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
87736      goto exit_drop_table;
87737    }
87738    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
87739      goto exit_drop_table;
87740    }
87741  }
87742#endif
87743  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
87744    && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
87745    sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
87746    goto exit_drop_table;
87747  }
87748
87749#ifndef SQLITE_OMIT_VIEW
87750  /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
87751  ** on a table.
87752  */
87753  if( isView && pTab->pSelect==0 ){
87754    sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
87755    goto exit_drop_table;
87756  }
87757  if( !isView && pTab->pSelect ){
87758    sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
87759    goto exit_drop_table;
87760  }
87761#endif
87762
87763  /* Generate code to remove the table from the master table
87764  ** on disk.
87765  */
87766  v = sqlite3GetVdbe(pParse);
87767  if( v ){
87768    sqlite3BeginWriteOperation(pParse, 1, iDb);
87769    sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
87770    sqlite3FkDropTable(pParse, pName, pTab);
87771    sqlite3CodeDropTable(pParse, pTab, iDb, isView);
87772  }
87773
87774exit_drop_table:
87775  sqlite3SrcListDelete(db, pName);
87776}
87777
87778/*
87779** This routine is called to create a new foreign key on the table
87780** currently under construction.  pFromCol determines which columns
87781** in the current table point to the foreign key.  If pFromCol==0 then
87782** connect the key to the last column inserted.  pTo is the name of
87783** the table referred to (a.k.a the "parent" table).  pToCol is a list
87784** of tables in the parent pTo table.  flags contains all
87785** information about the conflict resolution algorithms specified
87786** in the ON DELETE, ON UPDATE and ON INSERT clauses.
87787**
87788** An FKey structure is created and added to the table currently
87789** under construction in the pParse->pNewTable field.
87790**
87791** The foreign key is set for IMMEDIATE processing.  A subsequent call
87792** to sqlite3DeferForeignKey() might change this to DEFERRED.
87793*/
87794SQLITE_PRIVATE void sqlite3CreateForeignKey(
87795  Parse *pParse,       /* Parsing context */
87796  ExprList *pFromCol,  /* Columns in this table that point to other table */
87797  Token *pTo,          /* Name of the other table */
87798  ExprList *pToCol,    /* Columns in the other table */
87799  int flags            /* Conflict resolution algorithms. */
87800){
87801  sqlite3 *db = pParse->db;
87802#ifndef SQLITE_OMIT_FOREIGN_KEY
87803  FKey *pFKey = 0;
87804  FKey *pNextTo;
87805  Table *p = pParse->pNewTable;
87806  int nByte;
87807  int i;
87808  int nCol;
87809  char *z;
87810
87811  assert( pTo!=0 );
87812  if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
87813  if( pFromCol==0 ){
87814    int iCol = p->nCol-1;
87815    if( NEVER(iCol<0) ) goto fk_end;
87816    if( pToCol && pToCol->nExpr!=1 ){
87817      sqlite3ErrorMsg(pParse, "foreign key on %s"
87818         " should reference only one column of table %T",
87819         p->aCol[iCol].zName, pTo);
87820      goto fk_end;
87821    }
87822    nCol = 1;
87823  }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
87824    sqlite3ErrorMsg(pParse,
87825        "number of columns in foreign key does not match the number of "
87826        "columns in the referenced table");
87827    goto fk_end;
87828  }else{
87829    nCol = pFromCol->nExpr;
87830  }
87831  nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
87832  if( pToCol ){
87833    for(i=0; i<pToCol->nExpr; i++){
87834      nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
87835    }
87836  }
87837  pFKey = sqlite3DbMallocZero(db, nByte );
87838  if( pFKey==0 ){
87839    goto fk_end;
87840  }
87841  pFKey->pFrom = p;
87842  pFKey->pNextFrom = p->pFKey;
87843  z = (char*)&pFKey->aCol[nCol];
87844  pFKey->zTo = z;
87845  memcpy(z, pTo->z, pTo->n);
87846  z[pTo->n] = 0;
87847  sqlite3Dequote(z);
87848  z += pTo->n+1;
87849  pFKey->nCol = nCol;
87850  if( pFromCol==0 ){
87851    pFKey->aCol[0].iFrom = p->nCol-1;
87852  }else{
87853    for(i=0; i<nCol; i++){
87854      int j;
87855      for(j=0; j<p->nCol; j++){
87856        if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
87857          pFKey->aCol[i].iFrom = j;
87858          break;
87859        }
87860      }
87861      if( j>=p->nCol ){
87862        sqlite3ErrorMsg(pParse,
87863          "unknown column \"%s\" in foreign key definition",
87864          pFromCol->a[i].zName);
87865        goto fk_end;
87866      }
87867    }
87868  }
87869  if( pToCol ){
87870    for(i=0; i<nCol; i++){
87871      int n = sqlite3Strlen30(pToCol->a[i].zName);
87872      pFKey->aCol[i].zCol = z;
87873      memcpy(z, pToCol->a[i].zName, n);
87874      z[n] = 0;
87875      z += n+1;
87876    }
87877  }
87878  pFKey->isDeferred = 0;
87879  pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
87880  pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
87881
87882  assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
87883  pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
87884      pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
87885  );
87886  if( pNextTo==pFKey ){
87887    db->mallocFailed = 1;
87888    goto fk_end;
87889  }
87890  if( pNextTo ){
87891    assert( pNextTo->pPrevTo==0 );
87892    pFKey->pNextTo = pNextTo;
87893    pNextTo->pPrevTo = pFKey;
87894  }
87895
87896  /* Link the foreign key to the table as the last step.
87897  */
87898  p->pFKey = pFKey;
87899  pFKey = 0;
87900
87901fk_end:
87902  sqlite3DbFree(db, pFKey);
87903#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
87904  sqlite3ExprListDelete(db, pFromCol);
87905  sqlite3ExprListDelete(db, pToCol);
87906}
87907
87908/*
87909** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
87910** clause is seen as part of a foreign key definition.  The isDeferred
87911** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
87912** The behavior of the most recently created foreign key is adjusted
87913** accordingly.
87914*/
87915SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
87916#ifndef SQLITE_OMIT_FOREIGN_KEY
87917  Table *pTab;
87918  FKey *pFKey;
87919  if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
87920  assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
87921  pFKey->isDeferred = (u8)isDeferred;
87922#endif
87923}
87924
87925/*
87926** Generate code that will erase and refill index *pIdx.  This is
87927** used to initialize a newly created index or to recompute the
87928** content of an index in response to a REINDEX command.
87929**
87930** if memRootPage is not negative, it means that the index is newly
87931** created.  The register specified by memRootPage contains the
87932** root page number of the index.  If memRootPage is negative, then
87933** the index already exists and must be cleared before being refilled and
87934** the root page number of the index is taken from pIndex->tnum.
87935*/
87936static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
87937  Table *pTab = pIndex->pTable;  /* The table that is indexed */
87938  int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
87939  int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
87940  int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
87941  int addr1;                     /* Address of top of loop */
87942  int addr2;                     /* Address to jump to for next iteration */
87943  int tnum;                      /* Root page of index */
87944  int iPartIdxLabel;             /* Jump to this label to skip a row */
87945  Vdbe *v;                       /* Generate code into this virtual machine */
87946  KeyInfo *pKey;                 /* KeyInfo for index */
87947  int regRecord;                 /* Register holding assemblied index record */
87948  sqlite3 *db = pParse->db;      /* The database connection */
87949  int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
87950
87951#ifndef SQLITE_OMIT_AUTHORIZATION
87952  if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
87953      db->aDb[iDb].zName ) ){
87954    return;
87955  }
87956#endif
87957
87958  /* Require a write-lock on the table to perform this operation */
87959  sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
87960
87961  v = sqlite3GetVdbe(pParse);
87962  if( v==0 ) return;
87963  if( memRootPage>=0 ){
87964    tnum = memRootPage;
87965  }else{
87966    tnum = pIndex->tnum;
87967  }
87968  pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
87969
87970  /* Open the sorter cursor if we are to use one. */
87971  iSorter = pParse->nTab++;
87972  sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)
87973                    sqlite3KeyInfoRef(pKey), P4_KEYINFO);
87974
87975  /* Open the table. Loop through all rows of the table, inserting index
87976  ** records into the sorter. */
87977  sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
87978  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
87979  regRecord = sqlite3GetTempReg(pParse);
87980
87981  sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
87982  sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
87983  sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
87984  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
87985  sqlite3VdbeJumpHere(v, addr1);
87986  if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
87987  sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
87988                    (char *)pKey, P4_KEYINFO);
87989  sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
87990
87991  addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
87992  assert( pKey!=0 || db->mallocFailed || pParse->nErr );
87993  if( pIndex->onError!=OE_None && pKey!=0 ){
87994    int j2 = sqlite3VdbeCurrentAddr(v) + 3;
87995    sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
87996    addr2 = sqlite3VdbeCurrentAddr(v);
87997    sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
87998                         pKey->nField - pIndex->nKeyCol); VdbeCoverage(v);
87999    sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
88000  }else{
88001    addr2 = sqlite3VdbeCurrentAddr(v);
88002  }
88003  sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
88004  sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
88005  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
88006  sqlite3ReleaseTempReg(pParse, regRecord);
88007  sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
88008  sqlite3VdbeJumpHere(v, addr1);
88009
88010  sqlite3VdbeAddOp1(v, OP_Close, iTab);
88011  sqlite3VdbeAddOp1(v, OP_Close, iIdx);
88012  sqlite3VdbeAddOp1(v, OP_Close, iSorter);
88013}
88014
88015/*
88016** Allocate heap space to hold an Index object with nCol columns.
88017**
88018** Increase the allocation size to provide an extra nExtra bytes
88019** of 8-byte aligned space after the Index object and return a
88020** pointer to this extra space in *ppExtra.
88021*/
88022SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
88023  sqlite3 *db,         /* Database connection */
88024  i16 nCol,            /* Total number of columns in the index */
88025  int nExtra,          /* Number of bytes of extra space to alloc */
88026  char **ppExtra       /* Pointer to the "extra" space */
88027){
88028  Index *p;            /* Allocated index object */
88029  int nByte;           /* Bytes of space for Index object + arrays */
88030
88031  nByte = ROUND8(sizeof(Index)) +              /* Index structure  */
88032          ROUND8(sizeof(char*)*nCol) +         /* Index.azColl     */
88033          ROUND8(sizeof(LogEst)*(nCol+1) +     /* Index.aiRowLogEst   */
88034                 sizeof(i16)*nCol +            /* Index.aiColumn   */
88035                 sizeof(u8)*nCol);             /* Index.aSortOrder */
88036  p = sqlite3DbMallocZero(db, nByte + nExtra);
88037  if( p ){
88038    char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
88039    p->azColl = (char**)pExtra;       pExtra += ROUND8(sizeof(char*)*nCol);
88040    p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
88041    p->aiColumn = (i16*)pExtra;       pExtra += sizeof(i16)*nCol;
88042    p->aSortOrder = (u8*)pExtra;
88043    p->nColumn = nCol;
88044    p->nKeyCol = nCol - 1;
88045    *ppExtra = ((char*)p) + nByte;
88046  }
88047  return p;
88048}
88049
88050/*
88051** Create a new index for an SQL table.  pName1.pName2 is the name of the index
88052** and pTblList is the name of the table that is to be indexed.  Both will
88053** be NULL for a primary key or an index that is created to satisfy a
88054** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
88055** as the table to be indexed.  pParse->pNewTable is a table that is
88056** currently being constructed by a CREATE TABLE statement.
88057**
88058** pList is a list of columns to be indexed.  pList will be NULL if this
88059** is a primary key or unique-constraint on the most recent column added
88060** to the table currently under construction.
88061**
88062** If the index is created successfully, return a pointer to the new Index
88063** structure. This is used by sqlite3AddPrimaryKey() to mark the index
88064** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
88065*/
88066SQLITE_PRIVATE Index *sqlite3CreateIndex(
88067  Parse *pParse,     /* All information about this parse */
88068  Token *pName1,     /* First part of index name. May be NULL */
88069  Token *pName2,     /* Second part of index name. May be NULL */
88070  SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
88071  ExprList *pList,   /* A list of columns to be indexed */
88072  int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
88073  Token *pStart,     /* The CREATE token that begins this statement */
88074  Expr *pPIWhere,    /* WHERE clause for partial indices */
88075  int sortOrder,     /* Sort order of primary key when pList==NULL */
88076  int ifNotExist     /* Omit error if index already exists */
88077){
88078  Index *pRet = 0;     /* Pointer to return */
88079  Table *pTab = 0;     /* Table to be indexed */
88080  Index *pIndex = 0;   /* The index to be created */
88081  char *zName = 0;     /* Name of the index */
88082  int nName;           /* Number of characters in zName */
88083  int i, j;
88084  DbFixer sFix;        /* For assigning database names to pTable */
88085  int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
88086  sqlite3 *db = pParse->db;
88087  Db *pDb;             /* The specific table containing the indexed database */
88088  int iDb;             /* Index of the database that is being written */
88089  Token *pName = 0;    /* Unqualified name of the index to create */
88090  struct ExprList_item *pListItem; /* For looping over pList */
88091  const Column *pTabCol;           /* A column in the table */
88092  int nExtra = 0;                  /* Space allocated for zExtra[] */
88093  int nExtraCol;                   /* Number of extra columns needed */
88094  char *zExtra = 0;                /* Extra space after the Index object */
88095  Index *pPk = 0;      /* PRIMARY KEY index for WITHOUT ROWID tables */
88096
88097  assert( pParse->nErr==0 );      /* Never called with prior errors */
88098  if( db->mallocFailed || IN_DECLARE_VTAB ){
88099    goto exit_create_index;
88100  }
88101  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
88102    goto exit_create_index;
88103  }
88104
88105  /*
88106  ** Find the table that is to be indexed.  Return early if not found.
88107  */
88108  if( pTblName!=0 ){
88109
88110    /* Use the two-part index name to determine the database
88111    ** to search for the table. 'Fix' the table name to this db
88112    ** before looking up the table.
88113    */
88114    assert( pName1 && pName2 );
88115    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
88116    if( iDb<0 ) goto exit_create_index;
88117    assert( pName && pName->z );
88118
88119#ifndef SQLITE_OMIT_TEMPDB
88120    /* If the index name was unqualified, check if the table
88121    ** is a temp table. If so, set the database to 1. Do not do this
88122    ** if initialising a database schema.
88123    */
88124    if( !db->init.busy ){
88125      pTab = sqlite3SrcListLookup(pParse, pTblName);
88126      if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
88127        iDb = 1;
88128      }
88129    }
88130#endif
88131
88132    sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
88133    if( sqlite3FixSrcList(&sFix, pTblName) ){
88134      /* Because the parser constructs pTblName from a single identifier,
88135      ** sqlite3FixSrcList can never fail. */
88136      assert(0);
88137    }
88138    pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
88139    assert( db->mallocFailed==0 || pTab==0 );
88140    if( pTab==0 ) goto exit_create_index;
88141    if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
88142      sqlite3ErrorMsg(pParse,
88143           "cannot create a TEMP index on non-TEMP table \"%s\"",
88144           pTab->zName);
88145      goto exit_create_index;
88146    }
88147    if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
88148  }else{
88149    assert( pName==0 );
88150    assert( pStart==0 );
88151    pTab = pParse->pNewTable;
88152    if( !pTab ) goto exit_create_index;
88153    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
88154  }
88155  pDb = &db->aDb[iDb];
88156
88157  assert( pTab!=0 );
88158  assert( pParse->nErr==0 );
88159  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
88160       && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
88161    sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
88162    goto exit_create_index;
88163  }
88164#ifndef SQLITE_OMIT_VIEW
88165  if( pTab->pSelect ){
88166    sqlite3ErrorMsg(pParse, "views may not be indexed");
88167    goto exit_create_index;
88168  }
88169#endif
88170#ifndef SQLITE_OMIT_VIRTUALTABLE
88171  if( IsVirtual(pTab) ){
88172    sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
88173    goto exit_create_index;
88174  }
88175#endif
88176
88177  /*
88178  ** Find the name of the index.  Make sure there is not already another
88179  ** index or table with the same name.
88180  **
88181  ** Exception:  If we are reading the names of permanent indices from the
88182  ** sqlite_master table (because some other process changed the schema) and
88183  ** one of the index names collides with the name of a temporary table or
88184  ** index, then we will continue to process this index.
88185  **
88186  ** If pName==0 it means that we are
88187  ** dealing with a primary key or UNIQUE constraint.  We have to invent our
88188  ** own name.
88189  */
88190  if( pName ){
88191    zName = sqlite3NameFromToken(db, pName);
88192    if( zName==0 ) goto exit_create_index;
88193    assert( pName->z!=0 );
88194    if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
88195      goto exit_create_index;
88196    }
88197    if( !db->init.busy ){
88198      if( sqlite3FindTable(db, zName, 0)!=0 ){
88199        sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
88200        goto exit_create_index;
88201      }
88202    }
88203    if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
88204      if( !ifNotExist ){
88205        sqlite3ErrorMsg(pParse, "index %s already exists", zName);
88206      }else{
88207        assert( !db->init.busy );
88208        sqlite3CodeVerifySchema(pParse, iDb);
88209      }
88210      goto exit_create_index;
88211    }
88212  }else{
88213    int n;
88214    Index *pLoop;
88215    for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
88216    zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
88217    if( zName==0 ){
88218      goto exit_create_index;
88219    }
88220  }
88221
88222  /* Check for authorization to create an index.
88223  */
88224#ifndef SQLITE_OMIT_AUTHORIZATION
88225  {
88226    const char *zDb = pDb->zName;
88227    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
88228      goto exit_create_index;
88229    }
88230    i = SQLITE_CREATE_INDEX;
88231    if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
88232    if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
88233      goto exit_create_index;
88234    }
88235  }
88236#endif
88237
88238  /* If pList==0, it means this routine was called to make a primary
88239  ** key out of the last column added to the table under construction.
88240  ** So create a fake list to simulate this.
88241  */
88242  if( pList==0 ){
88243    pList = sqlite3ExprListAppend(pParse, 0, 0);
88244    if( pList==0 ) goto exit_create_index;
88245    pList->a[0].zName = sqlite3DbStrDup(pParse->db,
88246                                        pTab->aCol[pTab->nCol-1].zName);
88247    pList->a[0].sortOrder = (u8)sortOrder;
88248  }
88249
88250  /* Figure out how many bytes of space are required to store explicitly
88251  ** specified collation sequence names.
88252  */
88253  for(i=0; i<pList->nExpr; i++){
88254    Expr *pExpr = pList->a[i].pExpr;
88255    if( pExpr ){
88256      assert( pExpr->op==TK_COLLATE );
88257      nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
88258    }
88259  }
88260
88261  /*
88262  ** Allocate the index structure.
88263  */
88264  nName = sqlite3Strlen30(zName);
88265  nExtraCol = pPk ? pPk->nKeyCol : 1;
88266  pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
88267                                      nName + nExtra + 1, &zExtra);
88268  if( db->mallocFailed ){
88269    goto exit_create_index;
88270  }
88271  assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
88272  assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
88273  pIndex->zName = zExtra;
88274  zExtra += nName + 1;
88275  memcpy(pIndex->zName, zName, nName+1);
88276  pIndex->pTable = pTab;
88277  pIndex->onError = (u8)onError;
88278  pIndex->uniqNotNull = onError!=OE_None;
88279  pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE;
88280  pIndex->pSchema = db->aDb[iDb].pSchema;
88281  pIndex->nKeyCol = pList->nExpr;
88282  if( pPIWhere ){
88283    sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
88284    pIndex->pPartIdxWhere = pPIWhere;
88285    pPIWhere = 0;
88286  }
88287  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
88288
88289  /* Check to see if we should honor DESC requests on index columns
88290  */
88291  if( pDb->pSchema->file_format>=4 ){
88292    sortOrderMask = -1;   /* Honor DESC */
88293  }else{
88294    sortOrderMask = 0;    /* Ignore DESC */
88295  }
88296
88297  /* Scan the names of the columns of the table to be indexed and
88298  ** load the column indices into the Index structure.  Report an error
88299  ** if any column is not found.
88300  **
88301  ** TODO:  Add a test to make sure that the same column is not named
88302  ** more than once within the same index.  Only the first instance of
88303  ** the column will ever be used by the optimizer.  Note that using the
88304  ** same column more than once cannot be an error because that would
88305  ** break backwards compatibility - it needs to be a warning.
88306  */
88307  for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
88308    const char *zColName = pListItem->zName;
88309    int requestedSortOrder;
88310    char *zColl;                   /* Collation sequence name */
88311
88312    for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
88313      if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
88314    }
88315    if( j>=pTab->nCol ){
88316      sqlite3ErrorMsg(pParse, "table %s has no column named %s",
88317        pTab->zName, zColName);
88318      pParse->checkSchema = 1;
88319      goto exit_create_index;
88320    }
88321    assert( pTab->nCol<=0x7fff && j<=0x7fff );
88322    pIndex->aiColumn[i] = (i16)j;
88323    if( pListItem->pExpr ){
88324      int nColl;
88325      assert( pListItem->pExpr->op==TK_COLLATE );
88326      zColl = pListItem->pExpr->u.zToken;
88327      nColl = sqlite3Strlen30(zColl) + 1;
88328      assert( nExtra>=nColl );
88329      memcpy(zExtra, zColl, nColl);
88330      zColl = zExtra;
88331      zExtra += nColl;
88332      nExtra -= nColl;
88333    }else{
88334      zColl = pTab->aCol[j].zColl;
88335      if( !zColl ) zColl = "BINARY";
88336    }
88337    if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
88338      goto exit_create_index;
88339    }
88340    pIndex->azColl[i] = zColl;
88341    requestedSortOrder = pListItem->sortOrder & sortOrderMask;
88342    pIndex->aSortOrder[i] = (u8)requestedSortOrder;
88343    if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
88344  }
88345  if( pPk ){
88346    for(j=0; j<pPk->nKeyCol; j++){
88347      int x = pPk->aiColumn[j];
88348      if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
88349        pIndex->nColumn--;
88350      }else{
88351        pIndex->aiColumn[i] = x;
88352        pIndex->azColl[i] = pPk->azColl[j];
88353        pIndex->aSortOrder[i] = pPk->aSortOrder[j];
88354        i++;
88355      }
88356    }
88357    assert( i==pIndex->nColumn );
88358  }else{
88359    pIndex->aiColumn[i] = -1;
88360    pIndex->azColl[i] = "BINARY";
88361  }
88362  sqlite3DefaultRowEst(pIndex);
88363  if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
88364
88365  if( pTab==pParse->pNewTable ){
88366    /* This routine has been called to create an automatic index as a
88367    ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
88368    ** a PRIMARY KEY or UNIQUE clause following the column definitions.
88369    ** i.e. one of:
88370    **
88371    ** CREATE TABLE t(x PRIMARY KEY, y);
88372    ** CREATE TABLE t(x, y, UNIQUE(x, y));
88373    **
88374    ** Either way, check to see if the table already has such an index. If
88375    ** so, don't bother creating this one. This only applies to
88376    ** automatically created indices. Users can do as they wish with
88377    ** explicit indices.
88378    **
88379    ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
88380    ** (and thus suppressing the second one) even if they have different
88381    ** sort orders.
88382    **
88383    ** If there are different collating sequences or if the columns of
88384    ** the constraint occur in different orders, then the constraints are
88385    ** considered distinct and both result in separate indices.
88386    */
88387    Index *pIdx;
88388    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
88389      int k;
88390      assert( pIdx->onError!=OE_None );
88391      assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
88392      assert( pIndex->onError!=OE_None );
88393
88394      if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
88395      for(k=0; k<pIdx->nKeyCol; k++){
88396        const char *z1;
88397        const char *z2;
88398        if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
88399        z1 = pIdx->azColl[k];
88400        z2 = pIndex->azColl[k];
88401        if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
88402      }
88403      if( k==pIdx->nKeyCol ){
88404        if( pIdx->onError!=pIndex->onError ){
88405          /* This constraint creates the same index as a previous
88406          ** constraint specified somewhere in the CREATE TABLE statement.
88407          ** However the ON CONFLICT clauses are different. If both this
88408          ** constraint and the previous equivalent constraint have explicit
88409          ** ON CONFLICT clauses this is an error. Otherwise, use the
88410          ** explicitly specified behavior for the index.
88411          */
88412          if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
88413            sqlite3ErrorMsg(pParse,
88414                "conflicting ON CONFLICT clauses specified", 0);
88415          }
88416          if( pIdx->onError==OE_Default ){
88417            pIdx->onError = pIndex->onError;
88418          }
88419        }
88420        goto exit_create_index;
88421      }
88422    }
88423  }
88424
88425  /* Link the new Index structure to its table and to the other
88426  ** in-memory database structures.
88427  */
88428  if( db->init.busy ){
88429    Index *p;
88430    assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
88431    p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
88432                          pIndex->zName, sqlite3Strlen30(pIndex->zName),
88433                          pIndex);
88434    if( p ){
88435      assert( p==pIndex );  /* Malloc must have failed */
88436      db->mallocFailed = 1;
88437      goto exit_create_index;
88438    }
88439    db->flags |= SQLITE_InternChanges;
88440    if( pTblName!=0 ){
88441      pIndex->tnum = db->init.newTnum;
88442    }
88443  }
88444
88445  /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
88446  ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
88447  ** emit code to allocate the index rootpage on disk and make an entry for
88448  ** the index in the sqlite_master table and populate the index with
88449  ** content.  But, do not do this if we are simply reading the sqlite_master
88450  ** table to parse the schema, or if this index is the PRIMARY KEY index
88451  ** of a WITHOUT ROWID table.
88452  **
88453  ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
88454  ** or UNIQUE index in a CREATE TABLE statement.  Since the table
88455  ** has just been created, it contains no data and the index initialization
88456  ** step can be skipped.
88457  */
88458  else if( pParse->nErr==0 && (HasRowid(pTab) || pTblName!=0) ){
88459    Vdbe *v;
88460    char *zStmt;
88461    int iMem = ++pParse->nMem;
88462
88463    v = sqlite3GetVdbe(pParse);
88464    if( v==0 ) goto exit_create_index;
88465
88466
88467    /* Create the rootpage for the index
88468    */
88469    sqlite3BeginWriteOperation(pParse, 1, iDb);
88470    sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
88471
88472    /* Gather the complete text of the CREATE INDEX statement into
88473    ** the zStmt variable
88474    */
88475    if( pStart ){
88476      int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
88477      if( pName->z[n-1]==';' ) n--;
88478      /* A named index with an explicit CREATE INDEX statement */
88479      zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
88480        onError==OE_None ? "" : " UNIQUE", n, pName->z);
88481    }else{
88482      /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
88483      /* zStmt = sqlite3MPrintf(""); */
88484      zStmt = 0;
88485    }
88486
88487    /* Add an entry in sqlite_master for this index
88488    */
88489    sqlite3NestedParse(pParse,
88490        "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
88491        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
88492        pIndex->zName,
88493        pTab->zName,
88494        iMem,
88495        zStmt
88496    );
88497    sqlite3DbFree(db, zStmt);
88498
88499    /* Fill the index with data and reparse the schema. Code an OP_Expire
88500    ** to invalidate all pre-compiled statements.
88501    */
88502    if( pTblName ){
88503      sqlite3RefillIndex(pParse, pIndex, iMem);
88504      sqlite3ChangeCookie(pParse, iDb);
88505      sqlite3VdbeAddParseSchemaOp(v, iDb,
88506         sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
88507      sqlite3VdbeAddOp1(v, OP_Expire, 0);
88508    }
88509  }
88510
88511  /* When adding an index to the list of indices for a table, make
88512  ** sure all indices labeled OE_Replace come after all those labeled
88513  ** OE_Ignore.  This is necessary for the correct constraint check
88514  ** processing (in sqlite3GenerateConstraintChecks()) as part of
88515  ** UPDATE and INSERT statements.
88516  */
88517  if( db->init.busy || pTblName==0 ){
88518    if( onError!=OE_Replace || pTab->pIndex==0
88519         || pTab->pIndex->onError==OE_Replace){
88520      pIndex->pNext = pTab->pIndex;
88521      pTab->pIndex = pIndex;
88522    }else{
88523      Index *pOther = pTab->pIndex;
88524      while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
88525        pOther = pOther->pNext;
88526      }
88527      pIndex->pNext = pOther->pNext;
88528      pOther->pNext = pIndex;
88529    }
88530    pRet = pIndex;
88531    pIndex = 0;
88532  }
88533
88534  /* Clean up before exiting */
88535exit_create_index:
88536  if( pIndex ) freeIndex(db, pIndex);
88537  sqlite3ExprDelete(db, pPIWhere);
88538  sqlite3ExprListDelete(db, pList);
88539  sqlite3SrcListDelete(db, pTblName);
88540  sqlite3DbFree(db, zName);
88541  return pRet;
88542}
88543
88544/*
88545** Fill the Index.aiRowEst[] array with default information - information
88546** to be used when we have not run the ANALYZE command.
88547**
88548** aiRowEst[0] is suppose to contain the number of elements in the index.
88549** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
88550** number of rows in the table that match any particular value of the
88551** first column of the index.  aiRowEst[2] is an estimate of the number
88552** of rows that match any particular combination of the first 2 columns
88553** of the index.  And so forth.  It must always be the case that
88554*
88555**           aiRowEst[N]<=aiRowEst[N-1]
88556**           aiRowEst[N]>=1
88557**
88558** Apart from that, we have little to go on besides intuition as to
88559** how aiRowEst[] should be initialized.  The numbers generated here
88560** are based on typical values found in actual indices.
88561*/
88562SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
88563  /*                10,  9,  8,  7,  6 */
88564  LogEst aVal[] = { 33, 32, 30, 28, 26 };
88565  LogEst *a = pIdx->aiRowLogEst;
88566  int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
88567  int i;
88568
88569  /* Set the first entry (number of rows in the index) to the estimated
88570  ** number of rows in the table. Or 10, if the estimated number of rows
88571  ** in the table is less than that.  */
88572  a[0] = pIdx->pTable->nRowLogEst;
88573  if( a[0]<33 ) a[0] = 33;        assert( 33==sqlite3LogEst(10) );
88574
88575  /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
88576  ** 6 and each subsequent value (if any) is 5.  */
88577  memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
88578  for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
88579    a[i] = 23;                    assert( 23==sqlite3LogEst(5) );
88580  }
88581
88582  assert( 0==sqlite3LogEst(1) );
88583  if( pIdx->onError!=OE_None ) a[pIdx->nKeyCol] = 0;
88584}
88585
88586/*
88587** This routine will drop an existing named index.  This routine
88588** implements the DROP INDEX statement.
88589*/
88590SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
88591  Index *pIndex;
88592  Vdbe *v;
88593  sqlite3 *db = pParse->db;
88594  int iDb;
88595
88596  assert( pParse->nErr==0 );   /* Never called with prior errors */
88597  if( db->mallocFailed ){
88598    goto exit_drop_index;
88599  }
88600  assert( pName->nSrc==1 );
88601  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
88602    goto exit_drop_index;
88603  }
88604  pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
88605  if( pIndex==0 ){
88606    if( !ifExists ){
88607      sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
88608    }else{
88609      sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
88610    }
88611    pParse->checkSchema = 1;
88612    goto exit_drop_index;
88613  }
88614  if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
88615    sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
88616      "or PRIMARY KEY constraint cannot be dropped", 0);
88617    goto exit_drop_index;
88618  }
88619  iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
88620#ifndef SQLITE_OMIT_AUTHORIZATION
88621  {
88622    int code = SQLITE_DROP_INDEX;
88623    Table *pTab = pIndex->pTable;
88624    const char *zDb = db->aDb[iDb].zName;
88625    const char *zTab = SCHEMA_TABLE(iDb);
88626    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
88627      goto exit_drop_index;
88628    }
88629    if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
88630    if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
88631      goto exit_drop_index;
88632    }
88633  }
88634#endif
88635
88636  /* Generate code to remove the index and from the master table */
88637  v = sqlite3GetVdbe(pParse);
88638  if( v ){
88639    sqlite3BeginWriteOperation(pParse, 1, iDb);
88640    sqlite3NestedParse(pParse,
88641       "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
88642       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
88643    );
88644    sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
88645    sqlite3ChangeCookie(pParse, iDb);
88646    destroyRootPage(pParse, pIndex->tnum, iDb);
88647    sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
88648  }
88649
88650exit_drop_index:
88651  sqlite3SrcListDelete(db, pName);
88652}
88653
88654/*
88655** pArray is a pointer to an array of objects. Each object in the
88656** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
88657** to extend the array so that there is space for a new object at the end.
88658**
88659** When this function is called, *pnEntry contains the current size of
88660** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
88661** in total).
88662**
88663** If the realloc() is successful (i.e. if no OOM condition occurs), the
88664** space allocated for the new object is zeroed, *pnEntry updated to
88665** reflect the new size of the array and a pointer to the new allocation
88666** returned. *pIdx is set to the index of the new array entry in this case.
88667**
88668** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
88669** unchanged and a copy of pArray returned.
88670*/
88671SQLITE_PRIVATE void *sqlite3ArrayAllocate(
88672  sqlite3 *db,      /* Connection to notify of malloc failures */
88673  void *pArray,     /* Array of objects.  Might be reallocated */
88674  int szEntry,      /* Size of each object in the array */
88675  int *pnEntry,     /* Number of objects currently in use */
88676  int *pIdx         /* Write the index of a new slot here */
88677){
88678  char *z;
88679  int n = *pnEntry;
88680  if( (n & (n-1))==0 ){
88681    int sz = (n==0) ? 1 : 2*n;
88682    void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
88683    if( pNew==0 ){
88684      *pIdx = -1;
88685      return pArray;
88686    }
88687    pArray = pNew;
88688  }
88689  z = (char*)pArray;
88690  memset(&z[n * szEntry], 0, szEntry);
88691  *pIdx = n;
88692  ++*pnEntry;
88693  return pArray;
88694}
88695
88696/*
88697** Append a new element to the given IdList.  Create a new IdList if
88698** need be.
88699**
88700** A new IdList is returned, or NULL if malloc() fails.
88701*/
88702SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
88703  int i;
88704  if( pList==0 ){
88705    pList = sqlite3DbMallocZero(db, sizeof(IdList) );
88706    if( pList==0 ) return 0;
88707  }
88708  pList->a = sqlite3ArrayAllocate(
88709      db,
88710      pList->a,
88711      sizeof(pList->a[0]),
88712      &pList->nId,
88713      &i
88714  );
88715  if( i<0 ){
88716    sqlite3IdListDelete(db, pList);
88717    return 0;
88718  }
88719  pList->a[i].zName = sqlite3NameFromToken(db, pToken);
88720  return pList;
88721}
88722
88723/*
88724** Delete an IdList.
88725*/
88726SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
88727  int i;
88728  if( pList==0 ) return;
88729  for(i=0; i<pList->nId; i++){
88730    sqlite3DbFree(db, pList->a[i].zName);
88731  }
88732  sqlite3DbFree(db, pList->a);
88733  sqlite3DbFree(db, pList);
88734}
88735
88736/*
88737** Return the index in pList of the identifier named zId.  Return -1
88738** if not found.
88739*/
88740SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
88741  int i;
88742  if( pList==0 ) return -1;
88743  for(i=0; i<pList->nId; i++){
88744    if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
88745  }
88746  return -1;
88747}
88748
88749/*
88750** Expand the space allocated for the given SrcList object by
88751** creating nExtra new slots beginning at iStart.  iStart is zero based.
88752** New slots are zeroed.
88753**
88754** For example, suppose a SrcList initially contains two entries: A,B.
88755** To append 3 new entries onto the end, do this:
88756**
88757**    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
88758**
88759** After the call above it would contain:  A, B, nil, nil, nil.
88760** If the iStart argument had been 1 instead of 2, then the result
88761** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
88762** the iStart value would be 0.  The result then would
88763** be: nil, nil, nil, A, B.
88764**
88765** If a memory allocation fails the SrcList is unchanged.  The
88766** db->mallocFailed flag will be set to true.
88767*/
88768SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
88769  sqlite3 *db,       /* Database connection to notify of OOM errors */
88770  SrcList *pSrc,     /* The SrcList to be enlarged */
88771  int nExtra,        /* Number of new slots to add to pSrc->a[] */
88772  int iStart         /* Index in pSrc->a[] of first new slot */
88773){
88774  int i;
88775
88776  /* Sanity checking on calling parameters */
88777  assert( iStart>=0 );
88778  assert( nExtra>=1 );
88779  assert( pSrc!=0 );
88780  assert( iStart<=pSrc->nSrc );
88781
88782  /* Allocate additional space if needed */
88783  if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
88784    SrcList *pNew;
88785    int nAlloc = pSrc->nSrc+nExtra;
88786    int nGot;
88787    pNew = sqlite3DbRealloc(db, pSrc,
88788               sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
88789    if( pNew==0 ){
88790      assert( db->mallocFailed );
88791      return pSrc;
88792    }
88793    pSrc = pNew;
88794    nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
88795    pSrc->nAlloc = nGot;
88796  }
88797
88798  /* Move existing slots that come after the newly inserted slots
88799  ** out of the way */
88800  for(i=pSrc->nSrc-1; i>=iStart; i--){
88801    pSrc->a[i+nExtra] = pSrc->a[i];
88802  }
88803  pSrc->nSrc += nExtra;
88804
88805  /* Zero the newly allocated slots */
88806  memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
88807  for(i=iStart; i<iStart+nExtra; i++){
88808    pSrc->a[i].iCursor = -1;
88809  }
88810
88811  /* Return a pointer to the enlarged SrcList */
88812  return pSrc;
88813}
88814
88815
88816/*
88817** Append a new table name to the given SrcList.  Create a new SrcList if
88818** need be.  A new entry is created in the SrcList even if pTable is NULL.
88819**
88820** A SrcList is returned, or NULL if there is an OOM error.  The returned
88821** SrcList might be the same as the SrcList that was input or it might be
88822** a new one.  If an OOM error does occurs, then the prior value of pList
88823** that is input to this routine is automatically freed.
88824**
88825** If pDatabase is not null, it means that the table has an optional
88826** database name prefix.  Like this:  "database.table".  The pDatabase
88827** points to the table name and the pTable points to the database name.
88828** The SrcList.a[].zName field is filled with the table name which might
88829** come from pTable (if pDatabase is NULL) or from pDatabase.
88830** SrcList.a[].zDatabase is filled with the database name from pTable,
88831** or with NULL if no database is specified.
88832**
88833** In other words, if call like this:
88834**
88835**         sqlite3SrcListAppend(D,A,B,0);
88836**
88837** Then B is a table name and the database name is unspecified.  If called
88838** like this:
88839**
88840**         sqlite3SrcListAppend(D,A,B,C);
88841**
88842** Then C is the table name and B is the database name.  If C is defined
88843** then so is B.  In other words, we never have a case where:
88844**
88845**         sqlite3SrcListAppend(D,A,0,C);
88846**
88847** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
88848** before being added to the SrcList.
88849*/
88850SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
88851  sqlite3 *db,        /* Connection to notify of malloc failures */
88852  SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
88853  Token *pTable,      /* Table to append */
88854  Token *pDatabase    /* Database of the table */
88855){
88856  struct SrcList_item *pItem;
88857  assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
88858  if( pList==0 ){
88859    pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
88860    if( pList==0 ) return 0;
88861    pList->nAlloc = 1;
88862  }
88863  pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
88864  if( db->mallocFailed ){
88865    sqlite3SrcListDelete(db, pList);
88866    return 0;
88867  }
88868  pItem = &pList->a[pList->nSrc-1];
88869  if( pDatabase && pDatabase->z==0 ){
88870    pDatabase = 0;
88871  }
88872  if( pDatabase ){
88873    Token *pTemp = pDatabase;
88874    pDatabase = pTable;
88875    pTable = pTemp;
88876  }
88877  pItem->zName = sqlite3NameFromToken(db, pTable);
88878  pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
88879  return pList;
88880}
88881
88882/*
88883** Assign VdbeCursor index numbers to all tables in a SrcList
88884*/
88885SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
88886  int i;
88887  struct SrcList_item *pItem;
88888  assert(pList || pParse->db->mallocFailed );
88889  if( pList ){
88890    for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
88891      if( pItem->iCursor>=0 ) break;
88892      pItem->iCursor = pParse->nTab++;
88893      if( pItem->pSelect ){
88894        sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
88895      }
88896    }
88897  }
88898}
88899
88900/*
88901** Delete an entire SrcList including all its substructure.
88902*/
88903SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
88904  int i;
88905  struct SrcList_item *pItem;
88906  if( pList==0 ) return;
88907  for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
88908    sqlite3DbFree(db, pItem->zDatabase);
88909    sqlite3DbFree(db, pItem->zName);
88910    sqlite3DbFree(db, pItem->zAlias);
88911    sqlite3DbFree(db, pItem->zIndex);
88912    sqlite3DeleteTable(db, pItem->pTab);
88913    sqlite3SelectDelete(db, pItem->pSelect);
88914    sqlite3ExprDelete(db, pItem->pOn);
88915    sqlite3IdListDelete(db, pItem->pUsing);
88916  }
88917  sqlite3DbFree(db, pList);
88918}
88919
88920/*
88921** This routine is called by the parser to add a new term to the
88922** end of a growing FROM clause.  The "p" parameter is the part of
88923** the FROM clause that has already been constructed.  "p" is NULL
88924** if this is the first term of the FROM clause.  pTable and pDatabase
88925** are the name of the table and database named in the FROM clause term.
88926** pDatabase is NULL if the database name qualifier is missing - the
88927** usual case.  If the term has a alias, then pAlias points to the
88928** alias token.  If the term is a subquery, then pSubquery is the
88929** SELECT statement that the subquery encodes.  The pTable and
88930** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
88931** parameters are the content of the ON and USING clauses.
88932**
88933** Return a new SrcList which encodes is the FROM with the new
88934** term added.
88935*/
88936SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
88937  Parse *pParse,          /* Parsing context */
88938  SrcList *p,             /* The left part of the FROM clause already seen */
88939  Token *pTable,          /* Name of the table to add to the FROM clause */
88940  Token *pDatabase,       /* Name of the database containing pTable */
88941  Token *pAlias,          /* The right-hand side of the AS subexpression */
88942  Select *pSubquery,      /* A subquery used in place of a table name */
88943  Expr *pOn,              /* The ON clause of a join */
88944  IdList *pUsing          /* The USING clause of a join */
88945){
88946  struct SrcList_item *pItem;
88947  sqlite3 *db = pParse->db;
88948  if( !p && (pOn || pUsing) ){
88949    sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
88950      (pOn ? "ON" : "USING")
88951    );
88952    goto append_from_error;
88953  }
88954  p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
88955  if( p==0 || NEVER(p->nSrc==0) ){
88956    goto append_from_error;
88957  }
88958  pItem = &p->a[p->nSrc-1];
88959  assert( pAlias!=0 );
88960  if( pAlias->n ){
88961    pItem->zAlias = sqlite3NameFromToken(db, pAlias);
88962  }
88963  pItem->pSelect = pSubquery;
88964  pItem->pOn = pOn;
88965  pItem->pUsing = pUsing;
88966  return p;
88967
88968 append_from_error:
88969  assert( p==0 );
88970  sqlite3ExprDelete(db, pOn);
88971  sqlite3IdListDelete(db, pUsing);
88972  sqlite3SelectDelete(db, pSubquery);
88973  return 0;
88974}
88975
88976/*
88977** Add an INDEXED BY or NOT INDEXED clause to the most recently added
88978** element of the source-list passed as the second argument.
88979*/
88980SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
88981  assert( pIndexedBy!=0 );
88982  if( p && ALWAYS(p->nSrc>0) ){
88983    struct SrcList_item *pItem = &p->a[p->nSrc-1];
88984    assert( pItem->notIndexed==0 && pItem->zIndex==0 );
88985    if( pIndexedBy->n==1 && !pIndexedBy->z ){
88986      /* A "NOT INDEXED" clause was supplied. See parse.y
88987      ** construct "indexed_opt" for details. */
88988      pItem->notIndexed = 1;
88989    }else{
88990      pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
88991    }
88992  }
88993}
88994
88995/*
88996** When building up a FROM clause in the parser, the join operator
88997** is initially attached to the left operand.  But the code generator
88998** expects the join operator to be on the right operand.  This routine
88999** Shifts all join operators from left to right for an entire FROM
89000** clause.
89001**
89002** Example: Suppose the join is like this:
89003**
89004**           A natural cross join B
89005**
89006** The operator is "natural cross join".  The A and B operands are stored
89007** in p->a[0] and p->a[1], respectively.  The parser initially stores the
89008** operator with A.  This routine shifts that operator over to B.
89009*/
89010SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
89011  if( p ){
89012    int i;
89013    assert( p->a || p->nSrc==0 );
89014    for(i=p->nSrc-1; i>0; i--){
89015      p->a[i].jointype = p->a[i-1].jointype;
89016    }
89017    p->a[0].jointype = 0;
89018  }
89019}
89020
89021/*
89022** Begin a transaction
89023*/
89024SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
89025  sqlite3 *db;
89026  Vdbe *v;
89027  int i;
89028
89029  assert( pParse!=0 );
89030  db = pParse->db;
89031  assert( db!=0 );
89032/*  if( db->aDb[0].pBt==0 ) return; */
89033  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
89034    return;
89035  }
89036  v = sqlite3GetVdbe(pParse);
89037  if( !v ) return;
89038  if( type!=TK_DEFERRED ){
89039    for(i=0; i<db->nDb; i++){
89040      sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
89041      sqlite3VdbeUsesBtree(v, i);
89042    }
89043  }
89044  sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
89045}
89046
89047/*
89048** Commit a transaction
89049*/
89050SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
89051  Vdbe *v;
89052
89053  assert( pParse!=0 );
89054  assert( pParse->db!=0 );
89055  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
89056    return;
89057  }
89058  v = sqlite3GetVdbe(pParse);
89059  if( v ){
89060    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
89061  }
89062}
89063
89064/*
89065** Rollback a transaction
89066*/
89067SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
89068  Vdbe *v;
89069
89070  assert( pParse!=0 );
89071  assert( pParse->db!=0 );
89072  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
89073    return;
89074  }
89075  v = sqlite3GetVdbe(pParse);
89076  if( v ){
89077    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
89078  }
89079}
89080
89081/*
89082** This function is called by the parser when it parses a command to create,
89083** release or rollback an SQL savepoint.
89084*/
89085SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
89086  char *zName = sqlite3NameFromToken(pParse->db, pName);
89087  if( zName ){
89088    Vdbe *v = sqlite3GetVdbe(pParse);
89089#ifndef SQLITE_OMIT_AUTHORIZATION
89090    static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
89091    assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
89092#endif
89093    if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
89094      sqlite3DbFree(pParse->db, zName);
89095      return;
89096    }
89097    sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
89098  }
89099}
89100
89101/*
89102** Make sure the TEMP database is open and available for use.  Return
89103** the number of errors.  Leave any error messages in the pParse structure.
89104*/
89105SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
89106  sqlite3 *db = pParse->db;
89107  if( db->aDb[1].pBt==0 && !pParse->explain ){
89108    int rc;
89109    Btree *pBt;
89110    static const int flags =
89111          SQLITE_OPEN_READWRITE |
89112          SQLITE_OPEN_CREATE |
89113          SQLITE_OPEN_EXCLUSIVE |
89114          SQLITE_OPEN_DELETEONCLOSE |
89115          SQLITE_OPEN_TEMP_DB;
89116
89117    rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
89118    if( rc!=SQLITE_OK ){
89119      sqlite3ErrorMsg(pParse, "unable to open a temporary database "
89120        "file for storing temporary tables");
89121      pParse->rc = rc;
89122      return 1;
89123    }
89124    db->aDb[1].pBt = pBt;
89125    assert( db->aDb[1].pSchema );
89126    if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
89127      db->mallocFailed = 1;
89128      return 1;
89129    }
89130  }
89131  return 0;
89132}
89133
89134/*
89135** Record the fact that the schema cookie will need to be verified
89136** for database iDb.  The code to actually verify the schema cookie
89137** will occur at the end of the top-level VDBE and will be generated
89138** later, by sqlite3FinishCoding().
89139*/
89140SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
89141  Parse *pToplevel = sqlite3ParseToplevel(pParse);
89142  sqlite3 *db = pToplevel->db;
89143  yDbMask mask;
89144
89145  assert( iDb>=0 && iDb<db->nDb );
89146  assert( db->aDb[iDb].pBt!=0 || iDb==1 );
89147  assert( iDb<SQLITE_MAX_ATTACHED+2 );
89148  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
89149  mask = ((yDbMask)1)<<iDb;
89150  if( (pToplevel->cookieMask & mask)==0 ){
89151    pToplevel->cookieMask |= mask;
89152    pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
89153    if( !OMIT_TEMPDB && iDb==1 ){
89154      sqlite3OpenTempDatabase(pToplevel);
89155    }
89156  }
89157}
89158
89159/*
89160** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
89161** attached database. Otherwise, invoke it for the database named zDb only.
89162*/
89163SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
89164  sqlite3 *db = pParse->db;
89165  int i;
89166  for(i=0; i<db->nDb; i++){
89167    Db *pDb = &db->aDb[i];
89168    if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
89169      sqlite3CodeVerifySchema(pParse, i);
89170    }
89171  }
89172}
89173
89174/*
89175** Generate VDBE code that prepares for doing an operation that
89176** might change the database.
89177**
89178** This routine starts a new transaction if we are not already within
89179** a transaction.  If we are already within a transaction, then a checkpoint
89180** is set if the setStatement parameter is true.  A checkpoint should
89181** be set for operations that might fail (due to a constraint) part of
89182** the way through and which will need to undo some writes without having to
89183** rollback the whole transaction.  For operations where all constraints
89184** can be checked before any changes are made to the database, it is never
89185** necessary to undo a write and the checkpoint should not be set.
89186*/
89187SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
89188  Parse *pToplevel = sqlite3ParseToplevel(pParse);
89189  sqlite3CodeVerifySchema(pParse, iDb);
89190  pToplevel->writeMask |= ((yDbMask)1)<<iDb;
89191  pToplevel->isMultiWrite |= setStatement;
89192}
89193
89194/*
89195** Indicate that the statement currently under construction might write
89196** more than one entry (example: deleting one row then inserting another,
89197** inserting multiple rows in a table, or inserting a row and index entries.)
89198** If an abort occurs after some of these writes have completed, then it will
89199** be necessary to undo the completed writes.
89200*/
89201SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
89202  Parse *pToplevel = sqlite3ParseToplevel(pParse);
89203  pToplevel->isMultiWrite = 1;
89204}
89205
89206/*
89207** The code generator calls this routine if is discovers that it is
89208** possible to abort a statement prior to completion.  In order to
89209** perform this abort without corrupting the database, we need to make
89210** sure that the statement is protected by a statement transaction.
89211**
89212** Technically, we only need to set the mayAbort flag if the
89213** isMultiWrite flag was previously set.  There is a time dependency
89214** such that the abort must occur after the multiwrite.  This makes
89215** some statements involving the REPLACE conflict resolution algorithm
89216** go a little faster.  But taking advantage of this time dependency
89217** makes it more difficult to prove that the code is correct (in
89218** particular, it prevents us from writing an effective
89219** implementation of sqlite3AssertMayAbort()) and so we have chosen
89220** to take the safe route and skip the optimization.
89221*/
89222SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
89223  Parse *pToplevel = sqlite3ParseToplevel(pParse);
89224  pToplevel->mayAbort = 1;
89225}
89226
89227/*
89228** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
89229** error. The onError parameter determines which (if any) of the statement
89230** and/or current transaction is rolled back.
89231*/
89232SQLITE_PRIVATE void sqlite3HaltConstraint(
89233  Parse *pParse,    /* Parsing context */
89234  int errCode,      /* extended error code */
89235  int onError,      /* Constraint type */
89236  char *p4,         /* Error message */
89237  i8 p4type,        /* P4_STATIC or P4_TRANSIENT */
89238  u8 p5Errmsg       /* P5_ErrMsg type */
89239){
89240  Vdbe *v = sqlite3GetVdbe(pParse);
89241  assert( (errCode&0xff)==SQLITE_CONSTRAINT );
89242  if( onError==OE_Abort ){
89243    sqlite3MayAbort(pParse);
89244  }
89245  sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
89246  if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
89247}
89248
89249/*
89250** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
89251*/
89252SQLITE_PRIVATE void sqlite3UniqueConstraint(
89253  Parse *pParse,    /* Parsing context */
89254  int onError,      /* Constraint type */
89255  Index *pIdx       /* The index that triggers the constraint */
89256){
89257  char *zErr;
89258  int j;
89259  StrAccum errMsg;
89260  Table *pTab = pIdx->pTable;
89261
89262  sqlite3StrAccumInit(&errMsg, 0, 0, 200);
89263  errMsg.db = pParse->db;
89264  for(j=0; j<pIdx->nKeyCol; j++){
89265    char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
89266    if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
89267    sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
89268    sqlite3StrAccumAppend(&errMsg, ".", 1);
89269    sqlite3StrAccumAppendAll(&errMsg, zCol);
89270  }
89271  zErr = sqlite3StrAccumFinish(&errMsg);
89272  sqlite3HaltConstraint(pParse,
89273    IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
89274                            : SQLITE_CONSTRAINT_UNIQUE,
89275    onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
89276}
89277
89278
89279/*
89280** Code an OP_Halt due to non-unique rowid.
89281*/
89282SQLITE_PRIVATE void sqlite3RowidConstraint(
89283  Parse *pParse,    /* Parsing context */
89284  int onError,      /* Conflict resolution algorithm */
89285  Table *pTab       /* The table with the non-unique rowid */
89286){
89287  char *zMsg;
89288  int rc;
89289  if( pTab->iPKey>=0 ){
89290    zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
89291                          pTab->aCol[pTab->iPKey].zName);
89292    rc = SQLITE_CONSTRAINT_PRIMARYKEY;
89293  }else{
89294    zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
89295    rc = SQLITE_CONSTRAINT_ROWID;
89296  }
89297  sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
89298                        P5_ConstraintUnique);
89299}
89300
89301/*
89302** Check to see if pIndex uses the collating sequence pColl.  Return
89303** true if it does and false if it does not.
89304*/
89305#ifndef SQLITE_OMIT_REINDEX
89306static int collationMatch(const char *zColl, Index *pIndex){
89307  int i;
89308  assert( zColl!=0 );
89309  for(i=0; i<pIndex->nColumn; i++){
89310    const char *z = pIndex->azColl[i];
89311    assert( z!=0 || pIndex->aiColumn[i]<0 );
89312    if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
89313      return 1;
89314    }
89315  }
89316  return 0;
89317}
89318#endif
89319
89320/*
89321** Recompute all indices of pTab that use the collating sequence pColl.
89322** If pColl==0 then recompute all indices of pTab.
89323*/
89324#ifndef SQLITE_OMIT_REINDEX
89325static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
89326  Index *pIndex;              /* An index associated with pTab */
89327
89328  for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
89329    if( zColl==0 || collationMatch(zColl, pIndex) ){
89330      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
89331      sqlite3BeginWriteOperation(pParse, 0, iDb);
89332      sqlite3RefillIndex(pParse, pIndex, -1);
89333    }
89334  }
89335}
89336#endif
89337
89338/*
89339** Recompute all indices of all tables in all databases where the
89340** indices use the collating sequence pColl.  If pColl==0 then recompute
89341** all indices everywhere.
89342*/
89343#ifndef SQLITE_OMIT_REINDEX
89344static void reindexDatabases(Parse *pParse, char const *zColl){
89345  Db *pDb;                    /* A single database */
89346  int iDb;                    /* The database index number */
89347  sqlite3 *db = pParse->db;   /* The database connection */
89348  HashElem *k;                /* For looping over tables in pDb */
89349  Table *pTab;                /* A table in the database */
89350
89351  assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
89352  for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
89353    assert( pDb!=0 );
89354    for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
89355      pTab = (Table*)sqliteHashData(k);
89356      reindexTable(pParse, pTab, zColl);
89357    }
89358  }
89359}
89360#endif
89361
89362/*
89363** Generate code for the REINDEX command.
89364**
89365**        REINDEX                            -- 1
89366**        REINDEX  <collation>               -- 2
89367**        REINDEX  ?<database>.?<tablename>  -- 3
89368**        REINDEX  ?<database>.?<indexname>  -- 4
89369**
89370** Form 1 causes all indices in all attached databases to be rebuilt.
89371** Form 2 rebuilds all indices in all databases that use the named
89372** collating function.  Forms 3 and 4 rebuild the named index or all
89373** indices associated with the named table.
89374*/
89375#ifndef SQLITE_OMIT_REINDEX
89376SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
89377  CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
89378  char *z;                    /* Name of a table or index */
89379  const char *zDb;            /* Name of the database */
89380  Table *pTab;                /* A table in the database */
89381  Index *pIndex;              /* An index associated with pTab */
89382  int iDb;                    /* The database index number */
89383  sqlite3 *db = pParse->db;   /* The database connection */
89384  Token *pObjName;            /* Name of the table or index to be reindexed */
89385
89386  /* Read the database schema. If an error occurs, leave an error message
89387  ** and code in pParse and return NULL. */
89388  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
89389    return;
89390  }
89391
89392  if( pName1==0 ){
89393    reindexDatabases(pParse, 0);
89394    return;
89395  }else if( NEVER(pName2==0) || pName2->z==0 ){
89396    char *zColl;
89397    assert( pName1->z );
89398    zColl = sqlite3NameFromToken(pParse->db, pName1);
89399    if( !zColl ) return;
89400    pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
89401    if( pColl ){
89402      reindexDatabases(pParse, zColl);
89403      sqlite3DbFree(db, zColl);
89404      return;
89405    }
89406    sqlite3DbFree(db, zColl);
89407  }
89408  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
89409  if( iDb<0 ) return;
89410  z = sqlite3NameFromToken(db, pObjName);
89411  if( z==0 ) return;
89412  zDb = db->aDb[iDb].zName;
89413  pTab = sqlite3FindTable(db, z, zDb);
89414  if( pTab ){
89415    reindexTable(pParse, pTab, 0);
89416    sqlite3DbFree(db, z);
89417    return;
89418  }
89419  pIndex = sqlite3FindIndex(db, z, zDb);
89420  sqlite3DbFree(db, z);
89421  if( pIndex ){
89422    sqlite3BeginWriteOperation(pParse, 0, iDb);
89423    sqlite3RefillIndex(pParse, pIndex, -1);
89424    return;
89425  }
89426  sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
89427}
89428#endif
89429
89430/*
89431** Return a KeyInfo structure that is appropriate for the given Index.
89432**
89433** The KeyInfo structure for an index is cached in the Index object.
89434** So there might be multiple references to the returned pointer.  The
89435** caller should not try to modify the KeyInfo object.
89436**
89437** The caller should invoke sqlite3KeyInfoUnref() on the returned object
89438** when it has finished using it.
89439*/
89440SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
89441  if( pParse->nErr ) return 0;
89442#ifndef SQLITE_OMIT_SHARED_CACHE
89443  if( pIdx->pKeyInfo && pIdx->pKeyInfo->db!=pParse->db ){
89444    sqlite3KeyInfoUnref(pIdx->pKeyInfo);
89445    pIdx->pKeyInfo = 0;
89446  }
89447#endif
89448  if( pIdx->pKeyInfo==0 ){
89449    int i;
89450    int nCol = pIdx->nColumn;
89451    int nKey = pIdx->nKeyCol;
89452    KeyInfo *pKey;
89453    if( pIdx->uniqNotNull ){
89454      pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
89455    }else{
89456      pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
89457    }
89458    if( pKey ){
89459      assert( sqlite3KeyInfoIsWriteable(pKey) );
89460      for(i=0; i<nCol; i++){
89461        char *zColl = pIdx->azColl[i];
89462        assert( zColl!=0 );
89463        pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
89464                          sqlite3LocateCollSeq(pParse, zColl);
89465        pKey->aSortOrder[i] = pIdx->aSortOrder[i];
89466      }
89467      if( pParse->nErr ){
89468        sqlite3KeyInfoUnref(pKey);
89469      }else{
89470        pIdx->pKeyInfo = pKey;
89471      }
89472    }
89473  }
89474  return sqlite3KeyInfoRef(pIdx->pKeyInfo);
89475}
89476
89477#ifndef SQLITE_OMIT_CTE
89478/*
89479** This routine is invoked once per CTE by the parser while parsing a
89480** WITH clause.
89481*/
89482SQLITE_PRIVATE With *sqlite3WithAdd(
89483  Parse *pParse,          /* Parsing context */
89484  With *pWith,            /* Existing WITH clause, or NULL */
89485  Token *pName,           /* Name of the common-table */
89486  ExprList *pArglist,     /* Optional column name list for the table */
89487  Select *pQuery          /* Query used to initialize the table */
89488){
89489  sqlite3 *db = pParse->db;
89490  With *pNew;
89491  char *zName;
89492
89493  /* Check that the CTE name is unique within this WITH clause. If
89494  ** not, store an error in the Parse structure. */
89495  zName = sqlite3NameFromToken(pParse->db, pName);
89496  if( zName && pWith ){
89497    int i;
89498    for(i=0; i<pWith->nCte; i++){
89499      if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
89500        sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
89501      }
89502    }
89503  }
89504
89505  if( pWith ){
89506    int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
89507    pNew = sqlite3DbRealloc(db, pWith, nByte);
89508  }else{
89509    pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
89510  }
89511  assert( zName!=0 || pNew==0 );
89512  assert( db->mallocFailed==0 || pNew==0 );
89513
89514  if( pNew==0 ){
89515    sqlite3ExprListDelete(db, pArglist);
89516    sqlite3SelectDelete(db, pQuery);
89517    sqlite3DbFree(db, zName);
89518    pNew = pWith;
89519  }else{
89520    pNew->a[pNew->nCte].pSelect = pQuery;
89521    pNew->a[pNew->nCte].pCols = pArglist;
89522    pNew->a[pNew->nCte].zName = zName;
89523    pNew->a[pNew->nCte].zErr = 0;
89524    pNew->nCte++;
89525  }
89526
89527  return pNew;
89528}
89529
89530/*
89531** Free the contents of the With object passed as the second argument.
89532*/
89533SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
89534  if( pWith ){
89535    int i;
89536    for(i=0; i<pWith->nCte; i++){
89537      struct Cte *pCte = &pWith->a[i];
89538      sqlite3ExprListDelete(db, pCte->pCols);
89539      sqlite3SelectDelete(db, pCte->pSelect);
89540      sqlite3DbFree(db, pCte->zName);
89541    }
89542    sqlite3DbFree(db, pWith);
89543  }
89544}
89545#endif /* !defined(SQLITE_OMIT_CTE) */
89546
89547/************** End of build.c ***********************************************/
89548/************** Begin file callback.c ****************************************/
89549/*
89550** 2005 May 23
89551**
89552** The author disclaims copyright to this source code.  In place of
89553** a legal notice, here is a blessing:
89554**
89555**    May you do good and not evil.
89556**    May you find forgiveness for yourself and forgive others.
89557**    May you share freely, never taking more than you give.
89558**
89559*************************************************************************
89560**
89561** This file contains functions used to access the internal hash tables
89562** of user defined functions and collation sequences.
89563*/
89564
89565
89566/*
89567** Invoke the 'collation needed' callback to request a collation sequence
89568** in the encoding enc of name zName, length nName.
89569*/
89570static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
89571  assert( !db->xCollNeeded || !db->xCollNeeded16 );
89572  if( db->xCollNeeded ){
89573    char *zExternal = sqlite3DbStrDup(db, zName);
89574    if( !zExternal ) return;
89575    db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
89576    sqlite3DbFree(db, zExternal);
89577  }
89578#ifndef SQLITE_OMIT_UTF16
89579  if( db->xCollNeeded16 ){
89580    char const *zExternal;
89581    sqlite3_value *pTmp = sqlite3ValueNew(db);
89582    sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
89583    zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
89584    if( zExternal ){
89585      db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
89586    }
89587    sqlite3ValueFree(pTmp);
89588  }
89589#endif
89590}
89591
89592/*
89593** This routine is called if the collation factory fails to deliver a
89594** collation function in the best encoding but there may be other versions
89595** of this collation function (for other text encodings) available. Use one
89596** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
89597** possible.
89598*/
89599static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
89600  CollSeq *pColl2;
89601  char *z = pColl->zName;
89602  int i;
89603  static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
89604  for(i=0; i<3; i++){
89605    pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
89606    if( pColl2->xCmp!=0 ){
89607      memcpy(pColl, pColl2, sizeof(CollSeq));
89608      pColl->xDel = 0;         /* Do not copy the destructor */
89609      return SQLITE_OK;
89610    }
89611  }
89612  return SQLITE_ERROR;
89613}
89614
89615/*
89616** This function is responsible for invoking the collation factory callback
89617** or substituting a collation sequence of a different encoding when the
89618** requested collation sequence is not available in the desired encoding.
89619**
89620** If it is not NULL, then pColl must point to the database native encoding
89621** collation sequence with name zName, length nName.
89622**
89623** The return value is either the collation sequence to be used in database
89624** db for collation type name zName, length nName, or NULL, if no collation
89625** sequence can be found.  If no collation is found, leave an error message.
89626**
89627** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
89628*/
89629SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
89630  Parse *pParse,        /* Parsing context */
89631  u8 enc,               /* The desired encoding for the collating sequence */
89632  CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
89633  const char *zName     /* Collating sequence name */
89634){
89635  CollSeq *p;
89636  sqlite3 *db = pParse->db;
89637
89638  p = pColl;
89639  if( !p ){
89640    p = sqlite3FindCollSeq(db, enc, zName, 0);
89641  }
89642  if( !p || !p->xCmp ){
89643    /* No collation sequence of this type for this encoding is registered.
89644    ** Call the collation factory to see if it can supply us with one.
89645    */
89646    callCollNeeded(db, enc, zName);
89647    p = sqlite3FindCollSeq(db, enc, zName, 0);
89648  }
89649  if( p && !p->xCmp && synthCollSeq(db, p) ){
89650    p = 0;
89651  }
89652  assert( !p || p->xCmp );
89653  if( p==0 ){
89654    sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
89655  }
89656  return p;
89657}
89658
89659/*
89660** This routine is called on a collation sequence before it is used to
89661** check that it is defined. An undefined collation sequence exists when
89662** a database is loaded that contains references to collation sequences
89663** that have not been defined by sqlite3_create_collation() etc.
89664**
89665** If required, this routine calls the 'collation needed' callback to
89666** request a definition of the collating sequence. If this doesn't work,
89667** an equivalent collating sequence that uses a text encoding different
89668** from the main database is substituted, if one is available.
89669*/
89670SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
89671  if( pColl ){
89672    const char *zName = pColl->zName;
89673    sqlite3 *db = pParse->db;
89674    CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
89675    if( !p ){
89676      return SQLITE_ERROR;
89677    }
89678    assert( p==pColl );
89679  }
89680  return SQLITE_OK;
89681}
89682
89683
89684
89685/*
89686** Locate and return an entry from the db.aCollSeq hash table. If the entry
89687** specified by zName and nName is not found and parameter 'create' is
89688** true, then create a new entry. Otherwise return NULL.
89689**
89690** Each pointer stored in the sqlite3.aCollSeq hash table contains an
89691** array of three CollSeq structures. The first is the collation sequence
89692** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
89693**
89694** Stored immediately after the three collation sequences is a copy of
89695** the collation sequence name. A pointer to this string is stored in
89696** each collation sequence structure.
89697*/
89698static CollSeq *findCollSeqEntry(
89699  sqlite3 *db,          /* Database connection */
89700  const char *zName,    /* Name of the collating sequence */
89701  int create            /* Create a new entry if true */
89702){
89703  CollSeq *pColl;
89704  int nName = sqlite3Strlen30(zName);
89705  pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
89706
89707  if( 0==pColl && create ){
89708    pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
89709    if( pColl ){
89710      CollSeq *pDel = 0;
89711      pColl[0].zName = (char*)&pColl[3];
89712      pColl[0].enc = SQLITE_UTF8;
89713      pColl[1].zName = (char*)&pColl[3];
89714      pColl[1].enc = SQLITE_UTF16LE;
89715      pColl[2].zName = (char*)&pColl[3];
89716      pColl[2].enc = SQLITE_UTF16BE;
89717      memcpy(pColl[0].zName, zName, nName);
89718      pColl[0].zName[nName] = 0;
89719      pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
89720
89721      /* If a malloc() failure occurred in sqlite3HashInsert(), it will
89722      ** return the pColl pointer to be deleted (because it wasn't added
89723      ** to the hash table).
89724      */
89725      assert( pDel==0 || pDel==pColl );
89726      if( pDel!=0 ){
89727        db->mallocFailed = 1;
89728        sqlite3DbFree(db, pDel);
89729        pColl = 0;
89730      }
89731    }
89732  }
89733  return pColl;
89734}
89735
89736/*
89737** Parameter zName points to a UTF-8 encoded string nName bytes long.
89738** Return the CollSeq* pointer for the collation sequence named zName
89739** for the encoding 'enc' from the database 'db'.
89740**
89741** If the entry specified is not found and 'create' is true, then create a
89742** new entry.  Otherwise return NULL.
89743**
89744** A separate function sqlite3LocateCollSeq() is a wrapper around
89745** this routine.  sqlite3LocateCollSeq() invokes the collation factory
89746** if necessary and generates an error message if the collating sequence
89747** cannot be found.
89748**
89749** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
89750*/
89751SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
89752  sqlite3 *db,
89753  u8 enc,
89754  const char *zName,
89755  int create
89756){
89757  CollSeq *pColl;
89758  if( zName ){
89759    pColl = findCollSeqEntry(db, zName, create);
89760  }else{
89761    pColl = db->pDfltColl;
89762  }
89763  assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
89764  assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
89765  if( pColl ) pColl += enc-1;
89766  return pColl;
89767}
89768
89769/* During the search for the best function definition, this procedure
89770** is called to test how well the function passed as the first argument
89771** matches the request for a function with nArg arguments in a system
89772** that uses encoding enc. The value returned indicates how well the
89773** request is matched. A higher value indicates a better match.
89774**
89775** If nArg is -1 that means to only return a match (non-zero) if p->nArg
89776** is also -1.  In other words, we are searching for a function that
89777** takes a variable number of arguments.
89778**
89779** If nArg is -2 that means that we are searching for any function
89780** regardless of the number of arguments it uses, so return a positive
89781** match score for any
89782**
89783** The returned value is always between 0 and 6, as follows:
89784**
89785** 0: Not a match.
89786** 1: UTF8/16 conversion required and function takes any number of arguments.
89787** 2: UTF16 byte order change required and function takes any number of args.
89788** 3: encoding matches and function takes any number of arguments
89789** 4: UTF8/16 conversion required - argument count matches exactly
89790** 5: UTF16 byte order conversion required - argument count matches exactly
89791** 6: Perfect match:  encoding and argument count match exactly.
89792**
89793** If nArg==(-2) then any function with a non-null xStep or xFunc is
89794** a perfect match and any function with both xStep and xFunc NULL is
89795** a non-match.
89796*/
89797#define FUNC_PERFECT_MATCH 6  /* The score for a perfect match */
89798static int matchQuality(
89799  FuncDef *p,     /* The function we are evaluating for match quality */
89800  int nArg,       /* Desired number of arguments.  (-1)==any */
89801  u8 enc          /* Desired text encoding */
89802){
89803  int match;
89804
89805  /* nArg of -2 is a special case */
89806  if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
89807
89808  /* Wrong number of arguments means "no match" */
89809  if( p->nArg!=nArg && p->nArg>=0 ) return 0;
89810
89811  /* Give a better score to a function with a specific number of arguments
89812  ** than to function that accepts any number of arguments. */
89813  if( p->nArg==nArg ){
89814    match = 4;
89815  }else{
89816    match = 1;
89817  }
89818
89819  /* Bonus points if the text encoding matches */
89820  if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
89821    match += 2;  /* Exact encoding match */
89822  }else if( (enc & p->funcFlags & 2)!=0 ){
89823    match += 1;  /* Both are UTF16, but with different byte orders */
89824  }
89825
89826  return match;
89827}
89828
89829/*
89830** Search a FuncDefHash for a function with the given name.  Return
89831** a pointer to the matching FuncDef if found, or 0 if there is no match.
89832*/
89833static FuncDef *functionSearch(
89834  FuncDefHash *pHash,  /* Hash table to search */
89835  int h,               /* Hash of the name */
89836  const char *zFunc,   /* Name of function */
89837  int nFunc            /* Number of bytes in zFunc */
89838){
89839  FuncDef *p;
89840  for(p=pHash->a[h]; p; p=p->pHash){
89841    if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
89842      return p;
89843    }
89844  }
89845  return 0;
89846}
89847
89848/*
89849** Insert a new FuncDef into a FuncDefHash hash table.
89850*/
89851SQLITE_PRIVATE void sqlite3FuncDefInsert(
89852  FuncDefHash *pHash,  /* The hash table into which to insert */
89853  FuncDef *pDef        /* The function definition to insert */
89854){
89855  FuncDef *pOther;
89856  int nName = sqlite3Strlen30(pDef->zName);
89857  u8 c1 = (u8)pDef->zName[0];
89858  int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
89859  pOther = functionSearch(pHash, h, pDef->zName, nName);
89860  if( pOther ){
89861    assert( pOther!=pDef && pOther->pNext!=pDef );
89862    pDef->pNext = pOther->pNext;
89863    pOther->pNext = pDef;
89864  }else{
89865    pDef->pNext = 0;
89866    pDef->pHash = pHash->a[h];
89867    pHash->a[h] = pDef;
89868  }
89869}
89870
89871
89872
89873/*
89874** Locate a user function given a name, a number of arguments and a flag
89875** indicating whether the function prefers UTF-16 over UTF-8.  Return a
89876** pointer to the FuncDef structure that defines that function, or return
89877** NULL if the function does not exist.
89878**
89879** If the createFlag argument is true, then a new (blank) FuncDef
89880** structure is created and liked into the "db" structure if a
89881** no matching function previously existed.
89882**
89883** If nArg is -2, then the first valid function found is returned.  A
89884** function is valid if either xFunc or xStep is non-zero.  The nArg==(-2)
89885** case is used to see if zName is a valid function name for some number
89886** of arguments.  If nArg is -2, then createFlag must be 0.
89887**
89888** If createFlag is false, then a function with the required name and
89889** number of arguments may be returned even if the eTextRep flag does not
89890** match that requested.
89891*/
89892SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
89893  sqlite3 *db,       /* An open database */
89894  const char *zName, /* Name of the function.  Not null-terminated */
89895  int nName,         /* Number of characters in the name */
89896  int nArg,          /* Number of arguments.  -1 means any number */
89897  u8 enc,            /* Preferred text encoding */
89898  u8 createFlag      /* Create new entry if true and does not otherwise exist */
89899){
89900  FuncDef *p;         /* Iterator variable */
89901  FuncDef *pBest = 0; /* Best match found so far */
89902  int bestScore = 0;  /* Score of best match */
89903  int h;              /* Hash value */
89904
89905  assert( nArg>=(-2) );
89906  assert( nArg>=(-1) || createFlag==0 );
89907  h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
89908
89909  /* First search for a match amongst the application-defined functions.
89910  */
89911  p = functionSearch(&db->aFunc, h, zName, nName);
89912  while( p ){
89913    int score = matchQuality(p, nArg, enc);
89914    if( score>bestScore ){
89915      pBest = p;
89916      bestScore = score;
89917    }
89918    p = p->pNext;
89919  }
89920
89921  /* If no match is found, search the built-in functions.
89922  **
89923  ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
89924  ** functions even if a prior app-defined function was found.  And give
89925  ** priority to built-in functions.
89926  **
89927  ** Except, if createFlag is true, that means that we are trying to
89928  ** install a new function.  Whatever FuncDef structure is returned it will
89929  ** have fields overwritten with new information appropriate for the
89930  ** new function.  But the FuncDefs for built-in functions are read-only.
89931  ** So we must not search for built-ins when creating a new function.
89932  */
89933  if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
89934    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
89935    bestScore = 0;
89936    p = functionSearch(pHash, h, zName, nName);
89937    while( p ){
89938      int score = matchQuality(p, nArg, enc);
89939      if( score>bestScore ){
89940        pBest = p;
89941        bestScore = score;
89942      }
89943      p = p->pNext;
89944    }
89945  }
89946
89947  /* If the createFlag parameter is true and the search did not reveal an
89948  ** exact match for the name, number of arguments and encoding, then add a
89949  ** new entry to the hash table and return it.
89950  */
89951  if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
89952      (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
89953    pBest->zName = (char *)&pBest[1];
89954    pBest->nArg = (u16)nArg;
89955    pBest->funcFlags = enc;
89956    memcpy(pBest->zName, zName, nName);
89957    pBest->zName[nName] = 0;
89958    sqlite3FuncDefInsert(&db->aFunc, pBest);
89959  }
89960
89961  if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
89962    return pBest;
89963  }
89964  return 0;
89965}
89966
89967/*
89968** Free all resources held by the schema structure. The void* argument points
89969** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
89970** pointer itself, it just cleans up subsidiary resources (i.e. the contents
89971** of the schema hash tables).
89972**
89973** The Schema.cache_size variable is not cleared.
89974*/
89975SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
89976  Hash temp1;
89977  Hash temp2;
89978  HashElem *pElem;
89979  Schema *pSchema = (Schema *)p;
89980
89981  temp1 = pSchema->tblHash;
89982  temp2 = pSchema->trigHash;
89983  sqlite3HashInit(&pSchema->trigHash);
89984  sqlite3HashClear(&pSchema->idxHash);
89985  for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
89986    sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
89987  }
89988  sqlite3HashClear(&temp2);
89989  sqlite3HashInit(&pSchema->tblHash);
89990  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
89991    Table *pTab = sqliteHashData(pElem);
89992    sqlite3DeleteTable(0, pTab);
89993  }
89994  sqlite3HashClear(&temp1);
89995  sqlite3HashClear(&pSchema->fkeyHash);
89996  pSchema->pSeqTab = 0;
89997  if( pSchema->flags & DB_SchemaLoaded ){
89998    pSchema->iGeneration++;
89999    pSchema->flags &= ~DB_SchemaLoaded;
90000  }
90001}
90002
90003/*
90004** Find and return the schema associated with a BTree.  Create
90005** a new one if necessary.
90006*/
90007SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
90008  Schema * p;
90009  if( pBt ){
90010    p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
90011  }else{
90012    p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
90013  }
90014  if( !p ){
90015    db->mallocFailed = 1;
90016  }else if ( 0==p->file_format ){
90017    sqlite3HashInit(&p->tblHash);
90018    sqlite3HashInit(&p->idxHash);
90019    sqlite3HashInit(&p->trigHash);
90020    sqlite3HashInit(&p->fkeyHash);
90021    p->enc = SQLITE_UTF8;
90022  }
90023  return p;
90024}
90025
90026/************** End of callback.c ********************************************/
90027/************** Begin file delete.c ******************************************/
90028/*
90029** 2001 September 15
90030**
90031** The author disclaims copyright to this source code.  In place of
90032** a legal notice, here is a blessing:
90033**
90034**    May you do good and not evil.
90035**    May you find forgiveness for yourself and forgive others.
90036**    May you share freely, never taking more than you give.
90037**
90038*************************************************************************
90039** This file contains C code routines that are called by the parser
90040** in order to generate code for DELETE FROM statements.
90041*/
90042
90043/*
90044** While a SrcList can in general represent multiple tables and subqueries
90045** (as in the FROM clause of a SELECT statement) in this case it contains
90046** the name of a single table, as one might find in an INSERT, DELETE,
90047** or UPDATE statement.  Look up that table in the symbol table and
90048** return a pointer.  Set an error message and return NULL if the table
90049** name is not found or if any other error occurs.
90050**
90051** The following fields are initialized appropriate in pSrc:
90052**
90053**    pSrc->a[0].pTab       Pointer to the Table object
90054**    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
90055**
90056*/
90057SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
90058  struct SrcList_item *pItem = pSrc->a;
90059  Table *pTab;
90060  assert( pItem && pSrc->nSrc==1 );
90061  pTab = sqlite3LocateTableItem(pParse, 0, pItem);
90062  sqlite3DeleteTable(pParse->db, pItem->pTab);
90063  pItem->pTab = pTab;
90064  if( pTab ){
90065    pTab->nRef++;
90066  }
90067  if( sqlite3IndexedByLookup(pParse, pItem) ){
90068    pTab = 0;
90069  }
90070  return pTab;
90071}
90072
90073/*
90074** Check to make sure the given table is writable.  If it is not
90075** writable, generate an error message and return 1.  If it is
90076** writable return 0;
90077*/
90078SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
90079  /* A table is not writable under the following circumstances:
90080  **
90081  **   1) It is a virtual table and no implementation of the xUpdate method
90082  **      has been provided, or
90083  **   2) It is a system table (i.e. sqlite_master), this call is not
90084  **      part of a nested parse and writable_schema pragma has not
90085  **      been specified.
90086  **
90087  ** In either case leave an error message in pParse and return non-zero.
90088  */
90089  if( ( IsVirtual(pTab)
90090     && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
90091   || ( (pTab->tabFlags & TF_Readonly)!=0
90092     && (pParse->db->flags & SQLITE_WriteSchema)==0
90093     && pParse->nested==0 )
90094  ){
90095    sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
90096    return 1;
90097  }
90098
90099#ifndef SQLITE_OMIT_VIEW
90100  if( !viewOk && pTab->pSelect ){
90101    sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
90102    return 1;
90103  }
90104#endif
90105  return 0;
90106}
90107
90108
90109#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
90110/*
90111** Evaluate a view and store its result in an ephemeral table.  The
90112** pWhere argument is an optional WHERE clause that restricts the
90113** set of rows in the view that are to be added to the ephemeral table.
90114*/
90115SQLITE_PRIVATE void sqlite3MaterializeView(
90116  Parse *pParse,       /* Parsing context */
90117  Table *pView,        /* View definition */
90118  Expr *pWhere,        /* Optional WHERE clause to be added */
90119  int iCur             /* Cursor number for ephemerial table */
90120){
90121  SelectDest dest;
90122  Select *pSel;
90123  SrcList *pFrom;
90124  sqlite3 *db = pParse->db;
90125  int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
90126  pWhere = sqlite3ExprDup(db, pWhere, 0);
90127  pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
90128  if( pFrom ){
90129    assert( pFrom->nSrc==1 );
90130    pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
90131    pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
90132    assert( pFrom->a[0].pOn==0 );
90133    assert( pFrom->a[0].pUsing==0 );
90134  }
90135  pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
90136  sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
90137  sqlite3Select(pParse, pSel, &dest);
90138  sqlite3SelectDelete(db, pSel);
90139}
90140#endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
90141
90142#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
90143/*
90144** Generate an expression tree to implement the WHERE, ORDER BY,
90145** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
90146**
90147**     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
90148**                            \__________________________/
90149**                               pLimitWhere (pInClause)
90150*/
90151SQLITE_PRIVATE Expr *sqlite3LimitWhere(
90152  Parse *pParse,               /* The parser context */
90153  SrcList *pSrc,               /* the FROM clause -- which tables to scan */
90154  Expr *pWhere,                /* The WHERE clause.  May be null */
90155  ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
90156  Expr *pLimit,                /* The LIMIT clause.  May be null */
90157  Expr *pOffset,               /* The OFFSET clause.  May be null */
90158  char *zStmtType              /* Either DELETE or UPDATE.  For err msgs. */
90159){
90160  Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
90161  Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
90162  Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
90163  ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
90164  SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
90165  Select *pSelect = NULL;      /* Complete SELECT tree */
90166
90167  /* Check that there isn't an ORDER BY without a LIMIT clause.
90168  */
90169  if( pOrderBy && (pLimit == 0) ) {
90170    sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
90171    goto limit_where_cleanup_2;
90172  }
90173
90174  /* We only need to generate a select expression if there
90175  ** is a limit/offset term to enforce.
90176  */
90177  if( pLimit == 0 ) {
90178    /* if pLimit is null, pOffset will always be null as well. */
90179    assert( pOffset == 0 );
90180    return pWhere;
90181  }
90182
90183  /* Generate a select expression tree to enforce the limit/offset
90184  ** term for the DELETE or UPDATE statement.  For example:
90185  **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
90186  ** becomes:
90187  **   DELETE FROM table_a WHERE rowid IN (
90188  **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
90189  **   );
90190  */
90191
90192  pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
90193  if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
90194  pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
90195  if( pEList == 0 ) goto limit_where_cleanup_2;
90196
90197  /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
90198  ** and the SELECT subtree. */
90199  pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
90200  if( pSelectSrc == 0 ) {
90201    sqlite3ExprListDelete(pParse->db, pEList);
90202    goto limit_where_cleanup_2;
90203  }
90204
90205  /* generate the SELECT expression tree. */
90206  pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
90207                             pOrderBy,0,pLimit,pOffset);
90208  if( pSelect == 0 ) return 0;
90209
90210  /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
90211  pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
90212  if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
90213  pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
90214  if( pInClause == 0 ) goto limit_where_cleanup_1;
90215
90216  pInClause->x.pSelect = pSelect;
90217  pInClause->flags |= EP_xIsSelect;
90218  sqlite3ExprSetHeight(pParse, pInClause);
90219  return pInClause;
90220
90221  /* something went wrong. clean up anything allocated. */
90222limit_where_cleanup_1:
90223  sqlite3SelectDelete(pParse->db, pSelect);
90224  return 0;
90225
90226limit_where_cleanup_2:
90227  sqlite3ExprDelete(pParse->db, pWhere);
90228  sqlite3ExprListDelete(pParse->db, pOrderBy);
90229  sqlite3ExprDelete(pParse->db, pLimit);
90230  sqlite3ExprDelete(pParse->db, pOffset);
90231  return 0;
90232}
90233#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
90234       /*      && !defined(SQLITE_OMIT_SUBQUERY) */
90235
90236/*
90237** Generate code for a DELETE FROM statement.
90238**
90239**     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
90240**                 \________/       \________________/
90241**                  pTabList              pWhere
90242*/
90243SQLITE_PRIVATE void sqlite3DeleteFrom(
90244  Parse *pParse,         /* The parser context */
90245  SrcList *pTabList,     /* The table from which we should delete things */
90246  Expr *pWhere           /* The WHERE clause.  May be null */
90247){
90248  Vdbe *v;               /* The virtual database engine */
90249  Table *pTab;           /* The table from which records will be deleted */
90250  const char *zDb;       /* Name of database holding pTab */
90251  int i;                 /* Loop counter */
90252  WhereInfo *pWInfo;     /* Information about the WHERE clause */
90253  Index *pIdx;           /* For looping over indices of the table */
90254  int iTabCur;           /* Cursor number for the table */
90255  int iDataCur;          /* VDBE cursor for the canonical data source */
90256  int iIdxCur;           /* Cursor number of the first index */
90257  int nIdx;              /* Number of indices */
90258  sqlite3 *db;           /* Main database structure */
90259  AuthContext sContext;  /* Authorization context */
90260  NameContext sNC;       /* Name context to resolve expressions in */
90261  int iDb;               /* Database number */
90262  int memCnt = -1;       /* Memory cell used for change counting */
90263  int rcauth;            /* Value returned by authorization callback */
90264  int okOnePass;         /* True for one-pass algorithm without the FIFO */
90265  int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
90266  u8 *aToOpen = 0;       /* Open cursor iTabCur+j if aToOpen[j] is true */
90267  Index *pPk;            /* The PRIMARY KEY index on the table */
90268  int iPk = 0;           /* First of nPk registers holding PRIMARY KEY value */
90269  i16 nPk = 1;           /* Number of columns in the PRIMARY KEY */
90270  int iKey;              /* Memory cell holding key of row to be deleted */
90271  i16 nKey;              /* Number of memory cells in the row key */
90272  int iEphCur = 0;       /* Ephemeral table holding all primary key values */
90273  int iRowSet = 0;       /* Register for rowset of rows to delete */
90274  int addrBypass = 0;    /* Address of jump over the delete logic */
90275  int addrLoop = 0;      /* Top of the delete loop */
90276  int addrDelete = 0;    /* Jump directly to the delete logic */
90277  int addrEphOpen = 0;   /* Instruction to open the Ephermeral table */
90278
90279#ifndef SQLITE_OMIT_TRIGGER
90280  int isView;                  /* True if attempting to delete from a view */
90281  Trigger *pTrigger;           /* List of table triggers, if required */
90282#endif
90283
90284  memset(&sContext, 0, sizeof(sContext));
90285  db = pParse->db;
90286  if( pParse->nErr || db->mallocFailed ){
90287    goto delete_from_cleanup;
90288  }
90289  assert( pTabList->nSrc==1 );
90290
90291  /* Locate the table which we want to delete.  This table has to be
90292  ** put in an SrcList structure because some of the subroutines we
90293  ** will be calling are designed to work with multiple tables and expect
90294  ** an SrcList* parameter instead of just a Table* parameter.
90295  */
90296  pTab = sqlite3SrcListLookup(pParse, pTabList);
90297  if( pTab==0 )  goto delete_from_cleanup;
90298
90299  /* Figure out if we have any triggers and if the table being
90300  ** deleted from is a view
90301  */
90302#ifndef SQLITE_OMIT_TRIGGER
90303  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
90304  isView = pTab->pSelect!=0;
90305#else
90306# define pTrigger 0
90307# define isView 0
90308#endif
90309#ifdef SQLITE_OMIT_VIEW
90310# undef isView
90311# define isView 0
90312#endif
90313
90314  /* If pTab is really a view, make sure it has been initialized.
90315  */
90316  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
90317    goto delete_from_cleanup;
90318  }
90319
90320  if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
90321    goto delete_from_cleanup;
90322  }
90323  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
90324  assert( iDb<db->nDb );
90325  zDb = db->aDb[iDb].zName;
90326  rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
90327  assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
90328  if( rcauth==SQLITE_DENY ){
90329    goto delete_from_cleanup;
90330  }
90331  assert(!isView || pTrigger);
90332
90333  /* Assign cursor numbers to the table and all its indices.
90334  */
90335  assert( pTabList->nSrc==1 );
90336  iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
90337  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
90338    pParse->nTab++;
90339  }
90340
90341  /* Start the view context
90342  */
90343  if( isView ){
90344    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
90345  }
90346
90347  /* Begin generating code.
90348  */
90349  v = sqlite3GetVdbe(pParse);
90350  if( v==0 ){
90351    goto delete_from_cleanup;
90352  }
90353  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
90354  sqlite3BeginWriteOperation(pParse, 1, iDb);
90355
90356  /* If we are trying to delete from a view, realize that view into
90357  ** a ephemeral table.
90358  */
90359#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
90360  if( isView ){
90361    sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
90362    iDataCur = iIdxCur = iTabCur;
90363  }
90364#endif
90365
90366  /* Resolve the column names in the WHERE clause.
90367  */
90368  memset(&sNC, 0, sizeof(sNC));
90369  sNC.pParse = pParse;
90370  sNC.pSrcList = pTabList;
90371  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
90372    goto delete_from_cleanup;
90373  }
90374
90375  /* Initialize the counter of the number of rows deleted, if
90376  ** we are counting rows.
90377  */
90378  if( db->flags & SQLITE_CountRows ){
90379    memCnt = ++pParse->nMem;
90380    sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
90381  }
90382
90383#ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
90384  /* Special case: A DELETE without a WHERE clause deletes everything.
90385  ** It is easier just to erase the whole table. Prior to version 3.6.5,
90386  ** this optimization caused the row change count (the value returned by
90387  ** API function sqlite3_count_changes) to be set incorrectly.  */
90388  if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
90389   && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
90390  ){
90391    assert( !isView );
90392    sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
90393    if( HasRowid(pTab) ){
90394      sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
90395                        pTab->zName, P4_STATIC);
90396    }
90397    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
90398      assert( pIdx->pSchema==pTab->pSchema );
90399      sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
90400    }
90401  }else
90402#endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
90403  {
90404    if( HasRowid(pTab) ){
90405      /* For a rowid table, initialize the RowSet to an empty set */
90406      pPk = 0;
90407      nPk = 1;
90408      iRowSet = ++pParse->nMem;
90409      sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
90410    }else{
90411      /* For a WITHOUT ROWID table, create an ephermeral table used to
90412      ** hold all primary keys for rows to be deleted. */
90413      pPk = sqlite3PrimaryKeyIndex(pTab);
90414      assert( pPk!=0 );
90415      nPk = pPk->nKeyCol;
90416      iPk = pParse->nMem+1;
90417      pParse->nMem += nPk;
90418      iEphCur = pParse->nTab++;
90419      addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
90420      sqlite3VdbeSetP4KeyInfo(pParse, pPk);
90421    }
90422
90423    /* Construct a query to find the rowid or primary key for every row
90424    ** to be deleted, based on the WHERE clause.
90425    */
90426    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
90427                               WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK,
90428                               iTabCur+1);
90429    if( pWInfo==0 ) goto delete_from_cleanup;
90430    okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
90431
90432    /* Keep track of the number of rows to be deleted */
90433    if( db->flags & SQLITE_CountRows ){
90434      sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
90435    }
90436
90437    /* Extract the rowid or primary key for the current row */
90438    if( pPk ){
90439      for(i=0; i<nPk; i++){
90440        sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
90441                                        pPk->aiColumn[i], iPk+i);
90442      }
90443      iKey = iPk;
90444    }else{
90445      iKey = pParse->nMem + 1;
90446      iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
90447      if( iKey>pParse->nMem ) pParse->nMem = iKey;
90448    }
90449
90450    if( okOnePass ){
90451      /* For ONEPASS, no need to store the rowid/primary-key.  There is only
90452      ** one, so just keep it in its register(s) and fall through to the
90453      ** delete code.
90454      */
90455      nKey = nPk; /* OP_Found will use an unpacked key */
90456      aToOpen = sqlite3DbMallocRaw(db, nIdx+2);
90457      if( aToOpen==0 ){
90458        sqlite3WhereEnd(pWInfo);
90459        goto delete_from_cleanup;
90460      }
90461      memset(aToOpen, 1, nIdx+1);
90462      aToOpen[nIdx+1] = 0;
90463      if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
90464      if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
90465      if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
90466      addrDelete = sqlite3VdbeAddOp0(v, OP_Goto); /* Jump to DELETE logic */
90467    }else if( pPk ){
90468      /* Construct a composite key for the row to be deleted and remember it */
90469      iKey = ++pParse->nMem;
90470      nKey = 0;   /* Zero tells OP_Found to use a composite key */
90471      sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
90472                        sqlite3IndexAffinityStr(v, pPk), nPk);
90473      sqlite3VdbeAddOp2(v, OP_IdxInsert, iEphCur, iKey);
90474    }else{
90475      /* Get the rowid of the row to be deleted and remember it in the RowSet */
90476      nKey = 1;  /* OP_Seek always uses a single rowid */
90477      sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
90478    }
90479
90480    /* End of the WHERE loop */
90481    sqlite3WhereEnd(pWInfo);
90482    if( okOnePass ){
90483      /* Bypass the delete logic below if the WHERE loop found zero rows */
90484      addrBypass = sqlite3VdbeMakeLabel(v);
90485      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrBypass);
90486      sqlite3VdbeJumpHere(v, addrDelete);
90487    }
90488
90489    /* Unless this is a view, open cursors for the table we are
90490    ** deleting from and all its indices. If this is a view, then the
90491    ** only effect this statement has is to fire the INSTEAD OF
90492    ** triggers.
90493    */
90494    if( !isView ){
90495      sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iTabCur, aToOpen,
90496                                 &iDataCur, &iIdxCur);
90497      assert( pPk || iDataCur==iTabCur );
90498      assert( pPk || iIdxCur==iDataCur+1 );
90499    }
90500
90501    /* Set up a loop over the rowids/primary-keys that were found in the
90502    ** where-clause loop above.
90503    */
90504    if( okOnePass ){
90505      /* Just one row.  Hence the top-of-loop is a no-op */
90506      assert( nKey==nPk ); /* OP_Found will use an unpacked key */
90507      if( aToOpen[iDataCur-iTabCur] ){
90508        assert( pPk!=0 );
90509        sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
90510        VdbeCoverage(v);
90511      }
90512    }else if( pPk ){
90513      addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
90514      sqlite3VdbeAddOp2(v, OP_RowKey, iEphCur, iKey);
90515      assert( nKey==0 );  /* OP_Found will use a composite key */
90516    }else{
90517      addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
90518      VdbeCoverage(v);
90519      assert( nKey==1 );
90520    }
90521
90522    /* Delete the row */
90523#ifndef SQLITE_OMIT_VIRTUALTABLE
90524    if( IsVirtual(pTab) ){
90525      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
90526      sqlite3VtabMakeWritable(pParse, pTab);
90527      sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
90528      sqlite3VdbeChangeP5(v, OE_Abort);
90529      sqlite3MayAbort(pParse);
90530    }else
90531#endif
90532    {
90533      int count = (pParse->nested==0);    /* True to count changes */
90534      sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
90535                               iKey, nKey, count, OE_Default, okOnePass);
90536    }
90537
90538    /* End of the loop over all rowids/primary-keys. */
90539    if( okOnePass ){
90540      sqlite3VdbeResolveLabel(v, addrBypass);
90541    }else if( pPk ){
90542      sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
90543      sqlite3VdbeJumpHere(v, addrLoop);
90544    }else{
90545      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrLoop);
90546      sqlite3VdbeJumpHere(v, addrLoop);
90547    }
90548
90549    /* Close the cursors open on the table and its indexes. */
90550    if( !isView && !IsVirtual(pTab) ){
90551      if( !pPk ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
90552      for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
90553        sqlite3VdbeAddOp1(v, OP_Close, iIdxCur + i);
90554      }
90555    }
90556  } /* End non-truncate path */
90557
90558  /* Update the sqlite_sequence table by storing the content of the
90559  ** maximum rowid counter values recorded while inserting into
90560  ** autoincrement tables.
90561  */
90562  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
90563    sqlite3AutoincrementEnd(pParse);
90564  }
90565
90566  /* Return the number of rows that were deleted. If this routine is
90567  ** generating code because of a call to sqlite3NestedParse(), do not
90568  ** invoke the callback function.
90569  */
90570  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
90571    sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
90572    sqlite3VdbeSetNumCols(v, 1);
90573    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
90574  }
90575
90576delete_from_cleanup:
90577  sqlite3AuthContextPop(&sContext);
90578  sqlite3SrcListDelete(db, pTabList);
90579  sqlite3ExprDelete(db, pWhere);
90580  sqlite3DbFree(db, aToOpen);
90581  return;
90582}
90583/* Make sure "isView" and other macros defined above are undefined. Otherwise
90584** thely may interfere with compilation of other functions in this file
90585** (or in another file, if this file becomes part of the amalgamation).  */
90586#ifdef isView
90587 #undef isView
90588#endif
90589#ifdef pTrigger
90590 #undef pTrigger
90591#endif
90592
90593/*
90594** This routine generates VDBE code that causes a single row of a
90595** single table to be deleted.  Both the original table entry and
90596** all indices are removed.
90597**
90598** Preconditions:
90599**
90600**   1.  iDataCur is an open cursor on the btree that is the canonical data
90601**       store for the table.  (This will be either the table itself,
90602**       in the case of a rowid table, or the PRIMARY KEY index in the case
90603**       of a WITHOUT ROWID table.)
90604**
90605**   2.  Read/write cursors for all indices of pTab must be open as
90606**       cursor number iIdxCur+i for the i-th index.
90607**
90608**   3.  The primary key for the row to be deleted must be stored in a
90609**       sequence of nPk memory cells starting at iPk.  If nPk==0 that means
90610**       that a search record formed from OP_MakeRecord is contained in the
90611**       single memory location iPk.
90612*/
90613SQLITE_PRIVATE void sqlite3GenerateRowDelete(
90614  Parse *pParse,     /* Parsing context */
90615  Table *pTab,       /* Table containing the row to be deleted */
90616  Trigger *pTrigger, /* List of triggers to (potentially) fire */
90617  int iDataCur,      /* Cursor from which column data is extracted */
90618  int iIdxCur,       /* First index cursor */
90619  int iPk,           /* First memory cell containing the PRIMARY KEY */
90620  i16 nPk,           /* Number of PRIMARY KEY memory cells */
90621  u8 count,          /* If non-zero, increment the row change counter */
90622  u8 onconf,         /* Default ON CONFLICT policy for triggers */
90623  u8 bNoSeek         /* iDataCur is already pointing to the row to delete */
90624){
90625  Vdbe *v = pParse->pVdbe;        /* Vdbe */
90626  int iOld = 0;                   /* First register in OLD.* array */
90627  int iLabel;                     /* Label resolved to end of generated code */
90628  u8 opSeek;                      /* Seek opcode */
90629
90630  /* Vdbe is guaranteed to have been allocated by this stage. */
90631  assert( v );
90632  VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
90633                         iDataCur, iIdxCur, iPk, (int)nPk));
90634
90635  /* Seek cursor iCur to the row to delete. If this row no longer exists
90636  ** (this can happen if a trigger program has already deleted it), do
90637  ** not attempt to delete it or fire any DELETE triggers.  */
90638  iLabel = sqlite3VdbeMakeLabel(v);
90639  opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
90640  if( !bNoSeek ){
90641    sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
90642    VdbeCoverageIf(v, opSeek==OP_NotExists);
90643    VdbeCoverageIf(v, opSeek==OP_NotFound);
90644  }
90645
90646  /* If there are any triggers to fire, allocate a range of registers to
90647  ** use for the old.* references in the triggers.  */
90648  if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
90649    u32 mask;                     /* Mask of OLD.* columns in use */
90650    int iCol;                     /* Iterator used while populating OLD.* */
90651    int addrStart;                /* Start of BEFORE trigger programs */
90652
90653    /* TODO: Could use temporary registers here. Also could attempt to
90654    ** avoid copying the contents of the rowid register.  */
90655    mask = sqlite3TriggerColmask(
90656        pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
90657    );
90658    mask |= sqlite3FkOldmask(pParse, pTab);
90659    iOld = pParse->nMem+1;
90660    pParse->nMem += (1 + pTab->nCol);
90661
90662    /* Populate the OLD.* pseudo-table register array. These values will be
90663    ** used by any BEFORE and AFTER triggers that exist.  */
90664    sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
90665    for(iCol=0; iCol<pTab->nCol; iCol++){
90666      testcase( mask!=0xffffffff && iCol==31 );
90667      testcase( mask!=0xffffffff && iCol==32 );
90668      if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
90669        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
90670      }
90671    }
90672
90673    /* Invoke BEFORE DELETE trigger programs. */
90674    addrStart = sqlite3VdbeCurrentAddr(v);
90675    sqlite3CodeRowTrigger(pParse, pTrigger,
90676        TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
90677    );
90678
90679    /* If any BEFORE triggers were coded, then seek the cursor to the
90680    ** row to be deleted again. It may be that the BEFORE triggers moved
90681    ** the cursor or of already deleted the row that the cursor was
90682    ** pointing to.
90683    */
90684    if( addrStart<sqlite3VdbeCurrentAddr(v) ){
90685      sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
90686      VdbeCoverageIf(v, opSeek==OP_NotExists);
90687      VdbeCoverageIf(v, opSeek==OP_NotFound);
90688    }
90689
90690    /* Do FK processing. This call checks that any FK constraints that
90691    ** refer to this table (i.e. constraints attached to other tables)
90692    ** are not violated by deleting this row.  */
90693    sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
90694  }
90695
90696  /* Delete the index and table entries. Skip this step if pTab is really
90697  ** a view (in which case the only effect of the DELETE statement is to
90698  ** fire the INSTEAD OF triggers).  */
90699  if( pTab->pSelect==0 ){
90700    sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
90701    sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
90702    if( count ){
90703      sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
90704    }
90705  }
90706
90707  /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
90708  ** handle rows (possibly in other tables) that refer via a foreign key
90709  ** to the row just deleted. */
90710  sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
90711
90712  /* Invoke AFTER DELETE trigger programs. */
90713  sqlite3CodeRowTrigger(pParse, pTrigger,
90714      TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
90715  );
90716
90717  /* Jump here if the row had already been deleted before any BEFORE
90718  ** trigger programs were invoked. Or if a trigger program throws a
90719  ** RAISE(IGNORE) exception.  */
90720  sqlite3VdbeResolveLabel(v, iLabel);
90721  VdbeModuleComment((v, "END: GenRowDel()"));
90722}
90723
90724/*
90725** This routine generates VDBE code that causes the deletion of all
90726** index entries associated with a single row of a single table, pTab
90727**
90728** Preconditions:
90729**
90730**   1.  A read/write cursor "iDataCur" must be open on the canonical storage
90731**       btree for the table pTab.  (This will be either the table itself
90732**       for rowid tables or to the primary key index for WITHOUT ROWID
90733**       tables.)
90734**
90735**   2.  Read/write cursors for all indices of pTab must be open as
90736**       cursor number iIdxCur+i for the i-th index.  (The pTab->pIndex
90737**       index is the 0-th index.)
90738**
90739**   3.  The "iDataCur" cursor must be already be positioned on the row
90740**       that is to be deleted.
90741*/
90742SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
90743  Parse *pParse,     /* Parsing and code generating context */
90744  Table *pTab,       /* Table containing the row to be deleted */
90745  int iDataCur,      /* Cursor of table holding data. */
90746  int iIdxCur,       /* First index cursor */
90747  int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
90748){
90749  int i;             /* Index loop counter */
90750  int r1 = -1;       /* Register holding an index key */
90751  int iPartIdxLabel; /* Jump destination for skipping partial index entries */
90752  Index *pIdx;       /* Current index */
90753  Index *pPrior = 0; /* Prior index */
90754  Vdbe *v;           /* The prepared statement under construction */
90755  Index *pPk;        /* PRIMARY KEY index, or NULL for rowid tables */
90756
90757  v = pParse->pVdbe;
90758  pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
90759  for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
90760    assert( iIdxCur+i!=iDataCur || pPk==pIdx );
90761    if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
90762    if( pIdx==pPk ) continue;
90763    VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
90764    r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
90765                                 &iPartIdxLabel, pPrior, r1);
90766    sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
90767                      pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
90768    sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
90769    pPrior = pIdx;
90770  }
90771}
90772
90773/*
90774** Generate code that will assemble an index key and stores it in register
90775** regOut.  The key with be for index pIdx which is an index on pTab.
90776** iCur is the index of a cursor open on the pTab table and pointing to
90777** the entry that needs indexing.  If pTab is a WITHOUT ROWID table, then
90778** iCur must be the cursor of the PRIMARY KEY index.
90779**
90780** Return a register number which is the first in a block of
90781** registers that holds the elements of the index key.  The
90782** block of registers has already been deallocated by the time
90783** this routine returns.
90784**
90785** If *piPartIdxLabel is not NULL, fill it in with a label and jump
90786** to that label if pIdx is a partial index that should be skipped.
90787** The label should be resolved using sqlite3ResolvePartIdxLabel().
90788** A partial index should be skipped if its WHERE clause evaluates
90789** to false or null.  If pIdx is not a partial index, *piPartIdxLabel
90790** will be set to zero which is an empty label that is ignored by
90791** sqlite3ResolvePartIdxLabel().
90792**
90793** The pPrior and regPrior parameters are used to implement a cache to
90794** avoid unnecessary register loads.  If pPrior is not NULL, then it is
90795** a pointer to a different index for which an index key has just been
90796** computed into register regPrior.  If the current pIdx index is generating
90797** its key into the same sequence of registers and if pPrior and pIdx share
90798** a column in common, then the register corresponding to that column already
90799** holds the correct value and the loading of that register is skipped.
90800** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
90801** on a table with multiple indices, and especially with the ROWID or
90802** PRIMARY KEY columns of the index.
90803*/
90804SQLITE_PRIVATE int sqlite3GenerateIndexKey(
90805  Parse *pParse,       /* Parsing context */
90806  Index *pIdx,         /* The index for which to generate a key */
90807  int iDataCur,        /* Cursor number from which to take column data */
90808  int regOut,          /* Put the new key into this register if not 0 */
90809  int prefixOnly,      /* Compute only a unique prefix of the key */
90810  int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
90811  Index *pPrior,       /* Previously generated index key */
90812  int regPrior         /* Register holding previous generated key */
90813){
90814  Vdbe *v = pParse->pVdbe;
90815  int j;
90816  Table *pTab = pIdx->pTable;
90817  int regBase;
90818  int nCol;
90819
90820  if( piPartIdxLabel ){
90821    if( pIdx->pPartIdxWhere ){
90822      *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
90823      pParse->iPartIdxTab = iDataCur;
90824      sqlite3ExprCachePush(pParse);
90825      sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
90826                         SQLITE_JUMPIFNULL);
90827    }else{
90828      *piPartIdxLabel = 0;
90829    }
90830  }
90831  nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
90832  regBase = sqlite3GetTempRange(pParse, nCol);
90833  if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
90834  for(j=0; j<nCol; j++){
90835    if( pPrior && pPrior->aiColumn[j]==pIdx->aiColumn[j] ) continue;
90836    sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pIdx->aiColumn[j],
90837                                    regBase+j);
90838    /* If the column affinity is REAL but the number is an integer, then it
90839    ** might be stored in the table as an integer (using a compact
90840    ** representation) then converted to REAL by an OP_RealAffinity opcode.
90841    ** But we are getting ready to store this value back into an index, where
90842    ** it should be converted by to INTEGER again.  So omit the OP_RealAffinity
90843    ** opcode if it is present */
90844    sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
90845  }
90846  if( regOut ){
90847    sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
90848  }
90849  sqlite3ReleaseTempRange(pParse, regBase, nCol);
90850  return regBase;
90851}
90852
90853/*
90854** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
90855** because it was a partial index, then this routine should be called to
90856** resolve that label.
90857*/
90858SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
90859  if( iLabel ){
90860    sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
90861    sqlite3ExprCachePop(pParse);
90862  }
90863}
90864
90865/************** End of delete.c **********************************************/
90866/************** Begin file func.c ********************************************/
90867/*
90868** 2002 February 23
90869**
90870** The author disclaims copyright to this source code.  In place of
90871** a legal notice, here is a blessing:
90872**
90873**    May you do good and not evil.
90874**    May you find forgiveness for yourself and forgive others.
90875**    May you share freely, never taking more than you give.
90876**
90877*************************************************************************
90878** This file contains the C functions that implement various SQL
90879** functions of SQLite.
90880**
90881** There is only one exported symbol in this file - the function
90882** sqliteRegisterBuildinFunctions() found at the bottom of the file.
90883** All other code has file scope.
90884*/
90885/* #include <stdlib.h> */
90886/* #include <assert.h> */
90887
90888/*
90889** Return the collating function associated with a function.
90890*/
90891static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
90892  return context->pColl;
90893}
90894
90895/*
90896** Indicate that the accumulator load should be skipped on this
90897** iteration of the aggregate loop.
90898*/
90899static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
90900  context->skipFlag = 1;
90901}
90902
90903/*
90904** Implementation of the non-aggregate min() and max() functions
90905*/
90906static void minmaxFunc(
90907  sqlite3_context *context,
90908  int argc,
90909  sqlite3_value **argv
90910){
90911  int i;
90912  int mask;    /* 0 for min() or 0xffffffff for max() */
90913  int iBest;
90914  CollSeq *pColl;
90915
90916  assert( argc>1 );
90917  mask = sqlite3_user_data(context)==0 ? 0 : -1;
90918  pColl = sqlite3GetFuncCollSeq(context);
90919  assert( pColl );
90920  assert( mask==-1 || mask==0 );
90921  iBest = 0;
90922  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
90923  for(i=1; i<argc; i++){
90924    if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
90925    if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
90926      testcase( mask==0 );
90927      iBest = i;
90928    }
90929  }
90930  sqlite3_result_value(context, argv[iBest]);
90931}
90932
90933/*
90934** Return the type of the argument.
90935*/
90936static void typeofFunc(
90937  sqlite3_context *context,
90938  int NotUsed,
90939  sqlite3_value **argv
90940){
90941  const char *z = 0;
90942  UNUSED_PARAMETER(NotUsed);
90943  switch( sqlite3_value_type(argv[0]) ){
90944    case SQLITE_INTEGER: z = "integer"; break;
90945    case SQLITE_TEXT:    z = "text";    break;
90946    case SQLITE_FLOAT:   z = "real";    break;
90947    case SQLITE_BLOB:    z = "blob";    break;
90948    default:             z = "null";    break;
90949  }
90950  sqlite3_result_text(context, z, -1, SQLITE_STATIC);
90951}
90952
90953
90954/*
90955** Implementation of the length() function
90956*/
90957static void lengthFunc(
90958  sqlite3_context *context,
90959  int argc,
90960  sqlite3_value **argv
90961){
90962  int len;
90963
90964  assert( argc==1 );
90965  UNUSED_PARAMETER(argc);
90966  switch( sqlite3_value_type(argv[0]) ){
90967    case SQLITE_BLOB:
90968    case SQLITE_INTEGER:
90969    case SQLITE_FLOAT: {
90970      sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
90971      break;
90972    }
90973    case SQLITE_TEXT: {
90974      const unsigned char *z = sqlite3_value_text(argv[0]);
90975      if( z==0 ) return;
90976      len = 0;
90977      while( *z ){
90978        len++;
90979        SQLITE_SKIP_UTF8(z);
90980      }
90981      sqlite3_result_int(context, len);
90982      break;
90983    }
90984    default: {
90985      sqlite3_result_null(context);
90986      break;
90987    }
90988  }
90989}
90990
90991/*
90992** Implementation of the abs() function.
90993**
90994** IMP: R-23979-26855 The abs(X) function returns the absolute value of
90995** the numeric argument X.
90996*/
90997static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
90998  assert( argc==1 );
90999  UNUSED_PARAMETER(argc);
91000  switch( sqlite3_value_type(argv[0]) ){
91001    case SQLITE_INTEGER: {
91002      i64 iVal = sqlite3_value_int64(argv[0]);
91003      if( iVal<0 ){
91004        if( iVal==SMALLEST_INT64 ){
91005          /* IMP: R-31676-45509 If X is the integer -9223372036854775808
91006          ** then abs(X) throws an integer overflow error since there is no
91007          ** equivalent positive 64-bit two complement value. */
91008          sqlite3_result_error(context, "integer overflow", -1);
91009          return;
91010        }
91011        iVal = -iVal;
91012      }
91013      sqlite3_result_int64(context, iVal);
91014      break;
91015    }
91016    case SQLITE_NULL: {
91017      /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
91018      sqlite3_result_null(context);
91019      break;
91020    }
91021    default: {
91022      /* Because sqlite3_value_double() returns 0.0 if the argument is not
91023      ** something that can be converted into a number, we have:
91024      ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
91025      ** cannot be converted to a numeric value.
91026      */
91027      double rVal = sqlite3_value_double(argv[0]);
91028      if( rVal<0 ) rVal = -rVal;
91029      sqlite3_result_double(context, rVal);
91030      break;
91031    }
91032  }
91033}
91034
91035/*
91036** Implementation of the instr() function.
91037**
91038** instr(haystack,needle) finds the first occurrence of needle
91039** in haystack and returns the number of previous characters plus 1,
91040** or 0 if needle does not occur within haystack.
91041**
91042** If both haystack and needle are BLOBs, then the result is one more than
91043** the number of bytes in haystack prior to the first occurrence of needle,
91044** or 0 if needle never occurs in haystack.
91045*/
91046static void instrFunc(
91047  sqlite3_context *context,
91048  int argc,
91049  sqlite3_value **argv
91050){
91051  const unsigned char *zHaystack;
91052  const unsigned char *zNeedle;
91053  int nHaystack;
91054  int nNeedle;
91055  int typeHaystack, typeNeedle;
91056  int N = 1;
91057  int isText;
91058
91059  UNUSED_PARAMETER(argc);
91060  typeHaystack = sqlite3_value_type(argv[0]);
91061  typeNeedle = sqlite3_value_type(argv[1]);
91062  if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
91063  nHaystack = sqlite3_value_bytes(argv[0]);
91064  nNeedle = sqlite3_value_bytes(argv[1]);
91065  if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
91066    zHaystack = sqlite3_value_blob(argv[0]);
91067    zNeedle = sqlite3_value_blob(argv[1]);
91068    isText = 0;
91069  }else{
91070    zHaystack = sqlite3_value_text(argv[0]);
91071    zNeedle = sqlite3_value_text(argv[1]);
91072    isText = 1;
91073  }
91074  while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
91075    N++;
91076    do{
91077      nHaystack--;
91078      zHaystack++;
91079    }while( isText && (zHaystack[0]&0xc0)==0x80 );
91080  }
91081  if( nNeedle>nHaystack ) N = 0;
91082  sqlite3_result_int(context, N);
91083}
91084
91085/*
91086** Implementation of the printf() function.
91087*/
91088static void printfFunc(
91089  sqlite3_context *context,
91090  int argc,
91091  sqlite3_value **argv
91092){
91093  PrintfArguments x;
91094  StrAccum str;
91095  const char *zFormat;
91096  int n;
91097
91098  if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
91099    x.nArg = argc-1;
91100    x.nUsed = 0;
91101    x.apArg = argv+1;
91102    sqlite3StrAccumInit(&str, 0, 0, SQLITE_MAX_LENGTH);
91103    str.db = sqlite3_context_db_handle(context);
91104    sqlite3XPrintf(&str, SQLITE_PRINTF_SQLFUNC, zFormat, &x);
91105    n = str.nChar;
91106    sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
91107                        SQLITE_DYNAMIC);
91108  }
91109}
91110
91111/*
91112** Implementation of the substr() function.
91113**
91114** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
91115** p1 is 1-indexed.  So substr(x,1,1) returns the first character
91116** of x.  If x is text, then we actually count UTF-8 characters.
91117** If x is a blob, then we count bytes.
91118**
91119** If p1 is negative, then we begin abs(p1) from the end of x[].
91120**
91121** If p2 is negative, return the p2 characters preceding p1.
91122*/
91123static void substrFunc(
91124  sqlite3_context *context,
91125  int argc,
91126  sqlite3_value **argv
91127){
91128  const unsigned char *z;
91129  const unsigned char *z2;
91130  int len;
91131  int p0type;
91132  i64 p1, p2;
91133  int negP2 = 0;
91134
91135  assert( argc==3 || argc==2 );
91136  if( sqlite3_value_type(argv[1])==SQLITE_NULL
91137   || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
91138  ){
91139    return;
91140  }
91141  p0type = sqlite3_value_type(argv[0]);
91142  p1 = sqlite3_value_int(argv[1]);
91143  if( p0type==SQLITE_BLOB ){
91144    len = sqlite3_value_bytes(argv[0]);
91145    z = sqlite3_value_blob(argv[0]);
91146    if( z==0 ) return;
91147    assert( len==sqlite3_value_bytes(argv[0]) );
91148  }else{
91149    z = sqlite3_value_text(argv[0]);
91150    if( z==0 ) return;
91151    len = 0;
91152    if( p1<0 ){
91153      for(z2=z; *z2; len++){
91154        SQLITE_SKIP_UTF8(z2);
91155      }
91156    }
91157  }
91158  if( argc==3 ){
91159    p2 = sqlite3_value_int(argv[2]);
91160    if( p2<0 ){
91161      p2 = -p2;
91162      negP2 = 1;
91163    }
91164  }else{
91165    p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
91166  }
91167  if( p1<0 ){
91168    p1 += len;
91169    if( p1<0 ){
91170      p2 += p1;
91171      if( p2<0 ) p2 = 0;
91172      p1 = 0;
91173    }
91174  }else if( p1>0 ){
91175    p1--;
91176  }else if( p2>0 ){
91177    p2--;
91178  }
91179  if( negP2 ){
91180    p1 -= p2;
91181    if( p1<0 ){
91182      p2 += p1;
91183      p1 = 0;
91184    }
91185  }
91186  assert( p1>=0 && p2>=0 );
91187  if( p0type!=SQLITE_BLOB ){
91188    while( *z && p1 ){
91189      SQLITE_SKIP_UTF8(z);
91190      p1--;
91191    }
91192    for(z2=z; *z2 && p2; p2--){
91193      SQLITE_SKIP_UTF8(z2);
91194    }
91195    sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
91196  }else{
91197    if( p1+p2>len ){
91198      p2 = len-p1;
91199      if( p2<0 ) p2 = 0;
91200    }
91201    sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
91202  }
91203}
91204
91205/*
91206** Implementation of the round() function
91207*/
91208#ifndef SQLITE_OMIT_FLOATING_POINT
91209static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
91210  int n = 0;
91211  double r;
91212  char *zBuf;
91213  assert( argc==1 || argc==2 );
91214  if( argc==2 ){
91215    if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
91216    n = sqlite3_value_int(argv[1]);
91217    if( n>30 ) n = 30;
91218    if( n<0 ) n = 0;
91219  }
91220  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
91221  r = sqlite3_value_double(argv[0]);
91222  /* If Y==0 and X will fit in a 64-bit int,
91223  ** handle the rounding directly,
91224  ** otherwise use printf.
91225  */
91226  if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
91227    r = (double)((sqlite_int64)(r+0.5));
91228  }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
91229    r = -(double)((sqlite_int64)((-r)+0.5));
91230  }else{
91231    zBuf = sqlite3_mprintf("%.*f",n,r);
91232    if( zBuf==0 ){
91233      sqlite3_result_error_nomem(context);
91234      return;
91235    }
91236    sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
91237    sqlite3_free(zBuf);
91238  }
91239  sqlite3_result_double(context, r);
91240}
91241#endif
91242
91243/*
91244** Allocate nByte bytes of space using sqlite3_malloc(). If the
91245** allocation fails, call sqlite3_result_error_nomem() to notify
91246** the database handle that malloc() has failed and return NULL.
91247** If nByte is larger than the maximum string or blob length, then
91248** raise an SQLITE_TOOBIG exception and return NULL.
91249*/
91250static void *contextMalloc(sqlite3_context *context, i64 nByte){
91251  char *z;
91252  sqlite3 *db = sqlite3_context_db_handle(context);
91253  assert( nByte>0 );
91254  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
91255  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
91256  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
91257    sqlite3_result_error_toobig(context);
91258    z = 0;
91259  }else{
91260    z = sqlite3Malloc((int)nByte);
91261    if( !z ){
91262      sqlite3_result_error_nomem(context);
91263    }
91264  }
91265  return z;
91266}
91267
91268/*
91269** Implementation of the upper() and lower() SQL functions.
91270*/
91271static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
91272  char *z1;
91273  const char *z2;
91274  int i, n;
91275  UNUSED_PARAMETER(argc);
91276  z2 = (char*)sqlite3_value_text(argv[0]);
91277  n = sqlite3_value_bytes(argv[0]);
91278  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
91279  assert( z2==(char*)sqlite3_value_text(argv[0]) );
91280  if( z2 ){
91281    z1 = contextMalloc(context, ((i64)n)+1);
91282    if( z1 ){
91283      for(i=0; i<n; i++){
91284        z1[i] = (char)sqlite3Toupper(z2[i]);
91285      }
91286      sqlite3_result_text(context, z1, n, sqlite3_free);
91287    }
91288  }
91289}
91290static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
91291  char *z1;
91292  const char *z2;
91293  int i, n;
91294  UNUSED_PARAMETER(argc);
91295  z2 = (char*)sqlite3_value_text(argv[0]);
91296  n = sqlite3_value_bytes(argv[0]);
91297  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
91298  assert( z2==(char*)sqlite3_value_text(argv[0]) );
91299  if( z2 ){
91300    z1 = contextMalloc(context, ((i64)n)+1);
91301    if( z1 ){
91302      for(i=0; i<n; i++){
91303        z1[i] = sqlite3Tolower(z2[i]);
91304      }
91305      sqlite3_result_text(context, z1, n, sqlite3_free);
91306    }
91307  }
91308}
91309
91310/*
91311** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
91312** as VDBE code so that unused argument values do not have to be computed.
91313** However, we still need some kind of function implementation for this
91314** routines in the function table.  The noopFunc macro provides this.
91315** noopFunc will never be called so it doesn't matter what the implementation
91316** is.  We might as well use the "version()" function as a substitute.
91317*/
91318#define noopFunc versionFunc   /* Substitute function - never called */
91319
91320/*
91321** Implementation of random().  Return a random integer.
91322*/
91323static void randomFunc(
91324  sqlite3_context *context,
91325  int NotUsed,
91326  sqlite3_value **NotUsed2
91327){
91328  sqlite_int64 r;
91329  UNUSED_PARAMETER2(NotUsed, NotUsed2);
91330  sqlite3_randomness(sizeof(r), &r);
91331  if( r<0 ){
91332    /* We need to prevent a random number of 0x8000000000000000
91333    ** (or -9223372036854775808) since when you do abs() of that
91334    ** number of you get the same value back again.  To do this
91335    ** in a way that is testable, mask the sign bit off of negative
91336    ** values, resulting in a positive value.  Then take the
91337    ** 2s complement of that positive value.  The end result can
91338    ** therefore be no less than -9223372036854775807.
91339    */
91340    r = -(r & LARGEST_INT64);
91341  }
91342  sqlite3_result_int64(context, r);
91343}
91344
91345/*
91346** Implementation of randomblob(N).  Return a random blob
91347** that is N bytes long.
91348*/
91349static void randomBlob(
91350  sqlite3_context *context,
91351  int argc,
91352  sqlite3_value **argv
91353){
91354  int n;
91355  unsigned char *p;
91356  assert( argc==1 );
91357  UNUSED_PARAMETER(argc);
91358  n = sqlite3_value_int(argv[0]);
91359  if( n<1 ){
91360    n = 1;
91361  }
91362  p = contextMalloc(context, n);
91363  if( p ){
91364    sqlite3_randomness(n, p);
91365    sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
91366  }
91367}
91368
91369/*
91370** Implementation of the last_insert_rowid() SQL function.  The return
91371** value is the same as the sqlite3_last_insert_rowid() API function.
91372*/
91373static void last_insert_rowid(
91374  sqlite3_context *context,
91375  int NotUsed,
91376  sqlite3_value **NotUsed2
91377){
91378  sqlite3 *db = sqlite3_context_db_handle(context);
91379  UNUSED_PARAMETER2(NotUsed, NotUsed2);
91380  /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
91381  ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
91382  ** function. */
91383  sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
91384}
91385
91386/*
91387** Implementation of the changes() SQL function.
91388**
91389** IMP: R-62073-11209 The changes() SQL function is a wrapper
91390** around the sqlite3_changes() C/C++ function and hence follows the same
91391** rules for counting changes.
91392*/
91393static void changes(
91394  sqlite3_context *context,
91395  int NotUsed,
91396  sqlite3_value **NotUsed2
91397){
91398  sqlite3 *db = sqlite3_context_db_handle(context);
91399  UNUSED_PARAMETER2(NotUsed, NotUsed2);
91400  sqlite3_result_int(context, sqlite3_changes(db));
91401}
91402
91403/*
91404** Implementation of the total_changes() SQL function.  The return value is
91405** the same as the sqlite3_total_changes() API function.
91406*/
91407static void total_changes(
91408  sqlite3_context *context,
91409  int NotUsed,
91410  sqlite3_value **NotUsed2
91411){
91412  sqlite3 *db = sqlite3_context_db_handle(context);
91413  UNUSED_PARAMETER2(NotUsed, NotUsed2);
91414  /* IMP: R-52756-41993 This function is a wrapper around the
91415  ** sqlite3_total_changes() C/C++ interface. */
91416  sqlite3_result_int(context, sqlite3_total_changes(db));
91417}
91418
91419/*
91420** A structure defining how to do GLOB-style comparisons.
91421*/
91422struct compareInfo {
91423  u8 matchAll;
91424  u8 matchOne;
91425  u8 matchSet;
91426  u8 noCase;
91427};
91428
91429/*
91430** For LIKE and GLOB matching on EBCDIC machines, assume that every
91431** character is exactly one byte in size.  Also, all characters are
91432** able to participate in upper-case-to-lower-case mappings in EBCDIC
91433** whereas only characters less than 0x80 do in ASCII.
91434*/
91435#if defined(SQLITE_EBCDIC)
91436# define sqlite3Utf8Read(A)    (*((*A)++))
91437# define GlobUpperToLower(A)   A = sqlite3UpperToLower[A]
91438#else
91439# define GlobUpperToLower(A)   if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
91440#endif
91441
91442static const struct compareInfo globInfo = { '*', '?', '[', 0 };
91443/* The correct SQL-92 behavior is for the LIKE operator to ignore
91444** case.  Thus  'a' LIKE 'A' would be true. */
91445static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
91446/* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
91447** is case sensitive causing 'a' LIKE 'A' to be false */
91448static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
91449
91450/*
91451** Compare two UTF-8 strings for equality where the first string can
91452** potentially be a "glob" expression.  Return true (1) if they
91453** are the same and false (0) if they are different.
91454**
91455** Globbing rules:
91456**
91457**      '*'       Matches any sequence of zero or more characters.
91458**
91459**      '?'       Matches exactly one character.
91460**
91461**     [...]      Matches one character from the enclosed list of
91462**                characters.
91463**
91464**     [^...]     Matches one character not in the enclosed list.
91465**
91466** With the [...] and [^...] matching, a ']' character can be included
91467** in the list by making it the first character after '[' or '^'.  A
91468** range of characters can be specified using '-'.  Example:
91469** "[a-z]" matches any single lower-case letter.  To match a '-', make
91470** it the last character in the list.
91471**
91472** This routine is usually quick, but can be N**2 in the worst case.
91473**
91474** Hints: to match '*' or '?', put them in "[]".  Like this:
91475**
91476**         abc[*]xyz        Matches "abc*xyz" only
91477*/
91478static int patternCompare(
91479  const u8 *zPattern,              /* The glob pattern */
91480  const u8 *zString,               /* The string to compare against the glob */
91481  const struct compareInfo *pInfo, /* Information about how to do the compare */
91482  u32 esc                          /* The escape character */
91483){
91484  u32 c, c2;
91485  int invert;
91486  int seen;
91487  u8 matchOne = pInfo->matchOne;
91488  u8 matchAll = pInfo->matchAll;
91489  u8 matchSet = pInfo->matchSet;
91490  u8 noCase = pInfo->noCase;
91491  int prevEscape = 0;     /* True if the previous character was 'escape' */
91492
91493  while( (c = sqlite3Utf8Read(&zPattern))!=0 ){
91494    if( c==matchAll && !prevEscape ){
91495      while( (c=sqlite3Utf8Read(&zPattern)) == matchAll
91496               || c == matchOne ){
91497        if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
91498          return 0;
91499        }
91500      }
91501      if( c==0 ){
91502        return 1;
91503      }else if( c==esc ){
91504        c = sqlite3Utf8Read(&zPattern);
91505        if( c==0 ){
91506          return 0;
91507        }
91508      }else if( c==matchSet ){
91509        assert( esc==0 );         /* This is GLOB, not LIKE */
91510        assert( matchSet<0x80 );  /* '[' is a single-byte character */
91511        while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
91512          SQLITE_SKIP_UTF8(zString);
91513        }
91514        return *zString!=0;
91515      }
91516      while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
91517        if( noCase ){
91518          GlobUpperToLower(c2);
91519          GlobUpperToLower(c);
91520          while( c2 != 0 && c2 != c ){
91521            c2 = sqlite3Utf8Read(&zString);
91522            GlobUpperToLower(c2);
91523          }
91524        }else{
91525          while( c2 != 0 && c2 != c ){
91526            c2 = sqlite3Utf8Read(&zString);
91527          }
91528        }
91529        if( c2==0 ) return 0;
91530        if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
91531      }
91532      return 0;
91533    }else if( c==matchOne && !prevEscape ){
91534      if( sqlite3Utf8Read(&zString)==0 ){
91535        return 0;
91536      }
91537    }else if( c==matchSet ){
91538      u32 prior_c = 0;
91539      assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
91540      seen = 0;
91541      invert = 0;
91542      c = sqlite3Utf8Read(&zString);
91543      if( c==0 ) return 0;
91544      c2 = sqlite3Utf8Read(&zPattern);
91545      if( c2=='^' ){
91546        invert = 1;
91547        c2 = sqlite3Utf8Read(&zPattern);
91548      }
91549      if( c2==']' ){
91550        if( c==']' ) seen = 1;
91551        c2 = sqlite3Utf8Read(&zPattern);
91552      }
91553      while( c2 && c2!=']' ){
91554        if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
91555          c2 = sqlite3Utf8Read(&zPattern);
91556          if( c>=prior_c && c<=c2 ) seen = 1;
91557          prior_c = 0;
91558        }else{
91559          if( c==c2 ){
91560            seen = 1;
91561          }
91562          prior_c = c2;
91563        }
91564        c2 = sqlite3Utf8Read(&zPattern);
91565      }
91566      if( c2==0 || (seen ^ invert)==0 ){
91567        return 0;
91568      }
91569    }else if( esc==c && !prevEscape ){
91570      prevEscape = 1;
91571    }else{
91572      c2 = sqlite3Utf8Read(&zString);
91573      if( noCase ){
91574        GlobUpperToLower(c);
91575        GlobUpperToLower(c2);
91576      }
91577      if( c!=c2 ){
91578        return 0;
91579      }
91580      prevEscape = 0;
91581    }
91582  }
91583  return *zString==0;
91584}
91585
91586/*
91587** The sqlite3_strglob() interface.
91588*/
91589SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
91590  return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, 0)==0;
91591}
91592
91593/*
91594** Count the number of times that the LIKE operator (or GLOB which is
91595** just a variation of LIKE) gets called.  This is used for testing
91596** only.
91597*/
91598#ifdef SQLITE_TEST
91599SQLITE_API int sqlite3_like_count = 0;
91600#endif
91601
91602
91603/*
91604** Implementation of the like() SQL function.  This function implements
91605** the build-in LIKE operator.  The first argument to the function is the
91606** pattern and the second argument is the string.  So, the SQL statements:
91607**
91608**       A LIKE B
91609**
91610** is implemented as like(B,A).
91611**
91612** This same function (with a different compareInfo structure) computes
91613** the GLOB operator.
91614*/
91615static void likeFunc(
91616  sqlite3_context *context,
91617  int argc,
91618  sqlite3_value **argv
91619){
91620  const unsigned char *zA, *zB;
91621  u32 escape = 0;
91622  int nPat;
91623  sqlite3 *db = sqlite3_context_db_handle(context);
91624
91625  zB = sqlite3_value_text(argv[0]);
91626  zA = sqlite3_value_text(argv[1]);
91627
91628  /* Limit the length of the LIKE or GLOB pattern to avoid problems
91629  ** of deep recursion and N*N behavior in patternCompare().
91630  */
91631  nPat = sqlite3_value_bytes(argv[0]);
91632  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
91633  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
91634  if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
91635    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
91636    return;
91637  }
91638  assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
91639
91640  if( argc==3 ){
91641    /* The escape character string must consist of a single UTF-8 character.
91642    ** Otherwise, return an error.
91643    */
91644    const unsigned char *zEsc = sqlite3_value_text(argv[2]);
91645    if( zEsc==0 ) return;
91646    if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
91647      sqlite3_result_error(context,
91648          "ESCAPE expression must be a single character", -1);
91649      return;
91650    }
91651    escape = sqlite3Utf8Read(&zEsc);
91652  }
91653  if( zA && zB ){
91654    struct compareInfo *pInfo = sqlite3_user_data(context);
91655#ifdef SQLITE_TEST
91656    sqlite3_like_count++;
91657#endif
91658
91659    sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
91660  }
91661}
91662
91663/*
91664** Implementation of the NULLIF(x,y) function.  The result is the first
91665** argument if the arguments are different.  The result is NULL if the
91666** arguments are equal to each other.
91667*/
91668static void nullifFunc(
91669  sqlite3_context *context,
91670  int NotUsed,
91671  sqlite3_value **argv
91672){
91673  CollSeq *pColl = sqlite3GetFuncCollSeq(context);
91674  UNUSED_PARAMETER(NotUsed);
91675  if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
91676    sqlite3_result_value(context, argv[0]);
91677  }
91678}
91679
91680/*
91681** Implementation of the sqlite_version() function.  The result is the version
91682** of the SQLite library that is running.
91683*/
91684static void versionFunc(
91685  sqlite3_context *context,
91686  int NotUsed,
91687  sqlite3_value **NotUsed2
91688){
91689  UNUSED_PARAMETER2(NotUsed, NotUsed2);
91690  /* IMP: R-48699-48617 This function is an SQL wrapper around the
91691  ** sqlite3_libversion() C-interface. */
91692  sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
91693}
91694
91695/*
91696** Implementation of the sqlite_source_id() function. The result is a string
91697** that identifies the particular version of the source code used to build
91698** SQLite.
91699*/
91700static void sourceidFunc(
91701  sqlite3_context *context,
91702  int NotUsed,
91703  sqlite3_value **NotUsed2
91704){
91705  UNUSED_PARAMETER2(NotUsed, NotUsed2);
91706  /* IMP: R-24470-31136 This function is an SQL wrapper around the
91707  ** sqlite3_sourceid() C interface. */
91708  sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
91709}
91710
91711/*
91712** Implementation of the sqlite_log() function.  This is a wrapper around
91713** sqlite3_log().  The return value is NULL.  The function exists purely for
91714** its side-effects.
91715*/
91716static void errlogFunc(
91717  sqlite3_context *context,
91718  int argc,
91719  sqlite3_value **argv
91720){
91721  UNUSED_PARAMETER(argc);
91722  UNUSED_PARAMETER(context);
91723  sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
91724}
91725
91726/*
91727** Implementation of the sqlite_compileoption_used() function.
91728** The result is an integer that identifies if the compiler option
91729** was used to build SQLite.
91730*/
91731#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
91732static void compileoptionusedFunc(
91733  sqlite3_context *context,
91734  int argc,
91735  sqlite3_value **argv
91736){
91737  const char *zOptName;
91738  assert( argc==1 );
91739  UNUSED_PARAMETER(argc);
91740  /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
91741  ** function is a wrapper around the sqlite3_compileoption_used() C/C++
91742  ** function.
91743  */
91744  if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
91745    sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
91746  }
91747}
91748#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
91749
91750/*
91751** Implementation of the sqlite_compileoption_get() function.
91752** The result is a string that identifies the compiler options
91753** used to build SQLite.
91754*/
91755#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
91756static void compileoptiongetFunc(
91757  sqlite3_context *context,
91758  int argc,
91759  sqlite3_value **argv
91760){
91761  int n;
91762  assert( argc==1 );
91763  UNUSED_PARAMETER(argc);
91764  /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
91765  ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
91766  */
91767  n = sqlite3_value_int(argv[0]);
91768  sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
91769}
91770#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
91771
91772/* Array for converting from half-bytes (nybbles) into ASCII hex
91773** digits. */
91774static const char hexdigits[] = {
91775  '0', '1', '2', '3', '4', '5', '6', '7',
91776  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
91777};
91778
91779/*
91780** Implementation of the QUOTE() function.  This function takes a single
91781** argument.  If the argument is numeric, the return value is the same as
91782** the argument.  If the argument is NULL, the return value is the string
91783** "NULL".  Otherwise, the argument is enclosed in single quotes with
91784** single-quote escapes.
91785*/
91786static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
91787  assert( argc==1 );
91788  UNUSED_PARAMETER(argc);
91789  switch( sqlite3_value_type(argv[0]) ){
91790    case SQLITE_FLOAT: {
91791      double r1, r2;
91792      char zBuf[50];
91793      r1 = sqlite3_value_double(argv[0]);
91794      sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
91795      sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
91796      if( r1!=r2 ){
91797        sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
91798      }
91799      sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
91800      break;
91801    }
91802    case SQLITE_INTEGER: {
91803      sqlite3_result_value(context, argv[0]);
91804      break;
91805    }
91806    case SQLITE_BLOB: {
91807      char *zText = 0;
91808      char const *zBlob = sqlite3_value_blob(argv[0]);
91809      int nBlob = sqlite3_value_bytes(argv[0]);
91810      assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
91811      zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
91812      if( zText ){
91813        int i;
91814        for(i=0; i<nBlob; i++){
91815          zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
91816          zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
91817        }
91818        zText[(nBlob*2)+2] = '\'';
91819        zText[(nBlob*2)+3] = '\0';
91820        zText[0] = 'X';
91821        zText[1] = '\'';
91822        sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
91823        sqlite3_free(zText);
91824      }
91825      break;
91826    }
91827    case SQLITE_TEXT: {
91828      int i,j;
91829      u64 n;
91830      const unsigned char *zArg = sqlite3_value_text(argv[0]);
91831      char *z;
91832
91833      if( zArg==0 ) return;
91834      for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
91835      z = contextMalloc(context, ((i64)i)+((i64)n)+3);
91836      if( z ){
91837        z[0] = '\'';
91838        for(i=0, j=1; zArg[i]; i++){
91839          z[j++] = zArg[i];
91840          if( zArg[i]=='\'' ){
91841            z[j++] = '\'';
91842          }
91843        }
91844        z[j++] = '\'';
91845        z[j] = 0;
91846        sqlite3_result_text(context, z, j, sqlite3_free);
91847      }
91848      break;
91849    }
91850    default: {
91851      assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
91852      sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
91853      break;
91854    }
91855  }
91856}
91857
91858/*
91859** The unicode() function.  Return the integer unicode code-point value
91860** for the first character of the input string.
91861*/
91862static void unicodeFunc(
91863  sqlite3_context *context,
91864  int argc,
91865  sqlite3_value **argv
91866){
91867  const unsigned char *z = sqlite3_value_text(argv[0]);
91868  (void)argc;
91869  if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
91870}
91871
91872/*
91873** The char() function takes zero or more arguments, each of which is
91874** an integer.  It constructs a string where each character of the string
91875** is the unicode character for the corresponding integer argument.
91876*/
91877static void charFunc(
91878  sqlite3_context *context,
91879  int argc,
91880  sqlite3_value **argv
91881){
91882  unsigned char *z, *zOut;
91883  int i;
91884  zOut = z = sqlite3_malloc( argc*4+1 );
91885  if( z==0 ){
91886    sqlite3_result_error_nomem(context);
91887    return;
91888  }
91889  for(i=0; i<argc; i++){
91890    sqlite3_int64 x;
91891    unsigned c;
91892    x = sqlite3_value_int64(argv[i]);
91893    if( x<0 || x>0x10ffff ) x = 0xfffd;
91894    c = (unsigned)(x & 0x1fffff);
91895    if( c<0x00080 ){
91896      *zOut++ = (u8)(c&0xFF);
91897    }else if( c<0x00800 ){
91898      *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
91899      *zOut++ = 0x80 + (u8)(c & 0x3F);
91900    }else if( c<0x10000 ){
91901      *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
91902      *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
91903      *zOut++ = 0x80 + (u8)(c & 0x3F);
91904    }else{
91905      *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
91906      *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
91907      *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
91908      *zOut++ = 0x80 + (u8)(c & 0x3F);
91909    }                                                    \
91910  }
91911  sqlite3_result_text(context, (char*)z, (int)(zOut-z), sqlite3_free);
91912}
91913
91914/*
91915** The hex() function.  Interpret the argument as a blob.  Return
91916** a hexadecimal rendering as text.
91917*/
91918static void hexFunc(
91919  sqlite3_context *context,
91920  int argc,
91921  sqlite3_value **argv
91922){
91923  int i, n;
91924  const unsigned char *pBlob;
91925  char *zHex, *z;
91926  assert( argc==1 );
91927  UNUSED_PARAMETER(argc);
91928  pBlob = sqlite3_value_blob(argv[0]);
91929  n = sqlite3_value_bytes(argv[0]);
91930  assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
91931  z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
91932  if( zHex ){
91933    for(i=0; i<n; i++, pBlob++){
91934      unsigned char c = *pBlob;
91935      *(z++) = hexdigits[(c>>4)&0xf];
91936      *(z++) = hexdigits[c&0xf];
91937    }
91938    *z = 0;
91939    sqlite3_result_text(context, zHex, n*2, sqlite3_free);
91940  }
91941}
91942
91943/*
91944** The zeroblob(N) function returns a zero-filled blob of size N bytes.
91945*/
91946static void zeroblobFunc(
91947  sqlite3_context *context,
91948  int argc,
91949  sqlite3_value **argv
91950){
91951  i64 n;
91952  sqlite3 *db = sqlite3_context_db_handle(context);
91953  assert( argc==1 );
91954  UNUSED_PARAMETER(argc);
91955  n = sqlite3_value_int64(argv[0]);
91956  testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
91957  testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
91958  if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
91959    sqlite3_result_error_toobig(context);
91960  }else{
91961    sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
91962  }
91963}
91964
91965/*
91966** The replace() function.  Three arguments are all strings: call
91967** them A, B, and C. The result is also a string which is derived
91968** from A by replacing every occurrence of B with C.  The match
91969** must be exact.  Collating sequences are not used.
91970*/
91971static void replaceFunc(
91972  sqlite3_context *context,
91973  int argc,
91974  sqlite3_value **argv
91975){
91976  const unsigned char *zStr;        /* The input string A */
91977  const unsigned char *zPattern;    /* The pattern string B */
91978  const unsigned char *zRep;        /* The replacement string C */
91979  unsigned char *zOut;              /* The output */
91980  int nStr;                /* Size of zStr */
91981  int nPattern;            /* Size of zPattern */
91982  int nRep;                /* Size of zRep */
91983  i64 nOut;                /* Maximum size of zOut */
91984  int loopLimit;           /* Last zStr[] that might match zPattern[] */
91985  int i, j;                /* Loop counters */
91986
91987  assert( argc==3 );
91988  UNUSED_PARAMETER(argc);
91989  zStr = sqlite3_value_text(argv[0]);
91990  if( zStr==0 ) return;
91991  nStr = sqlite3_value_bytes(argv[0]);
91992  assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
91993  zPattern = sqlite3_value_text(argv[1]);
91994  if( zPattern==0 ){
91995    assert( sqlite3_value_type(argv[1])==SQLITE_NULL
91996            || sqlite3_context_db_handle(context)->mallocFailed );
91997    return;
91998  }
91999  if( zPattern[0]==0 ){
92000    assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
92001    sqlite3_result_value(context, argv[0]);
92002    return;
92003  }
92004  nPattern = sqlite3_value_bytes(argv[1]);
92005  assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
92006  zRep = sqlite3_value_text(argv[2]);
92007  if( zRep==0 ) return;
92008  nRep = sqlite3_value_bytes(argv[2]);
92009  assert( zRep==sqlite3_value_text(argv[2]) );
92010  nOut = nStr + 1;
92011  assert( nOut<SQLITE_MAX_LENGTH );
92012  zOut = contextMalloc(context, (i64)nOut);
92013  if( zOut==0 ){
92014    return;
92015  }
92016  loopLimit = nStr - nPattern;
92017  for(i=j=0; i<=loopLimit; i++){
92018    if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
92019      zOut[j++] = zStr[i];
92020    }else{
92021      u8 *zOld;
92022      sqlite3 *db = sqlite3_context_db_handle(context);
92023      nOut += nRep - nPattern;
92024      testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
92025      testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
92026      if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
92027        sqlite3_result_error_toobig(context);
92028        sqlite3_free(zOut);
92029        return;
92030      }
92031      zOld = zOut;
92032      zOut = sqlite3_realloc(zOut, (int)nOut);
92033      if( zOut==0 ){
92034        sqlite3_result_error_nomem(context);
92035        sqlite3_free(zOld);
92036        return;
92037      }
92038      memcpy(&zOut[j], zRep, nRep);
92039      j += nRep;
92040      i += nPattern-1;
92041    }
92042  }
92043  assert( j+nStr-i+1==nOut );
92044  memcpy(&zOut[j], &zStr[i], nStr-i);
92045  j += nStr - i;
92046  assert( j<=nOut );
92047  zOut[j] = 0;
92048  sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
92049}
92050
92051/*
92052** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
92053** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
92054*/
92055static void trimFunc(
92056  sqlite3_context *context,
92057  int argc,
92058  sqlite3_value **argv
92059){
92060  const unsigned char *zIn;         /* Input string */
92061  const unsigned char *zCharSet;    /* Set of characters to trim */
92062  int nIn;                          /* Number of bytes in input */
92063  int flags;                        /* 1: trimleft  2: trimright  3: trim */
92064  int i;                            /* Loop counter */
92065  unsigned char *aLen = 0;          /* Length of each character in zCharSet */
92066  unsigned char **azChar = 0;       /* Individual characters in zCharSet */
92067  int nChar;                        /* Number of characters in zCharSet */
92068
92069  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
92070    return;
92071  }
92072  zIn = sqlite3_value_text(argv[0]);
92073  if( zIn==0 ) return;
92074  nIn = sqlite3_value_bytes(argv[0]);
92075  assert( zIn==sqlite3_value_text(argv[0]) );
92076  if( argc==1 ){
92077    static const unsigned char lenOne[] = { 1 };
92078    static unsigned char * const azOne[] = { (u8*)" " };
92079    nChar = 1;
92080    aLen = (u8*)lenOne;
92081    azChar = (unsigned char **)azOne;
92082    zCharSet = 0;
92083  }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
92084    return;
92085  }else{
92086    const unsigned char *z;
92087    for(z=zCharSet, nChar=0; *z; nChar++){
92088      SQLITE_SKIP_UTF8(z);
92089    }
92090    if( nChar>0 ){
92091      azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
92092      if( azChar==0 ){
92093        return;
92094      }
92095      aLen = (unsigned char*)&azChar[nChar];
92096      for(z=zCharSet, nChar=0; *z; nChar++){
92097        azChar[nChar] = (unsigned char *)z;
92098        SQLITE_SKIP_UTF8(z);
92099        aLen[nChar] = (u8)(z - azChar[nChar]);
92100      }
92101    }
92102  }
92103  if( nChar>0 ){
92104    flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
92105    if( flags & 1 ){
92106      while( nIn>0 ){
92107        int len = 0;
92108        for(i=0; i<nChar; i++){
92109          len = aLen[i];
92110          if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
92111        }
92112        if( i>=nChar ) break;
92113        zIn += len;
92114        nIn -= len;
92115      }
92116    }
92117    if( flags & 2 ){
92118      while( nIn>0 ){
92119        int len = 0;
92120        for(i=0; i<nChar; i++){
92121          len = aLen[i];
92122          if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
92123        }
92124        if( i>=nChar ) break;
92125        nIn -= len;
92126      }
92127    }
92128    if( zCharSet ){
92129      sqlite3_free(azChar);
92130    }
92131  }
92132  sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
92133}
92134
92135
92136/* IMP: R-25361-16150 This function is omitted from SQLite by default. It
92137** is only available if the SQLITE_SOUNDEX compile-time option is used
92138** when SQLite is built.
92139*/
92140#ifdef SQLITE_SOUNDEX
92141/*
92142** Compute the soundex encoding of a word.
92143**
92144** IMP: R-59782-00072 The soundex(X) function returns a string that is the
92145** soundex encoding of the string X.
92146*/
92147static void soundexFunc(
92148  sqlite3_context *context,
92149  int argc,
92150  sqlite3_value **argv
92151){
92152  char zResult[8];
92153  const u8 *zIn;
92154  int i, j;
92155  static const unsigned char iCode[] = {
92156    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
92157    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
92158    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
92159    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
92160    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
92161    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
92162    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
92163    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
92164  };
92165  assert( argc==1 );
92166  zIn = (u8*)sqlite3_value_text(argv[0]);
92167  if( zIn==0 ) zIn = (u8*)"";
92168  for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
92169  if( zIn[i] ){
92170    u8 prevcode = iCode[zIn[i]&0x7f];
92171    zResult[0] = sqlite3Toupper(zIn[i]);
92172    for(j=1; j<4 && zIn[i]; i++){
92173      int code = iCode[zIn[i]&0x7f];
92174      if( code>0 ){
92175        if( code!=prevcode ){
92176          prevcode = code;
92177          zResult[j++] = code + '0';
92178        }
92179      }else{
92180        prevcode = 0;
92181      }
92182    }
92183    while( j<4 ){
92184      zResult[j++] = '0';
92185    }
92186    zResult[j] = 0;
92187    sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
92188  }else{
92189    /* IMP: R-64894-50321 The string "?000" is returned if the argument
92190    ** is NULL or contains no ASCII alphabetic characters. */
92191    sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
92192  }
92193}
92194#endif /* SQLITE_SOUNDEX */
92195
92196#ifndef SQLITE_OMIT_LOAD_EXTENSION
92197/*
92198** A function that loads a shared-library extension then returns NULL.
92199*/
92200static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
92201  const char *zFile = (const char *)sqlite3_value_text(argv[0]);
92202  const char *zProc;
92203  sqlite3 *db = sqlite3_context_db_handle(context);
92204  char *zErrMsg = 0;
92205
92206  if( argc==2 ){
92207    zProc = (const char *)sqlite3_value_text(argv[1]);
92208  }else{
92209    zProc = 0;
92210  }
92211  if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
92212    sqlite3_result_error(context, zErrMsg, -1);
92213    sqlite3_free(zErrMsg);
92214  }
92215}
92216#endif
92217
92218
92219/*
92220** An instance of the following structure holds the context of a
92221** sum() or avg() aggregate computation.
92222*/
92223typedef struct SumCtx SumCtx;
92224struct SumCtx {
92225  double rSum;      /* Floating point sum */
92226  i64 iSum;         /* Integer sum */
92227  i64 cnt;          /* Number of elements summed */
92228  u8 overflow;      /* True if integer overflow seen */
92229  u8 approx;        /* True if non-integer value was input to the sum */
92230};
92231
92232/*
92233** Routines used to compute the sum, average, and total.
92234**
92235** The SUM() function follows the (broken) SQL standard which means
92236** that it returns NULL if it sums over no inputs.  TOTAL returns
92237** 0.0 in that case.  In addition, TOTAL always returns a float where
92238** SUM might return an integer if it never encounters a floating point
92239** value.  TOTAL never fails, but SUM might through an exception if
92240** it overflows an integer.
92241*/
92242static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
92243  SumCtx *p;
92244  int type;
92245  assert( argc==1 );
92246  UNUSED_PARAMETER(argc);
92247  p = sqlite3_aggregate_context(context, sizeof(*p));
92248  type = sqlite3_value_numeric_type(argv[0]);
92249  if( p && type!=SQLITE_NULL ){
92250    p->cnt++;
92251    if( type==SQLITE_INTEGER ){
92252      i64 v = sqlite3_value_int64(argv[0]);
92253      p->rSum += v;
92254      if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
92255        p->overflow = 1;
92256      }
92257    }else{
92258      p->rSum += sqlite3_value_double(argv[0]);
92259      p->approx = 1;
92260    }
92261  }
92262}
92263static void sumFinalize(sqlite3_context *context){
92264  SumCtx *p;
92265  p = sqlite3_aggregate_context(context, 0);
92266  if( p && p->cnt>0 ){
92267    if( p->overflow ){
92268      sqlite3_result_error(context,"integer overflow",-1);
92269    }else if( p->approx ){
92270      sqlite3_result_double(context, p->rSum);
92271    }else{
92272      sqlite3_result_int64(context, p->iSum);
92273    }
92274  }
92275}
92276static void avgFinalize(sqlite3_context *context){
92277  SumCtx *p;
92278  p = sqlite3_aggregate_context(context, 0);
92279  if( p && p->cnt>0 ){
92280    sqlite3_result_double(context, p->rSum/(double)p->cnt);
92281  }
92282}
92283static void totalFinalize(sqlite3_context *context){
92284  SumCtx *p;
92285  p = sqlite3_aggregate_context(context, 0);
92286  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
92287  sqlite3_result_double(context, p ? p->rSum : (double)0);
92288}
92289
92290/*
92291** The following structure keeps track of state information for the
92292** count() aggregate function.
92293*/
92294typedef struct CountCtx CountCtx;
92295struct CountCtx {
92296  i64 n;
92297};
92298
92299/*
92300** Routines to implement the count() aggregate function.
92301*/
92302static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
92303  CountCtx *p;
92304  p = sqlite3_aggregate_context(context, sizeof(*p));
92305  if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
92306    p->n++;
92307  }
92308
92309#ifndef SQLITE_OMIT_DEPRECATED
92310  /* The sqlite3_aggregate_count() function is deprecated.  But just to make
92311  ** sure it still operates correctly, verify that its count agrees with our
92312  ** internal count when using count(*) and when the total count can be
92313  ** expressed as a 32-bit integer. */
92314  assert( argc==1 || p==0 || p->n>0x7fffffff
92315          || p->n==sqlite3_aggregate_count(context) );
92316#endif
92317}
92318static void countFinalize(sqlite3_context *context){
92319  CountCtx *p;
92320  p = sqlite3_aggregate_context(context, 0);
92321  sqlite3_result_int64(context, p ? p->n : 0);
92322}
92323
92324/*
92325** Routines to implement min() and max() aggregate functions.
92326*/
92327static void minmaxStep(
92328  sqlite3_context *context,
92329  int NotUsed,
92330  sqlite3_value **argv
92331){
92332  Mem *pArg  = (Mem *)argv[0];
92333  Mem *pBest;
92334  UNUSED_PARAMETER(NotUsed);
92335
92336  pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
92337  if( !pBest ) return;
92338
92339  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
92340    if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
92341  }else if( pBest->flags ){
92342    int max;
92343    int cmp;
92344    CollSeq *pColl = sqlite3GetFuncCollSeq(context);
92345    /* This step function is used for both the min() and max() aggregates,
92346    ** the only difference between the two being that the sense of the
92347    ** comparison is inverted. For the max() aggregate, the
92348    ** sqlite3_user_data() function returns (void *)-1. For min() it
92349    ** returns (void *)db, where db is the sqlite3* database pointer.
92350    ** Therefore the next statement sets variable 'max' to 1 for the max()
92351    ** aggregate, or 0 for min().
92352    */
92353    max = sqlite3_user_data(context)!=0;
92354    cmp = sqlite3MemCompare(pBest, pArg, pColl);
92355    if( (max && cmp<0) || (!max && cmp>0) ){
92356      sqlite3VdbeMemCopy(pBest, pArg);
92357    }else{
92358      sqlite3SkipAccumulatorLoad(context);
92359    }
92360  }else{
92361    sqlite3VdbeMemCopy(pBest, pArg);
92362  }
92363}
92364static void minMaxFinalize(sqlite3_context *context){
92365  sqlite3_value *pRes;
92366  pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
92367  if( pRes ){
92368    if( pRes->flags ){
92369      sqlite3_result_value(context, pRes);
92370    }
92371    sqlite3VdbeMemRelease(pRes);
92372  }
92373}
92374
92375/*
92376** group_concat(EXPR, ?SEPARATOR?)
92377*/
92378static void groupConcatStep(
92379  sqlite3_context *context,
92380  int argc,
92381  sqlite3_value **argv
92382){
92383  const char *zVal;
92384  StrAccum *pAccum;
92385  const char *zSep;
92386  int nVal, nSep;
92387  assert( argc==1 || argc==2 );
92388  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
92389  pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
92390
92391  if( pAccum ){
92392    sqlite3 *db = sqlite3_context_db_handle(context);
92393    int firstTerm = pAccum->useMalloc==0;
92394    pAccum->useMalloc = 2;
92395    pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
92396    if( !firstTerm ){
92397      if( argc==2 ){
92398        zSep = (char*)sqlite3_value_text(argv[1]);
92399        nSep = sqlite3_value_bytes(argv[1]);
92400      }else{
92401        zSep = ",";
92402        nSep = 1;
92403      }
92404      if( nSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
92405    }
92406    zVal = (char*)sqlite3_value_text(argv[0]);
92407    nVal = sqlite3_value_bytes(argv[0]);
92408    if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
92409  }
92410}
92411static void groupConcatFinalize(sqlite3_context *context){
92412  StrAccum *pAccum;
92413  pAccum = sqlite3_aggregate_context(context, 0);
92414  if( pAccum ){
92415    if( pAccum->accError==STRACCUM_TOOBIG ){
92416      sqlite3_result_error_toobig(context);
92417    }else if( pAccum->accError==STRACCUM_NOMEM ){
92418      sqlite3_result_error_nomem(context);
92419    }else{
92420      sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
92421                          sqlite3_free);
92422    }
92423  }
92424}
92425
92426/*
92427** This routine does per-connection function registration.  Most
92428** of the built-in functions above are part of the global function set.
92429** This routine only deals with those that are not global.
92430*/
92431SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
92432  int rc = sqlite3_overload_function(db, "MATCH", 2);
92433  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
92434  if( rc==SQLITE_NOMEM ){
92435    db->mallocFailed = 1;
92436  }
92437}
92438
92439/*
92440** Set the LIKEOPT flag on the 2-argument function with the given name.
92441*/
92442static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
92443  FuncDef *pDef;
92444  pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
92445                             2, SQLITE_UTF8, 0);
92446  if( ALWAYS(pDef) ){
92447    pDef->funcFlags |= flagVal;
92448  }
92449}
92450
92451/*
92452** Register the built-in LIKE and GLOB functions.  The caseSensitive
92453** parameter determines whether or not the LIKE operator is case
92454** sensitive.  GLOB is always case sensitive.
92455*/
92456SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
92457  struct compareInfo *pInfo;
92458  if( caseSensitive ){
92459    pInfo = (struct compareInfo*)&likeInfoAlt;
92460  }else{
92461    pInfo = (struct compareInfo*)&likeInfoNorm;
92462  }
92463  sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
92464  sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
92465  sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
92466      (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
92467  setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
92468  setLikeOptFlag(db, "like",
92469      caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
92470}
92471
92472/*
92473** pExpr points to an expression which implements a function.  If
92474** it is appropriate to apply the LIKE optimization to that function
92475** then set aWc[0] through aWc[2] to the wildcard characters and
92476** return TRUE.  If the function is not a LIKE-style function then
92477** return FALSE.
92478*/
92479SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
92480  FuncDef *pDef;
92481  if( pExpr->op!=TK_FUNCTION
92482   || !pExpr->x.pList
92483   || pExpr->x.pList->nExpr!=2
92484  ){
92485    return 0;
92486  }
92487  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
92488  pDef = sqlite3FindFunction(db, pExpr->u.zToken,
92489                             sqlite3Strlen30(pExpr->u.zToken),
92490                             2, SQLITE_UTF8, 0);
92491  if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
92492    return 0;
92493  }
92494
92495  /* The memcpy() statement assumes that the wildcard characters are
92496  ** the first three statements in the compareInfo structure.  The
92497  ** asserts() that follow verify that assumption
92498  */
92499  memcpy(aWc, pDef->pUserData, 3);
92500  assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
92501  assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
92502  assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
92503  *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
92504  return 1;
92505}
92506
92507/*
92508** All all of the FuncDef structures in the aBuiltinFunc[] array above
92509** to the global function hash table.  This occurs at start-time (as
92510** a consequence of calling sqlite3_initialize()).
92511**
92512** After this routine runs
92513*/
92514SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
92515  /*
92516  ** The following array holds FuncDef structures for all of the functions
92517  ** defined in this file.
92518  **
92519  ** The array cannot be constant since changes are made to the
92520  ** FuncDef.pHash elements at start-time.  The elements of this array
92521  ** are read-only after initialization is complete.
92522  */
92523  static SQLITE_WSD FuncDef aBuiltinFunc[] = {
92524    FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
92525    FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
92526    FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
92527    FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
92528    FUNCTION(trim,               1, 3, 0, trimFunc         ),
92529    FUNCTION(trim,               2, 3, 0, trimFunc         ),
92530    FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
92531    FUNCTION(min,                0, 0, 1, 0                ),
92532    AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
92533    FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
92534    FUNCTION(max,                0, 1, 1, 0                ),
92535    AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
92536    FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
92537    FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
92538    FUNCTION(instr,              2, 0, 0, instrFunc        ),
92539    FUNCTION(substr,             2, 0, 0, substrFunc       ),
92540    FUNCTION(substr,             3, 0, 0, substrFunc       ),
92541    FUNCTION(printf,            -1, 0, 0, printfFunc       ),
92542    FUNCTION(unicode,            1, 0, 0, unicodeFunc      ),
92543    FUNCTION(char,              -1, 0, 0, charFunc         ),
92544    FUNCTION(abs,                1, 0, 0, absFunc          ),
92545#ifndef SQLITE_OMIT_FLOATING_POINT
92546    FUNCTION(round,              1, 0, 0, roundFunc        ),
92547    FUNCTION(round,              2, 0, 0, roundFunc        ),
92548#endif
92549    FUNCTION(upper,              1, 0, 0, upperFunc        ),
92550    FUNCTION(lower,              1, 0, 0, lowerFunc        ),
92551    FUNCTION(coalesce,           1, 0, 0, 0                ),
92552    FUNCTION(coalesce,           0, 0, 0, 0                ),
92553    FUNCTION2(coalesce,         -1, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
92554    FUNCTION(hex,                1, 0, 0, hexFunc          ),
92555    FUNCTION2(ifnull,            2, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
92556    FUNCTION2(unlikely,          1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
92557    FUNCTION2(likelihood,        2, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
92558    VFUNCTION(random,            0, 0, 0, randomFunc       ),
92559    VFUNCTION(randomblob,        1, 0, 0, randomBlob       ),
92560    FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
92561    FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
92562    FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
92563    FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
92564#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
92565    FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
92566    FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
92567#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
92568    FUNCTION(quote,              1, 0, 0, quoteFunc        ),
92569    VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
92570    VFUNCTION(changes,           0, 0, 0, changes          ),
92571    VFUNCTION(total_changes,     0, 0, 0, total_changes    ),
92572    FUNCTION(replace,            3, 0, 0, replaceFunc      ),
92573    FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
92574  #ifdef SQLITE_SOUNDEX
92575    FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
92576  #endif
92577  #ifndef SQLITE_OMIT_LOAD_EXTENSION
92578    FUNCTION(load_extension,     1, 0, 0, loadExt          ),
92579    FUNCTION(load_extension,     2, 0, 0, loadExt          ),
92580  #endif
92581    AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
92582    AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
92583    AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
92584 /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
92585    {0,SQLITE_UTF8|SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
92586    AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
92587    AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
92588    AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
92589
92590    LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
92591  #ifdef SQLITE_CASE_SENSITIVE_LIKE
92592    LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
92593    LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
92594  #else
92595    LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
92596    LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
92597  #endif
92598  };
92599
92600  int i;
92601  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
92602  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
92603
92604  for(i=0; i<ArraySize(aBuiltinFunc); i++){
92605    sqlite3FuncDefInsert(pHash, &aFunc[i]);
92606  }
92607  sqlite3RegisterDateTimeFunctions();
92608#ifndef SQLITE_OMIT_ALTERTABLE
92609  sqlite3AlterFunctions();
92610#endif
92611#if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
92612  sqlite3AnalyzeFunctions();
92613#endif
92614}
92615
92616/************** End of func.c ************************************************/
92617/************** Begin file fkey.c ********************************************/
92618/*
92619**
92620** The author disclaims copyright to this source code.  In place of
92621** a legal notice, here is a blessing:
92622**
92623**    May you do good and not evil.
92624**    May you find forgiveness for yourself and forgive others.
92625**    May you share freely, never taking more than you give.
92626**
92627*************************************************************************
92628** This file contains code used by the compiler to add foreign key
92629** support to compiled SQL statements.
92630*/
92631
92632#ifndef SQLITE_OMIT_FOREIGN_KEY
92633#ifndef SQLITE_OMIT_TRIGGER
92634
92635/*
92636** Deferred and Immediate FKs
92637** --------------------------
92638**
92639** Foreign keys in SQLite come in two flavours: deferred and immediate.
92640** If an immediate foreign key constraint is violated,
92641** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
92642** statement transaction rolled back. If a
92643** deferred foreign key constraint is violated, no action is taken
92644** immediately. However if the application attempts to commit the
92645** transaction before fixing the constraint violation, the attempt fails.
92646**
92647** Deferred constraints are implemented using a simple counter associated
92648** with the database handle. The counter is set to zero each time a
92649** database transaction is opened. Each time a statement is executed
92650** that causes a foreign key violation, the counter is incremented. Each
92651** time a statement is executed that removes an existing violation from
92652** the database, the counter is decremented. When the transaction is
92653** committed, the commit fails if the current value of the counter is
92654** greater than zero. This scheme has two big drawbacks:
92655**
92656**   * When a commit fails due to a deferred foreign key constraint,
92657**     there is no way to tell which foreign constraint is not satisfied,
92658**     or which row it is not satisfied for.
92659**
92660**   * If the database contains foreign key violations when the
92661**     transaction is opened, this may cause the mechanism to malfunction.
92662**
92663** Despite these problems, this approach is adopted as it seems simpler
92664** than the alternatives.
92665**
92666** INSERT operations:
92667**
92668**   I.1) For each FK for which the table is the child table, search
92669**        the parent table for a match. If none is found increment the
92670**        constraint counter.
92671**
92672**   I.2) For each FK for which the table is the parent table,
92673**        search the child table for rows that correspond to the new
92674**        row in the parent table. Decrement the counter for each row
92675**        found (as the constraint is now satisfied).
92676**
92677** DELETE operations:
92678**
92679**   D.1) For each FK for which the table is the child table,
92680**        search the parent table for a row that corresponds to the
92681**        deleted row in the child table. If such a row is not found,
92682**        decrement the counter.
92683**
92684**   D.2) For each FK for which the table is the parent table, search
92685**        the child table for rows that correspond to the deleted row
92686**        in the parent table. For each found increment the counter.
92687**
92688** UPDATE operations:
92689**
92690**   An UPDATE command requires that all 4 steps above are taken, but only
92691**   for FK constraints for which the affected columns are actually
92692**   modified (values must be compared at runtime).
92693**
92694** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
92695** This simplifies the implementation a bit.
92696**
92697** For the purposes of immediate FK constraints, the OR REPLACE conflict
92698** resolution is considered to delete rows before the new row is inserted.
92699** If a delete caused by OR REPLACE violates an FK constraint, an exception
92700** is thrown, even if the FK constraint would be satisfied after the new
92701** row is inserted.
92702**
92703** Immediate constraints are usually handled similarly. The only difference
92704** is that the counter used is stored as part of each individual statement
92705** object (struct Vdbe). If, after the statement has run, its immediate
92706** constraint counter is greater than zero,
92707** it returns SQLITE_CONSTRAINT_FOREIGNKEY
92708** and the statement transaction is rolled back. An exception is an INSERT
92709** statement that inserts a single row only (no triggers). In this case,
92710** instead of using a counter, an exception is thrown immediately if the
92711** INSERT violates a foreign key constraint. This is necessary as such
92712** an INSERT does not open a statement transaction.
92713**
92714** TODO: How should dropping a table be handled? How should renaming a
92715** table be handled?
92716**
92717**
92718** Query API Notes
92719** ---------------
92720**
92721** Before coding an UPDATE or DELETE row operation, the code-generator
92722** for those two operations needs to know whether or not the operation
92723** requires any FK processing and, if so, which columns of the original
92724** row are required by the FK processing VDBE code (i.e. if FKs were
92725** implemented using triggers, which of the old.* columns would be
92726** accessed). No information is required by the code-generator before
92727** coding an INSERT operation. The functions used by the UPDATE/DELETE
92728** generation code to query for this information are:
92729**
92730**   sqlite3FkRequired() - Test to see if FK processing is required.
92731**   sqlite3FkOldmask()  - Query for the set of required old.* columns.
92732**
92733**
92734** Externally accessible module functions
92735** --------------------------------------
92736**
92737**   sqlite3FkCheck()    - Check for foreign key violations.
92738**   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
92739**   sqlite3FkDelete()   - Delete an FKey structure.
92740*/
92741
92742/*
92743** VDBE Calling Convention
92744** -----------------------
92745**
92746** Example:
92747**
92748**   For the following INSERT statement:
92749**
92750**     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
92751**     INSERT INTO t1 VALUES(1, 2, 3.1);
92752**
92753**   Register (x):        2    (type integer)
92754**   Register (x+1):      1    (type integer)
92755**   Register (x+2):      NULL (type NULL)
92756**   Register (x+3):      3.1  (type real)
92757*/
92758
92759/*
92760** A foreign key constraint requires that the key columns in the parent
92761** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
92762** Given that pParent is the parent table for foreign key constraint pFKey,
92763** search the schema for a unique index on the parent key columns.
92764**
92765** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
92766** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
92767** is set to point to the unique index.
92768**
92769** If the parent key consists of a single column (the foreign key constraint
92770** is not a composite foreign key), output variable *paiCol is set to NULL.
92771** Otherwise, it is set to point to an allocated array of size N, where
92772** N is the number of columns in the parent key. The first element of the
92773** array is the index of the child table column that is mapped by the FK
92774** constraint to the parent table column stored in the left-most column
92775** of index *ppIdx. The second element of the array is the index of the
92776** child table column that corresponds to the second left-most column of
92777** *ppIdx, and so on.
92778**
92779** If the required index cannot be found, either because:
92780**
92781**   1) The named parent key columns do not exist, or
92782**
92783**   2) The named parent key columns do exist, but are not subject to a
92784**      UNIQUE or PRIMARY KEY constraint, or
92785**
92786**   3) No parent key columns were provided explicitly as part of the
92787**      foreign key definition, and the parent table does not have a
92788**      PRIMARY KEY, or
92789**
92790**   4) No parent key columns were provided explicitly as part of the
92791**      foreign key definition, and the PRIMARY KEY of the parent table
92792**      consists of a a different number of columns to the child key in
92793**      the child table.
92794**
92795** then non-zero is returned, and a "foreign key mismatch" error loaded
92796** into pParse. If an OOM error occurs, non-zero is returned and the
92797** pParse->db->mallocFailed flag is set.
92798*/
92799SQLITE_PRIVATE int sqlite3FkLocateIndex(
92800  Parse *pParse,                  /* Parse context to store any error in */
92801  Table *pParent,                 /* Parent table of FK constraint pFKey */
92802  FKey *pFKey,                    /* Foreign key to find index for */
92803  Index **ppIdx,                  /* OUT: Unique index on parent table */
92804  int **paiCol                    /* OUT: Map of index columns in pFKey */
92805){
92806  Index *pIdx = 0;                    /* Value to return via *ppIdx */
92807  int *aiCol = 0;                     /* Value to return via *paiCol */
92808  int nCol = pFKey->nCol;             /* Number of columns in parent key */
92809  char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
92810
92811  /* The caller is responsible for zeroing output parameters. */
92812  assert( ppIdx && *ppIdx==0 );
92813  assert( !paiCol || *paiCol==0 );
92814  assert( pParse );
92815
92816  /* If this is a non-composite (single column) foreign key, check if it
92817  ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
92818  ** and *paiCol set to zero and return early.
92819  **
92820  ** Otherwise, for a composite foreign key (more than one column), allocate
92821  ** space for the aiCol array (returned via output parameter *paiCol).
92822  ** Non-composite foreign keys do not require the aiCol array.
92823  */
92824  if( nCol==1 ){
92825    /* The FK maps to the IPK if any of the following are true:
92826    **
92827    **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
92828    **      mapped to the primary key of table pParent, or
92829    **   2) The FK is explicitly mapped to a column declared as INTEGER
92830    **      PRIMARY KEY.
92831    */
92832    if( pParent->iPKey>=0 ){
92833      if( !zKey ) return 0;
92834      if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
92835    }
92836  }else if( paiCol ){
92837    assert( nCol>1 );
92838    aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
92839    if( !aiCol ) return 1;
92840    *paiCol = aiCol;
92841  }
92842
92843  for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
92844    if( pIdx->nKeyCol==nCol && pIdx->onError!=OE_None ){
92845      /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
92846      ** of columns. If each indexed column corresponds to a foreign key
92847      ** column of pFKey, then this index is a winner.  */
92848
92849      if( zKey==0 ){
92850        /* If zKey is NULL, then this foreign key is implicitly mapped to
92851        ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
92852        ** identified by the test.  */
92853        if( IsPrimaryKeyIndex(pIdx) ){
92854          if( aiCol ){
92855            int i;
92856            for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
92857          }
92858          break;
92859        }
92860      }else{
92861        /* If zKey is non-NULL, then this foreign key was declared to
92862        ** map to an explicit list of columns in table pParent. Check if this
92863        ** index matches those columns. Also, check that the index uses
92864        ** the default collation sequences for each column. */
92865        int i, j;
92866        for(i=0; i<nCol; i++){
92867          i16 iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
92868          char *zDfltColl;                  /* Def. collation for column */
92869          char *zIdxCol;                    /* Name of indexed column */
92870
92871          /* If the index uses a collation sequence that is different from
92872          ** the default collation sequence for the column, this index is
92873          ** unusable. Bail out early in this case.  */
92874          zDfltColl = pParent->aCol[iCol].zColl;
92875          if( !zDfltColl ){
92876            zDfltColl = "BINARY";
92877          }
92878          if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
92879
92880          zIdxCol = pParent->aCol[iCol].zName;
92881          for(j=0; j<nCol; j++){
92882            if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
92883              if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
92884              break;
92885            }
92886          }
92887          if( j==nCol ) break;
92888        }
92889        if( i==nCol ) break;      /* pIdx is usable */
92890      }
92891    }
92892  }
92893
92894  if( !pIdx ){
92895    if( !pParse->disableTriggers ){
92896      sqlite3ErrorMsg(pParse,
92897           "foreign key mismatch - \"%w\" referencing \"%w\"",
92898           pFKey->pFrom->zName, pFKey->zTo);
92899    }
92900    sqlite3DbFree(pParse->db, aiCol);
92901    return 1;
92902  }
92903
92904  *ppIdx = pIdx;
92905  return 0;
92906}
92907
92908/*
92909** This function is called when a row is inserted into or deleted from the
92910** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
92911** on the child table of pFKey, this function is invoked twice for each row
92912** affected - once to "delete" the old row, and then again to "insert" the
92913** new row.
92914**
92915** Each time it is called, this function generates VDBE code to locate the
92916** row in the parent table that corresponds to the row being inserted into
92917** or deleted from the child table. If the parent row can be found, no
92918** special action is taken. Otherwise, if the parent row can *not* be
92919** found in the parent table:
92920**
92921**   Operation | FK type   | Action taken
92922**   --------------------------------------------------------------------------
92923**   INSERT      immediate   Increment the "immediate constraint counter".
92924**
92925**   DELETE      immediate   Decrement the "immediate constraint counter".
92926**
92927**   INSERT      deferred    Increment the "deferred constraint counter".
92928**
92929**   DELETE      deferred    Decrement the "deferred constraint counter".
92930**
92931** These operations are identified in the comment at the top of this file
92932** (fkey.c) as "I.1" and "D.1".
92933*/
92934static void fkLookupParent(
92935  Parse *pParse,        /* Parse context */
92936  int iDb,              /* Index of database housing pTab */
92937  Table *pTab,          /* Parent table of FK pFKey */
92938  Index *pIdx,          /* Unique index on parent key columns in pTab */
92939  FKey *pFKey,          /* Foreign key constraint */
92940  int *aiCol,           /* Map from parent key columns to child table columns */
92941  int regData,          /* Address of array containing child table row */
92942  int nIncr,            /* Increment constraint counter by this */
92943  int isIgnore          /* If true, pretend pTab contains all NULL values */
92944){
92945  int i;                                    /* Iterator variable */
92946  Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
92947  int iCur = pParse->nTab - 1;              /* Cursor number to use */
92948  int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
92949
92950  /* If nIncr is less than zero, then check at runtime if there are any
92951  ** outstanding constraints to resolve. If there are not, there is no need
92952  ** to check if deleting this row resolves any outstanding violations.
92953  **
92954  ** Check if any of the key columns in the child table row are NULL. If
92955  ** any are, then the constraint is considered satisfied. No need to
92956  ** search for a matching row in the parent table.  */
92957  if( nIncr<0 ){
92958    sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
92959    VdbeCoverage(v);
92960  }
92961  for(i=0; i<pFKey->nCol; i++){
92962    int iReg = aiCol[i] + regData + 1;
92963    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
92964  }
92965
92966  if( isIgnore==0 ){
92967    if( pIdx==0 ){
92968      /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
92969      ** column of the parent table (table pTab).  */
92970      int iMustBeInt;               /* Address of MustBeInt instruction */
92971      int regTemp = sqlite3GetTempReg(pParse);
92972
92973      /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
92974      ** apply the affinity of the parent key). If this fails, then there
92975      ** is no matching parent key. Before using MustBeInt, make a copy of
92976      ** the value. Otherwise, the value inserted into the child key column
92977      ** will have INTEGER affinity applied to it, which may not be correct.  */
92978      sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
92979      iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
92980      VdbeCoverage(v);
92981
92982      /* If the parent table is the same as the child table, and we are about
92983      ** to increment the constraint-counter (i.e. this is an INSERT operation),
92984      ** then check if the row being inserted matches itself. If so, do not
92985      ** increment the constraint-counter.  */
92986      if( pTab==pFKey->pFrom && nIncr==1 ){
92987        sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
92988        sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
92989      }
92990
92991      sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
92992      sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
92993      sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
92994      sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
92995      sqlite3VdbeJumpHere(v, iMustBeInt);
92996      sqlite3ReleaseTempReg(pParse, regTemp);
92997    }else{
92998      int nCol = pFKey->nCol;
92999      int regTemp = sqlite3GetTempRange(pParse, nCol);
93000      int regRec = sqlite3GetTempReg(pParse);
93001
93002      sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
93003      sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
93004      for(i=0; i<nCol; i++){
93005        sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
93006      }
93007
93008      /* If the parent table is the same as the child table, and we are about
93009      ** to increment the constraint-counter (i.e. this is an INSERT operation),
93010      ** then check if the row being inserted matches itself. If so, do not
93011      ** increment the constraint-counter.
93012      **
93013      ** If any of the parent-key values are NULL, then the row cannot match
93014      ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
93015      ** of the parent-key values are NULL (at this point it is known that
93016      ** none of the child key values are).
93017      */
93018      if( pTab==pFKey->pFrom && nIncr==1 ){
93019        int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
93020        for(i=0; i<nCol; i++){
93021          int iChild = aiCol[i]+1+regData;
93022          int iParent = pIdx->aiColumn[i]+1+regData;
93023          assert( aiCol[i]!=pTab->iPKey );
93024          if( pIdx->aiColumn[i]==pTab->iPKey ){
93025            /* The parent key is a composite key that includes the IPK column */
93026            iParent = regData;
93027          }
93028          sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
93029          sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
93030        }
93031        sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
93032      }
93033
93034      sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
93035                        sqlite3IndexAffinityStr(v,pIdx), nCol);
93036      sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
93037
93038      sqlite3ReleaseTempReg(pParse, regRec);
93039      sqlite3ReleaseTempRange(pParse, regTemp, nCol);
93040    }
93041  }
93042
93043  if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
93044   && !pParse->pToplevel
93045   && !pParse->isMultiWrite
93046  ){
93047    /* Special case: If this is an INSERT statement that will insert exactly
93048    ** one row into the table, raise a constraint immediately instead of
93049    ** incrementing a counter. This is necessary as the VM code is being
93050    ** generated for will not open a statement transaction.  */
93051    assert( nIncr==1 );
93052    sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
93053        OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
93054  }else{
93055    if( nIncr>0 && pFKey->isDeferred==0 ){
93056      sqlite3ParseToplevel(pParse)->mayAbort = 1;
93057    }
93058    sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
93059  }
93060
93061  sqlite3VdbeResolveLabel(v, iOk);
93062  sqlite3VdbeAddOp1(v, OP_Close, iCur);
93063}
93064
93065
93066/*
93067** Return an Expr object that refers to a memory register corresponding
93068** to column iCol of table pTab.
93069**
93070** regBase is the first of an array of register that contains the data
93071** for pTab.  regBase itself holds the rowid.  regBase+1 holds the first
93072** column.  regBase+2 holds the second column, and so forth.
93073*/
93074static Expr *exprTableRegister(
93075  Parse *pParse,     /* Parsing and code generating context */
93076  Table *pTab,       /* The table whose content is at r[regBase]... */
93077  int regBase,       /* Contents of table pTab */
93078  i16 iCol           /* Which column of pTab is desired */
93079){
93080  Expr *pExpr;
93081  Column *pCol;
93082  const char *zColl;
93083  sqlite3 *db = pParse->db;
93084
93085  pExpr = sqlite3Expr(db, TK_REGISTER, 0);
93086  if( pExpr ){
93087    if( iCol>=0 && iCol!=pTab->iPKey ){
93088      pCol = &pTab->aCol[iCol];
93089      pExpr->iTable = regBase + iCol + 1;
93090      pExpr->affinity = pCol->affinity;
93091      zColl = pCol->zColl;
93092      if( zColl==0 ) zColl = db->pDfltColl->zName;
93093      pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
93094    }else{
93095      pExpr->iTable = regBase;
93096      pExpr->affinity = SQLITE_AFF_INTEGER;
93097    }
93098  }
93099  return pExpr;
93100}
93101
93102/*
93103** Return an Expr object that refers to column iCol of table pTab which
93104** has cursor iCur.
93105*/
93106static Expr *exprTableColumn(
93107  sqlite3 *db,      /* The database connection */
93108  Table *pTab,      /* The table whose column is desired */
93109  int iCursor,      /* The open cursor on the table */
93110  i16 iCol          /* The column that is wanted */
93111){
93112  Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
93113  if( pExpr ){
93114    pExpr->pTab = pTab;
93115    pExpr->iTable = iCursor;
93116    pExpr->iColumn = iCol;
93117  }
93118  return pExpr;
93119}
93120
93121/*
93122** This function is called to generate code executed when a row is deleted
93123** from the parent table of foreign key constraint pFKey and, if pFKey is
93124** deferred, when a row is inserted into the same table. When generating
93125** code for an SQL UPDATE operation, this function may be called twice -
93126** once to "delete" the old row and once to "insert" the new row.
93127**
93128** The code generated by this function scans through the rows in the child
93129** table that correspond to the parent table row being deleted or inserted.
93130** For each child row found, one of the following actions is taken:
93131**
93132**   Operation | FK type   | Action taken
93133**   --------------------------------------------------------------------------
93134**   DELETE      immediate   Increment the "immediate constraint counter".
93135**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
93136**                           throw a "FOREIGN KEY constraint failed" exception.
93137**
93138**   INSERT      immediate   Decrement the "immediate constraint counter".
93139**
93140**   DELETE      deferred    Increment the "deferred constraint counter".
93141**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
93142**                           throw a "FOREIGN KEY constraint failed" exception.
93143**
93144**   INSERT      deferred    Decrement the "deferred constraint counter".
93145**
93146** These operations are identified in the comment at the top of this file
93147** (fkey.c) as "I.2" and "D.2".
93148*/
93149static void fkScanChildren(
93150  Parse *pParse,                  /* Parse context */
93151  SrcList *pSrc,                  /* The child table to be scanned */
93152  Table *pTab,                    /* The parent table */
93153  Index *pIdx,                    /* Index on parent covering the foreign key */
93154  FKey *pFKey,                    /* The foreign key linking pSrc to pTab */
93155  int *aiCol,                     /* Map from pIdx cols to child table cols */
93156  int regData,                    /* Parent row data starts here */
93157  int nIncr                       /* Amount to increment deferred counter by */
93158){
93159  sqlite3 *db = pParse->db;       /* Database handle */
93160  int i;                          /* Iterator variable */
93161  Expr *pWhere = 0;               /* WHERE clause to scan with */
93162  NameContext sNameContext;       /* Context used to resolve WHERE clause */
93163  WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
93164  int iFkIfZero = 0;              /* Address of OP_FkIfZero */
93165  Vdbe *v = sqlite3GetVdbe(pParse);
93166
93167  assert( pIdx==0 || pIdx->pTable==pTab );
93168  assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
93169  assert( pIdx!=0 || pFKey->nCol==1 );
93170  assert( pIdx!=0 || HasRowid(pTab) );
93171
93172  if( nIncr<0 ){
93173    iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
93174    VdbeCoverage(v);
93175  }
93176
93177  /* Create an Expr object representing an SQL expression like:
93178  **
93179  **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
93180  **
93181  ** The collation sequence used for the comparison should be that of
93182  ** the parent key columns. The affinity of the parent key column should
93183  ** be applied to each child key value before the comparison takes place.
93184  */
93185  for(i=0; i<pFKey->nCol; i++){
93186    Expr *pLeft;                  /* Value from parent table row */
93187    Expr *pRight;                 /* Column ref to child table */
93188    Expr *pEq;                    /* Expression (pLeft = pRight) */
93189    i16 iCol;                     /* Index of column in child table */
93190    const char *zCol;             /* Name of column in child table */
93191
93192    iCol = pIdx ? pIdx->aiColumn[i] : -1;
93193    pLeft = exprTableRegister(pParse, pTab, regData, iCol);
93194    iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
93195    assert( iCol>=0 );
93196    zCol = pFKey->pFrom->aCol[iCol].zName;
93197    pRight = sqlite3Expr(db, TK_ID, zCol);
93198    pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
93199    pWhere = sqlite3ExprAnd(db, pWhere, pEq);
93200  }
93201
93202  /* If the child table is the same as the parent table, then add terms
93203  ** to the WHERE clause that prevent this entry from being scanned.
93204  ** The added WHERE clause terms are like this:
93205  **
93206  **     $current_rowid!=rowid
93207  **     NOT( $current_a==a AND $current_b==b AND ... )
93208  **
93209  ** The first form is used for rowid tables.  The second form is used
93210  ** for WITHOUT ROWID tables.  In the second form, the primary key is
93211  ** (a,b,...)
93212  */
93213  if( pTab==pFKey->pFrom && nIncr>0 ){
93214    Expr *pNe;                    /* Expression (pLeft != pRight) */
93215    Expr *pLeft;                  /* Value from parent table row */
93216    Expr *pRight;                 /* Column ref to child table */
93217    if( HasRowid(pTab) ){
93218      pLeft = exprTableRegister(pParse, pTab, regData, -1);
93219      pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
93220      pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
93221    }else{
93222      Expr *pEq, *pAll = 0;
93223      Index *pPk = sqlite3PrimaryKeyIndex(pTab);
93224      assert( pIdx!=0 );
93225      for(i=0; i<pPk->nKeyCol; i++){
93226        i16 iCol = pIdx->aiColumn[i];
93227        pLeft = exprTableRegister(pParse, pTab, regData, iCol);
93228        pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
93229        pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
93230        pAll = sqlite3ExprAnd(db, pAll, pEq);
93231      }
93232      pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0, 0);
93233    }
93234    pWhere = sqlite3ExprAnd(db, pWhere, pNe);
93235  }
93236
93237  /* Resolve the references in the WHERE clause. */
93238  memset(&sNameContext, 0, sizeof(NameContext));
93239  sNameContext.pSrcList = pSrc;
93240  sNameContext.pParse = pParse;
93241  sqlite3ResolveExprNames(&sNameContext, pWhere);
93242
93243  /* Create VDBE to loop through the entries in pSrc that match the WHERE
93244  ** clause. If the constraint is not deferred, throw an exception for
93245  ** each row found. Otherwise, for deferred constraints, increment the
93246  ** deferred constraint counter by nIncr for each row selected.  */
93247  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
93248  if( nIncr>0 && pFKey->isDeferred==0 ){
93249    sqlite3ParseToplevel(pParse)->mayAbort = 1;
93250  }
93251  sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
93252  if( pWInfo ){
93253    sqlite3WhereEnd(pWInfo);
93254  }
93255
93256  /* Clean up the WHERE clause constructed above. */
93257  sqlite3ExprDelete(db, pWhere);
93258  if( iFkIfZero ){
93259    sqlite3VdbeJumpHere(v, iFkIfZero);
93260  }
93261}
93262
93263/*
93264** This function returns a linked list of FKey objects (connected by
93265** FKey.pNextTo) holding all children of table pTab.  For example,
93266** given the following schema:
93267**
93268**   CREATE TABLE t1(a PRIMARY KEY);
93269**   CREATE TABLE t2(b REFERENCES t1(a);
93270**
93271** Calling this function with table "t1" as an argument returns a pointer
93272** to the FKey structure representing the foreign key constraint on table
93273** "t2". Calling this function with "t2" as the argument would return a
93274** NULL pointer (as there are no FK constraints for which t2 is the parent
93275** table).
93276*/
93277SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
93278  int nName = sqlite3Strlen30(pTab->zName);
93279  return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
93280}
93281
93282/*
93283** The second argument is a Trigger structure allocated by the
93284** fkActionTrigger() routine. This function deletes the Trigger structure
93285** and all of its sub-components.
93286**
93287** The Trigger structure or any of its sub-components may be allocated from
93288** the lookaside buffer belonging to database handle dbMem.
93289*/
93290static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
93291  if( p ){
93292    TriggerStep *pStep = p->step_list;
93293    sqlite3ExprDelete(dbMem, pStep->pWhere);
93294    sqlite3ExprListDelete(dbMem, pStep->pExprList);
93295    sqlite3SelectDelete(dbMem, pStep->pSelect);
93296    sqlite3ExprDelete(dbMem, p->pWhen);
93297    sqlite3DbFree(dbMem, p);
93298  }
93299}
93300
93301/*
93302** This function is called to generate code that runs when table pTab is
93303** being dropped from the database. The SrcList passed as the second argument
93304** to this function contains a single entry guaranteed to resolve to
93305** table pTab.
93306**
93307** Normally, no code is required. However, if either
93308**
93309**   (a) The table is the parent table of a FK constraint, or
93310**   (b) The table is the child table of a deferred FK constraint and it is
93311**       determined at runtime that there are outstanding deferred FK
93312**       constraint violations in the database,
93313**
93314** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
93315** the table from the database. Triggers are disabled while running this
93316** DELETE, but foreign key actions are not.
93317*/
93318SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
93319  sqlite3 *db = pParse->db;
93320  if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
93321    int iSkip = 0;
93322    Vdbe *v = sqlite3GetVdbe(pParse);
93323
93324    assert( v );                  /* VDBE has already been allocated */
93325    if( sqlite3FkReferences(pTab)==0 ){
93326      /* Search for a deferred foreign key constraint for which this table
93327      ** is the child table. If one cannot be found, return without
93328      ** generating any VDBE code. If one can be found, then jump over
93329      ** the entire DELETE if there are no outstanding deferred constraints
93330      ** when this statement is run.  */
93331      FKey *p;
93332      for(p=pTab->pFKey; p; p=p->pNextFrom){
93333        if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
93334      }
93335      if( !p ) return;
93336      iSkip = sqlite3VdbeMakeLabel(v);
93337      sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
93338    }
93339
93340    pParse->disableTriggers = 1;
93341    sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
93342    pParse->disableTriggers = 0;
93343
93344    /* If the DELETE has generated immediate foreign key constraint
93345    ** violations, halt the VDBE and return an error at this point, before
93346    ** any modifications to the schema are made. This is because statement
93347    ** transactions are not able to rollback schema changes.
93348    **
93349    ** If the SQLITE_DeferFKs flag is set, then this is not required, as
93350    ** the statement transaction will not be rolled back even if FK
93351    ** constraints are violated.
93352    */
93353    if( (db->flags & SQLITE_DeferFKs)==0 ){
93354      sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
93355      VdbeCoverage(v);
93356      sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
93357          OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
93358    }
93359
93360    if( iSkip ){
93361      sqlite3VdbeResolveLabel(v, iSkip);
93362    }
93363  }
93364}
93365
93366
93367/*
93368** The second argument points to an FKey object representing a foreign key
93369** for which pTab is the child table. An UPDATE statement against pTab
93370** is currently being processed. For each column of the table that is
93371** actually updated, the corresponding element in the aChange[] array
93372** is zero or greater (if a column is unmodified the corresponding element
93373** is set to -1). If the rowid column is modified by the UPDATE statement
93374** the bChngRowid argument is non-zero.
93375**
93376** This function returns true if any of the columns that are part of the
93377** child key for FK constraint *p are modified.
93378*/
93379static int fkChildIsModified(
93380  Table *pTab,                    /* Table being updated */
93381  FKey *p,                        /* Foreign key for which pTab is the child */
93382  int *aChange,                   /* Array indicating modified columns */
93383  int bChngRowid                  /* True if rowid is modified by this update */
93384){
93385  int i;
93386  for(i=0; i<p->nCol; i++){
93387    int iChildKey = p->aCol[i].iFrom;
93388    if( aChange[iChildKey]>=0 ) return 1;
93389    if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
93390  }
93391  return 0;
93392}
93393
93394/*
93395** The second argument points to an FKey object representing a foreign key
93396** for which pTab is the parent table. An UPDATE statement against pTab
93397** is currently being processed. For each column of the table that is
93398** actually updated, the corresponding element in the aChange[] array
93399** is zero or greater (if a column is unmodified the corresponding element
93400** is set to -1). If the rowid column is modified by the UPDATE statement
93401** the bChngRowid argument is non-zero.
93402**
93403** This function returns true if any of the columns that are part of the
93404** parent key for FK constraint *p are modified.
93405*/
93406static int fkParentIsModified(
93407  Table *pTab,
93408  FKey *p,
93409  int *aChange,
93410  int bChngRowid
93411){
93412  int i;
93413  for(i=0; i<p->nCol; i++){
93414    char *zKey = p->aCol[i].zCol;
93415    int iKey;
93416    for(iKey=0; iKey<pTab->nCol; iKey++){
93417      if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
93418        Column *pCol = &pTab->aCol[iKey];
93419        if( zKey ){
93420          if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
93421        }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
93422          return 1;
93423        }
93424      }
93425    }
93426  }
93427  return 0;
93428}
93429
93430/*
93431** This function is called when inserting, deleting or updating a row of
93432** table pTab to generate VDBE code to perform foreign key constraint
93433** processing for the operation.
93434**
93435** For a DELETE operation, parameter regOld is passed the index of the
93436** first register in an array of (pTab->nCol+1) registers containing the
93437** rowid of the row being deleted, followed by each of the column values
93438** of the row being deleted, from left to right. Parameter regNew is passed
93439** zero in this case.
93440**
93441** For an INSERT operation, regOld is passed zero and regNew is passed the
93442** first register of an array of (pTab->nCol+1) registers containing the new
93443** row data.
93444**
93445** For an UPDATE operation, this function is called twice. Once before
93446** the original record is deleted from the table using the calling convention
93447** described for DELETE. Then again after the original record is deleted
93448** but before the new record is inserted using the INSERT convention.
93449*/
93450SQLITE_PRIVATE void sqlite3FkCheck(
93451  Parse *pParse,                  /* Parse context */
93452  Table *pTab,                    /* Row is being deleted from this table */
93453  int regOld,                     /* Previous row data is stored here */
93454  int regNew,                     /* New row data is stored here */
93455  int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
93456  int bChngRowid                  /* True if rowid is UPDATEd */
93457){
93458  sqlite3 *db = pParse->db;       /* Database handle */
93459  FKey *pFKey;                    /* Used to iterate through FKs */
93460  int iDb;                        /* Index of database containing pTab */
93461  const char *zDb;                /* Name of database containing pTab */
93462  int isIgnoreErrors = pParse->disableTriggers;
93463
93464  /* Exactly one of regOld and regNew should be non-zero. */
93465  assert( (regOld==0)!=(regNew==0) );
93466
93467  /* If foreign-keys are disabled, this function is a no-op. */
93468  if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
93469
93470  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
93471  zDb = db->aDb[iDb].zName;
93472
93473  /* Loop through all the foreign key constraints for which pTab is the
93474  ** child table (the table that the foreign key definition is part of).  */
93475  for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
93476    Table *pTo;                   /* Parent table of foreign key pFKey */
93477    Index *pIdx = 0;              /* Index on key columns in pTo */
93478    int *aiFree = 0;
93479    int *aiCol;
93480    int iCol;
93481    int i;
93482    int isIgnore = 0;
93483
93484    if( aChange
93485     && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
93486     && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
93487    ){
93488      continue;
93489    }
93490
93491    /* Find the parent table of this foreign key. Also find a unique index
93492    ** on the parent key columns in the parent table. If either of these
93493    ** schema items cannot be located, set an error in pParse and return
93494    ** early.  */
93495    if( pParse->disableTriggers ){
93496      pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
93497    }else{
93498      pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
93499    }
93500    if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
93501      assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
93502      if( !isIgnoreErrors || db->mallocFailed ) return;
93503      if( pTo==0 ){
93504        /* If isIgnoreErrors is true, then a table is being dropped. In this
93505        ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
93506        ** before actually dropping it in order to check FK constraints.
93507        ** If the parent table of an FK constraint on the current table is
93508        ** missing, behave as if it is empty. i.e. decrement the relevant
93509        ** FK counter for each row of the current table with non-NULL keys.
93510        */
93511        Vdbe *v = sqlite3GetVdbe(pParse);
93512        int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
93513        for(i=0; i<pFKey->nCol; i++){
93514          int iReg = pFKey->aCol[i].iFrom + regOld + 1;
93515          sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
93516        }
93517        sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
93518      }
93519      continue;
93520    }
93521    assert( pFKey->nCol==1 || (aiFree && pIdx) );
93522
93523    if( aiFree ){
93524      aiCol = aiFree;
93525    }else{
93526      iCol = pFKey->aCol[0].iFrom;
93527      aiCol = &iCol;
93528    }
93529    for(i=0; i<pFKey->nCol; i++){
93530      if( aiCol[i]==pTab->iPKey ){
93531        aiCol[i] = -1;
93532      }
93533#ifndef SQLITE_OMIT_AUTHORIZATION
93534      /* Request permission to read the parent key columns. If the
93535      ** authorization callback returns SQLITE_IGNORE, behave as if any
93536      ** values read from the parent table are NULL. */
93537      if( db->xAuth ){
93538        int rcauth;
93539        char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
93540        rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
93541        isIgnore = (rcauth==SQLITE_IGNORE);
93542      }
93543#endif
93544    }
93545
93546    /* Take a shared-cache advisory read-lock on the parent table. Allocate
93547    ** a cursor to use to search the unique index on the parent key columns
93548    ** in the parent table.  */
93549    sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
93550    pParse->nTab++;
93551
93552    if( regOld!=0 ){
93553      /* A row is being removed from the child table. Search for the parent.
93554      ** If the parent does not exist, removing the child row resolves an
93555      ** outstanding foreign key constraint violation. */
93556      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
93557    }
93558    if( regNew!=0 ){
93559      /* A row is being added to the child table. If a parent row cannot
93560      ** be found, adding the child row has violated the FK constraint. */
93561      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
93562    }
93563
93564    sqlite3DbFree(db, aiFree);
93565  }
93566
93567  /* Loop through all the foreign key constraints that refer to this table.
93568  ** (the "child" constraints) */
93569  for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
93570    Index *pIdx = 0;              /* Foreign key index for pFKey */
93571    SrcList *pSrc;
93572    int *aiCol = 0;
93573
93574    if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
93575      continue;
93576    }
93577
93578    if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
93579     && !pParse->pToplevel && !pParse->isMultiWrite
93580    ){
93581      assert( regOld==0 && regNew!=0 );
93582      /* Inserting a single row into a parent table cannot cause an immediate
93583      ** foreign key violation. So do nothing in this case.  */
93584      continue;
93585    }
93586
93587    if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
93588      if( !isIgnoreErrors || db->mallocFailed ) return;
93589      continue;
93590    }
93591    assert( aiCol || pFKey->nCol==1 );
93592
93593    /* Create a SrcList structure containing the child table.  We need the
93594    ** child table as a SrcList for sqlite3WhereBegin() */
93595    pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
93596    if( pSrc ){
93597      struct SrcList_item *pItem = pSrc->a;
93598      pItem->pTab = pFKey->pFrom;
93599      pItem->zName = pFKey->pFrom->zName;
93600      pItem->pTab->nRef++;
93601      pItem->iCursor = pParse->nTab++;
93602
93603      if( regNew!=0 ){
93604        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
93605      }
93606      if( regOld!=0 ){
93607        /* If there is a RESTRICT action configured for the current operation
93608        ** on the parent table of this FK, then throw an exception
93609        ** immediately if the FK constraint is violated, even if this is a
93610        ** deferred trigger. That's what RESTRICT means. To defer checking
93611        ** the constraint, the FK should specify NO ACTION (represented
93612        ** using OE_None). NO ACTION is the default.  */
93613        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
93614      }
93615      pItem->zName = 0;
93616      sqlite3SrcListDelete(db, pSrc);
93617    }
93618    sqlite3DbFree(db, aiCol);
93619  }
93620}
93621
93622#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
93623
93624/*
93625** This function is called before generating code to update or delete a
93626** row contained in table pTab.
93627*/
93628SQLITE_PRIVATE u32 sqlite3FkOldmask(
93629  Parse *pParse,                  /* Parse context */
93630  Table *pTab                     /* Table being modified */
93631){
93632  u32 mask = 0;
93633  if( pParse->db->flags&SQLITE_ForeignKeys ){
93634    FKey *p;
93635    int i;
93636    for(p=pTab->pFKey; p; p=p->pNextFrom){
93637      for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
93638    }
93639    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
93640      Index *pIdx = 0;
93641      sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
93642      if( pIdx ){
93643        for(i=0; i<pIdx->nKeyCol; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
93644      }
93645    }
93646  }
93647  return mask;
93648}
93649
93650
93651/*
93652** This function is called before generating code to update or delete a
93653** row contained in table pTab. If the operation is a DELETE, then
93654** parameter aChange is passed a NULL value. For an UPDATE, aChange points
93655** to an array of size N, where N is the number of columns in table pTab.
93656** If the i'th column is not modified by the UPDATE, then the corresponding
93657** entry in the aChange[] array is set to -1. If the column is modified,
93658** the value is 0 or greater. Parameter chngRowid is set to true if the
93659** UPDATE statement modifies the rowid fields of the table.
93660**
93661** If any foreign key processing will be required, this function returns
93662** true. If there is no foreign key related processing, this function
93663** returns false.
93664*/
93665SQLITE_PRIVATE int sqlite3FkRequired(
93666  Parse *pParse,                  /* Parse context */
93667  Table *pTab,                    /* Table being modified */
93668  int *aChange,                   /* Non-NULL for UPDATE operations */
93669  int chngRowid                   /* True for UPDATE that affects rowid */
93670){
93671  if( pParse->db->flags&SQLITE_ForeignKeys ){
93672    if( !aChange ){
93673      /* A DELETE operation. Foreign key processing is required if the
93674      ** table in question is either the child or parent table for any
93675      ** foreign key constraint.  */
93676      return (sqlite3FkReferences(pTab) || pTab->pFKey);
93677    }else{
93678      /* This is an UPDATE. Foreign key processing is only required if the
93679      ** operation modifies one or more child or parent key columns. */
93680      FKey *p;
93681
93682      /* Check if any child key columns are being modified. */
93683      for(p=pTab->pFKey; p; p=p->pNextFrom){
93684        if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
93685      }
93686
93687      /* Check if any parent key columns are being modified. */
93688      for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
93689        if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
93690      }
93691    }
93692  }
93693  return 0;
93694}
93695
93696/*
93697** This function is called when an UPDATE or DELETE operation is being
93698** compiled on table pTab, which is the parent table of foreign-key pFKey.
93699** If the current operation is an UPDATE, then the pChanges parameter is
93700** passed a pointer to the list of columns being modified. If it is a
93701** DELETE, pChanges is passed a NULL pointer.
93702**
93703** It returns a pointer to a Trigger structure containing a trigger
93704** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
93705** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
93706** returned (these actions require no special handling by the triggers
93707** sub-system, code for them is created by fkScanChildren()).
93708**
93709** For example, if pFKey is the foreign key and pTab is table "p" in
93710** the following schema:
93711**
93712**   CREATE TABLE p(pk PRIMARY KEY);
93713**   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
93714**
93715** then the returned trigger structure is equivalent to:
93716**
93717**   CREATE TRIGGER ... DELETE ON p BEGIN
93718**     DELETE FROM c WHERE ck = old.pk;
93719**   END;
93720**
93721** The returned pointer is cached as part of the foreign key object. It
93722** is eventually freed along with the rest of the foreign key object by
93723** sqlite3FkDelete().
93724*/
93725static Trigger *fkActionTrigger(
93726  Parse *pParse,                  /* Parse context */
93727  Table *pTab,                    /* Table being updated or deleted from */
93728  FKey *pFKey,                    /* Foreign key to get action for */
93729  ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
93730){
93731  sqlite3 *db = pParse->db;       /* Database handle */
93732  int action;                     /* One of OE_None, OE_Cascade etc. */
93733  Trigger *pTrigger;              /* Trigger definition to return */
93734  int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
93735
93736  action = pFKey->aAction[iAction];
93737  pTrigger = pFKey->apTrigger[iAction];
93738
93739  if( action!=OE_None && !pTrigger ){
93740    u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
93741    char const *zFrom;            /* Name of child table */
93742    int nFrom;                    /* Length in bytes of zFrom */
93743    Index *pIdx = 0;              /* Parent key index for this FK */
93744    int *aiCol = 0;               /* child table cols -> parent key cols */
93745    TriggerStep *pStep = 0;        /* First (only) step of trigger program */
93746    Expr *pWhere = 0;             /* WHERE clause of trigger step */
93747    ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
93748    Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
93749    int i;                        /* Iterator variable */
93750    Expr *pWhen = 0;              /* WHEN clause for the trigger */
93751
93752    if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
93753    assert( aiCol || pFKey->nCol==1 );
93754
93755    for(i=0; i<pFKey->nCol; i++){
93756      Token tOld = { "old", 3 };  /* Literal "old" token */
93757      Token tNew = { "new", 3 };  /* Literal "new" token */
93758      Token tFromCol;             /* Name of column in child table */
93759      Token tToCol;               /* Name of column in parent table */
93760      int iFromCol;               /* Idx of column in child table */
93761      Expr *pEq;                  /* tFromCol = OLD.tToCol */
93762
93763      iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
93764      assert( iFromCol>=0 );
93765      tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
93766      tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
93767
93768      tToCol.n = sqlite3Strlen30(tToCol.z);
93769      tFromCol.n = sqlite3Strlen30(tFromCol.z);
93770
93771      /* Create the expression "OLD.zToCol = zFromCol". It is important
93772      ** that the "OLD.zToCol" term is on the LHS of the = operator, so
93773      ** that the affinity and collation sequence associated with the
93774      ** parent table are used for the comparison. */
93775      pEq = sqlite3PExpr(pParse, TK_EQ,
93776          sqlite3PExpr(pParse, TK_DOT,
93777            sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
93778            sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
93779          , 0),
93780          sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
93781      , 0);
93782      pWhere = sqlite3ExprAnd(db, pWhere, pEq);
93783
93784      /* For ON UPDATE, construct the next term of the WHEN clause.
93785      ** The final WHEN clause will be like this:
93786      **
93787      **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
93788      */
93789      if( pChanges ){
93790        pEq = sqlite3PExpr(pParse, TK_IS,
93791            sqlite3PExpr(pParse, TK_DOT,
93792              sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
93793              sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
93794              0),
93795            sqlite3PExpr(pParse, TK_DOT,
93796              sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
93797              sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
93798              0),
93799            0);
93800        pWhen = sqlite3ExprAnd(db, pWhen, pEq);
93801      }
93802
93803      if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
93804        Expr *pNew;
93805        if( action==OE_Cascade ){
93806          pNew = sqlite3PExpr(pParse, TK_DOT,
93807            sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
93808            sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
93809          , 0);
93810        }else if( action==OE_SetDflt ){
93811          Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
93812          if( pDflt ){
93813            pNew = sqlite3ExprDup(db, pDflt, 0);
93814          }else{
93815            pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
93816          }
93817        }else{
93818          pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
93819        }
93820        pList = sqlite3ExprListAppend(pParse, pList, pNew);
93821        sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
93822      }
93823    }
93824    sqlite3DbFree(db, aiCol);
93825
93826    zFrom = pFKey->pFrom->zName;
93827    nFrom = sqlite3Strlen30(zFrom);
93828
93829    if( action==OE_Restrict ){
93830      Token tFrom;
93831      Expr *pRaise;
93832
93833      tFrom.z = zFrom;
93834      tFrom.n = nFrom;
93835      pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
93836      if( pRaise ){
93837        pRaise->affinity = OE_Abort;
93838      }
93839      pSelect = sqlite3SelectNew(pParse,
93840          sqlite3ExprListAppend(pParse, 0, pRaise),
93841          sqlite3SrcListAppend(db, 0, &tFrom, 0),
93842          pWhere,
93843          0, 0, 0, 0, 0, 0
93844      );
93845      pWhere = 0;
93846    }
93847
93848    /* Disable lookaside memory allocation */
93849    enableLookaside = db->lookaside.bEnabled;
93850    db->lookaside.bEnabled = 0;
93851
93852    pTrigger = (Trigger *)sqlite3DbMallocZero(db,
93853        sizeof(Trigger) +         /* struct Trigger */
93854        sizeof(TriggerStep) +     /* Single step in trigger program */
93855        nFrom + 1                 /* Space for pStep->target.z */
93856    );
93857    if( pTrigger ){
93858      pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
93859      pStep->target.z = (char *)&pStep[1];
93860      pStep->target.n = nFrom;
93861      memcpy((char *)pStep->target.z, zFrom, nFrom);
93862
93863      pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
93864      pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
93865      pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
93866      if( pWhen ){
93867        pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
93868        pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
93869      }
93870    }
93871
93872    /* Re-enable the lookaside buffer, if it was disabled earlier. */
93873    db->lookaside.bEnabled = enableLookaside;
93874
93875    sqlite3ExprDelete(db, pWhere);
93876    sqlite3ExprDelete(db, pWhen);
93877    sqlite3ExprListDelete(db, pList);
93878    sqlite3SelectDelete(db, pSelect);
93879    if( db->mallocFailed==1 ){
93880      fkTriggerDelete(db, pTrigger);
93881      return 0;
93882    }
93883    assert( pStep!=0 );
93884
93885    switch( action ){
93886      case OE_Restrict:
93887        pStep->op = TK_SELECT;
93888        break;
93889      case OE_Cascade:
93890        if( !pChanges ){
93891          pStep->op = TK_DELETE;
93892          break;
93893        }
93894      default:
93895        pStep->op = TK_UPDATE;
93896    }
93897    pStep->pTrig = pTrigger;
93898    pTrigger->pSchema = pTab->pSchema;
93899    pTrigger->pTabSchema = pTab->pSchema;
93900    pFKey->apTrigger[iAction] = pTrigger;
93901    pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
93902  }
93903
93904  return pTrigger;
93905}
93906
93907/*
93908** This function is called when deleting or updating a row to implement
93909** any required CASCADE, SET NULL or SET DEFAULT actions.
93910*/
93911SQLITE_PRIVATE void sqlite3FkActions(
93912  Parse *pParse,                  /* Parse context */
93913  Table *pTab,                    /* Table being updated or deleted from */
93914  ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
93915  int regOld,                     /* Address of array containing old row */
93916  int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
93917  int bChngRowid                  /* True if rowid is UPDATEd */
93918){
93919  /* If foreign-key support is enabled, iterate through all FKs that
93920  ** refer to table pTab. If there is an action associated with the FK
93921  ** for this operation (either update or delete), invoke the associated
93922  ** trigger sub-program.  */
93923  if( pParse->db->flags&SQLITE_ForeignKeys ){
93924    FKey *pFKey;                  /* Iterator variable */
93925    for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
93926      if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
93927        Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
93928        if( pAct ){
93929          sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
93930        }
93931      }
93932    }
93933  }
93934}
93935
93936#endif /* ifndef SQLITE_OMIT_TRIGGER */
93937
93938/*
93939** Free all memory associated with foreign key definitions attached to
93940** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
93941** hash table.
93942*/
93943SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
93944  FKey *pFKey;                    /* Iterator variable */
93945  FKey *pNext;                    /* Copy of pFKey->pNextFrom */
93946
93947  assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
93948  for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
93949
93950    /* Remove the FK from the fkeyHash hash table. */
93951    if( !db || db->pnBytesFreed==0 ){
93952      if( pFKey->pPrevTo ){
93953        pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
93954      }else{
93955        void *p = (void *)pFKey->pNextTo;
93956        const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
93957        sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
93958      }
93959      if( pFKey->pNextTo ){
93960        pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
93961      }
93962    }
93963
93964    /* EV: R-30323-21917 Each foreign key constraint in SQLite is
93965    ** classified as either immediate or deferred.
93966    */
93967    assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
93968
93969    /* Delete any triggers created to implement actions for this FK. */
93970#ifndef SQLITE_OMIT_TRIGGER
93971    fkTriggerDelete(db, pFKey->apTrigger[0]);
93972    fkTriggerDelete(db, pFKey->apTrigger[1]);
93973#endif
93974
93975    pNext = pFKey->pNextFrom;
93976    sqlite3DbFree(db, pFKey);
93977  }
93978}
93979#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
93980
93981/************** End of fkey.c ************************************************/
93982/************** Begin file insert.c ******************************************/
93983/*
93984** 2001 September 15
93985**
93986** The author disclaims copyright to this source code.  In place of
93987** a legal notice, here is a blessing:
93988**
93989**    May you do good and not evil.
93990**    May you find forgiveness for yourself and forgive others.
93991**    May you share freely, never taking more than you give.
93992**
93993*************************************************************************
93994** This file contains C code routines that are called by the parser
93995** to handle INSERT statements in SQLite.
93996*/
93997
93998/*
93999** Generate code that will
94000**
94001**   (1) acquire a lock for table pTab then
94002**   (2) open pTab as cursor iCur.
94003**
94004** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
94005** for that table that is actually opened.
94006*/
94007SQLITE_PRIVATE void sqlite3OpenTable(
94008  Parse *pParse,  /* Generate code into this VDBE */
94009  int iCur,       /* The cursor number of the table */
94010  int iDb,        /* The database index in sqlite3.aDb[] */
94011  Table *pTab,    /* The table to be opened */
94012  int opcode      /* OP_OpenRead or OP_OpenWrite */
94013){
94014  Vdbe *v;
94015  assert( !IsVirtual(pTab) );
94016  v = sqlite3GetVdbe(pParse);
94017  assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
94018  sqlite3TableLock(pParse, iDb, pTab->tnum,
94019                   (opcode==OP_OpenWrite)?1:0, pTab->zName);
94020  if( HasRowid(pTab) ){
94021    sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
94022    VdbeComment((v, "%s", pTab->zName));
94023  }else{
94024    Index *pPk = sqlite3PrimaryKeyIndex(pTab);
94025    assert( pPk!=0 );
94026    assert( pPk->tnum=pTab->tnum );
94027    sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
94028    sqlite3VdbeSetP4KeyInfo(pParse, pPk);
94029    VdbeComment((v, "%s", pTab->zName));
94030  }
94031}
94032
94033/*
94034** Return a pointer to the column affinity string associated with index
94035** pIdx. A column affinity string has one character for each column in
94036** the table, according to the affinity of the column:
94037**
94038**  Character      Column affinity
94039**  ------------------------------
94040**  'a'            TEXT
94041**  'b'            NONE
94042**  'c'            NUMERIC
94043**  'd'            INTEGER
94044**  'e'            REAL
94045**
94046** An extra 'd' is appended to the end of the string to cover the
94047** rowid that appears as the last column in every index.
94048**
94049** Memory for the buffer containing the column index affinity string
94050** is managed along with the rest of the Index structure. It will be
94051** released when sqlite3DeleteIndex() is called.
94052*/
94053SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
94054  if( !pIdx->zColAff ){
94055    /* The first time a column affinity string for a particular index is
94056    ** required, it is allocated and populated here. It is then stored as
94057    ** a member of the Index structure for subsequent use.
94058    **
94059    ** The column affinity string will eventually be deleted by
94060    ** sqliteDeleteIndex() when the Index structure itself is cleaned
94061    ** up.
94062    */
94063    int n;
94064    Table *pTab = pIdx->pTable;
94065    sqlite3 *db = sqlite3VdbeDb(v);
94066    pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
94067    if( !pIdx->zColAff ){
94068      db->mallocFailed = 1;
94069      return 0;
94070    }
94071    for(n=0; n<pIdx->nColumn; n++){
94072      i16 x = pIdx->aiColumn[n];
94073      pIdx->zColAff[n] = x<0 ? SQLITE_AFF_INTEGER : pTab->aCol[x].affinity;
94074    }
94075    pIdx->zColAff[n] = 0;
94076  }
94077
94078  return pIdx->zColAff;
94079}
94080
94081/*
94082** Compute the affinity string for table pTab, if it has not already been
94083** computed.  As an optimization, omit trailing SQLITE_AFF_NONE affinities.
94084**
94085** If the affinity exists (if it is no entirely SQLITE_AFF_NONE values) and
94086** if iReg>0 then code an OP_Affinity opcode that will set the affinities
94087** for register iReg and following.  Or if affinities exists and iReg==0,
94088** then just set the P4 operand of the previous opcode (which should  be
94089** an OP_MakeRecord) to the affinity string.
94090**
94091** A column affinity string has one character per column:
94092**
94093**  Character      Column affinity
94094**  ------------------------------
94095**  'a'            TEXT
94096**  'b'            NONE
94097**  'c'            NUMERIC
94098**  'd'            INTEGER
94099**  'e'            REAL
94100*/
94101SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
94102  int i;
94103  char *zColAff = pTab->zColAff;
94104  if( zColAff==0 ){
94105    sqlite3 *db = sqlite3VdbeDb(v);
94106    zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
94107    if( !zColAff ){
94108      db->mallocFailed = 1;
94109      return;
94110    }
94111
94112    for(i=0; i<pTab->nCol; i++){
94113      zColAff[i] = pTab->aCol[i].affinity;
94114    }
94115    do{
94116      zColAff[i--] = 0;
94117    }while( i>=0 && zColAff[i]==SQLITE_AFF_NONE );
94118    pTab->zColAff = zColAff;
94119  }
94120  i = sqlite3Strlen30(zColAff);
94121  if( i ){
94122    if( iReg ){
94123      sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
94124    }else{
94125      sqlite3VdbeChangeP4(v, -1, zColAff, i);
94126    }
94127  }
94128}
94129
94130/*
94131** Return non-zero if the table pTab in database iDb or any of its indices
94132** have been opened at any point in the VDBE program. This is used to see if
94133** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
94134** run without using a temporary table for the results of the SELECT.
94135*/
94136static int readsTable(Parse *p, int iDb, Table *pTab){
94137  Vdbe *v = sqlite3GetVdbe(p);
94138  int i;
94139  int iEnd = sqlite3VdbeCurrentAddr(v);
94140#ifndef SQLITE_OMIT_VIRTUALTABLE
94141  VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
94142#endif
94143
94144  for(i=1; i<iEnd; i++){
94145    VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
94146    assert( pOp!=0 );
94147    if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
94148      Index *pIndex;
94149      int tnum = pOp->p2;
94150      if( tnum==pTab->tnum ){
94151        return 1;
94152      }
94153      for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
94154        if( tnum==pIndex->tnum ){
94155          return 1;
94156        }
94157      }
94158    }
94159#ifndef SQLITE_OMIT_VIRTUALTABLE
94160    if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
94161      assert( pOp->p4.pVtab!=0 );
94162      assert( pOp->p4type==P4_VTAB );
94163      return 1;
94164    }
94165#endif
94166  }
94167  return 0;
94168}
94169
94170#ifndef SQLITE_OMIT_AUTOINCREMENT
94171/*
94172** Locate or create an AutoincInfo structure associated with table pTab
94173** which is in database iDb.  Return the register number for the register
94174** that holds the maximum rowid.
94175**
94176** There is at most one AutoincInfo structure per table even if the
94177** same table is autoincremented multiple times due to inserts within
94178** triggers.  A new AutoincInfo structure is created if this is the
94179** first use of table pTab.  On 2nd and subsequent uses, the original
94180** AutoincInfo structure is used.
94181**
94182** Three memory locations are allocated:
94183**
94184**   (1)  Register to hold the name of the pTab table.
94185**   (2)  Register to hold the maximum ROWID of pTab.
94186**   (3)  Register to hold the rowid in sqlite_sequence of pTab
94187**
94188** The 2nd register is the one that is returned.  That is all the
94189** insert routine needs to know about.
94190*/
94191static int autoIncBegin(
94192  Parse *pParse,      /* Parsing context */
94193  int iDb,            /* Index of the database holding pTab */
94194  Table *pTab         /* The table we are writing to */
94195){
94196  int memId = 0;      /* Register holding maximum rowid */
94197  if( pTab->tabFlags & TF_Autoincrement ){
94198    Parse *pToplevel = sqlite3ParseToplevel(pParse);
94199    AutoincInfo *pInfo;
94200
94201    pInfo = pToplevel->pAinc;
94202    while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
94203    if( pInfo==0 ){
94204      pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
94205      if( pInfo==0 ) return 0;
94206      pInfo->pNext = pToplevel->pAinc;
94207      pToplevel->pAinc = pInfo;
94208      pInfo->pTab = pTab;
94209      pInfo->iDb = iDb;
94210      pToplevel->nMem++;                  /* Register to hold name of table */
94211      pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
94212      pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
94213    }
94214    memId = pInfo->regCtr;
94215  }
94216  return memId;
94217}
94218
94219/*
94220** This routine generates code that will initialize all of the
94221** register used by the autoincrement tracker.
94222*/
94223SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
94224  AutoincInfo *p;            /* Information about an AUTOINCREMENT */
94225  sqlite3 *db = pParse->db;  /* The database connection */
94226  Db *pDb;                   /* Database only autoinc table */
94227  int memId;                 /* Register holding max rowid */
94228  int addr;                  /* A VDBE address */
94229  Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
94230
94231  /* This routine is never called during trigger-generation.  It is
94232  ** only called from the top-level */
94233  assert( pParse->pTriggerTab==0 );
94234  assert( pParse==sqlite3ParseToplevel(pParse) );
94235
94236  assert( v );   /* We failed long ago if this is not so */
94237  for(p = pParse->pAinc; p; p = p->pNext){
94238    pDb = &db->aDb[p->iDb];
94239    memId = p->regCtr;
94240    assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
94241    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
94242    sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
94243    addr = sqlite3VdbeCurrentAddr(v);
94244    sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
94245    sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9); VdbeCoverage(v);
94246    sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
94247    sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId); VdbeCoverage(v);
94248    sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
94249    sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
94250    sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
94251    sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
94252    sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2); VdbeCoverage(v);
94253    sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
94254    sqlite3VdbeAddOp0(v, OP_Close);
94255  }
94256}
94257
94258/*
94259** Update the maximum rowid for an autoincrement calculation.
94260**
94261** This routine should be called when the top of the stack holds a
94262** new rowid that is about to be inserted.  If that new rowid is
94263** larger than the maximum rowid in the memId memory cell, then the
94264** memory cell is updated.  The stack is unchanged.
94265*/
94266static void autoIncStep(Parse *pParse, int memId, int regRowid){
94267  if( memId>0 ){
94268    sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
94269  }
94270}
94271
94272/*
94273** This routine generates the code needed to write autoincrement
94274** maximum rowid values back into the sqlite_sequence register.
94275** Every statement that might do an INSERT into an autoincrement
94276** table (either directly or through triggers) needs to call this
94277** routine just before the "exit" code.
94278*/
94279SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
94280  AutoincInfo *p;
94281  Vdbe *v = pParse->pVdbe;
94282  sqlite3 *db = pParse->db;
94283
94284  assert( v );
94285  for(p = pParse->pAinc; p; p = p->pNext){
94286    Db *pDb = &db->aDb[p->iDb];
94287    int j1;
94288    int iRec;
94289    int memId = p->regCtr;
94290
94291    iRec = sqlite3GetTempReg(pParse);
94292    assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
94293    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
94294    j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); VdbeCoverage(v);
94295    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
94296    sqlite3VdbeJumpHere(v, j1);
94297    sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
94298    sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
94299    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
94300    sqlite3VdbeAddOp0(v, OP_Close);
94301    sqlite3ReleaseTempReg(pParse, iRec);
94302  }
94303}
94304#else
94305/*
94306** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
94307** above are all no-ops
94308*/
94309# define autoIncBegin(A,B,C) (0)
94310# define autoIncStep(A,B,C)
94311#endif /* SQLITE_OMIT_AUTOINCREMENT */
94312
94313
94314/* Forward declaration */
94315static int xferOptimization(
94316  Parse *pParse,        /* Parser context */
94317  Table *pDest,         /* The table we are inserting into */
94318  Select *pSelect,      /* A SELECT statement to use as the data source */
94319  int onError,          /* How to handle constraint errors */
94320  int iDbDest           /* The database of pDest */
94321);
94322
94323/*
94324** This routine is called to handle SQL of the following forms:
94325**
94326**    insert into TABLE (IDLIST) values(EXPRLIST)
94327**    insert into TABLE (IDLIST) select
94328**
94329** The IDLIST following the table name is always optional.  If omitted,
94330** then a list of all columns for the table is substituted.  The IDLIST
94331** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
94332**
94333** The pList parameter holds EXPRLIST in the first form of the INSERT
94334** statement above, and pSelect is NULL.  For the second form, pList is
94335** NULL and pSelect is a pointer to the select statement used to generate
94336** data for the insert.
94337**
94338** The code generated follows one of four templates.  For a simple
94339** insert with data coming from a VALUES clause, the code executes
94340** once straight down through.  Pseudo-code follows (we call this
94341** the "1st template"):
94342**
94343**         open write cursor to <table> and its indices
94344**         put VALUES clause expressions into registers
94345**         write the resulting record into <table>
94346**         cleanup
94347**
94348** The three remaining templates assume the statement is of the form
94349**
94350**   INSERT INTO <table> SELECT ...
94351**
94352** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
94353** in other words if the SELECT pulls all columns from a single table
94354** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
94355** if <table2> and <table1> are distinct tables but have identical
94356** schemas, including all the same indices, then a special optimization
94357** is invoked that copies raw records from <table2> over to <table1>.
94358** See the xferOptimization() function for the implementation of this
94359** template.  This is the 2nd template.
94360**
94361**         open a write cursor to <table>
94362**         open read cursor on <table2>
94363**         transfer all records in <table2> over to <table>
94364**         close cursors
94365**         foreach index on <table>
94366**           open a write cursor on the <table> index
94367**           open a read cursor on the corresponding <table2> index
94368**           transfer all records from the read to the write cursors
94369**           close cursors
94370**         end foreach
94371**
94372** The 3rd template is for when the second template does not apply
94373** and the SELECT clause does not read from <table> at any time.
94374** The generated code follows this template:
94375**
94376**         X <- A
94377**         goto B
94378**      A: setup for the SELECT
94379**         loop over the rows in the SELECT
94380**           load values into registers R..R+n
94381**           yield X
94382**         end loop
94383**         cleanup after the SELECT
94384**         end-coroutine X
94385**      B: open write cursor to <table> and its indices
94386**      C: yield X, at EOF goto D
94387**         insert the select result into <table> from R..R+n
94388**         goto C
94389**      D: cleanup
94390**
94391** The 4th template is used if the insert statement takes its
94392** values from a SELECT but the data is being inserted into a table
94393** that is also read as part of the SELECT.  In the third form,
94394** we have to use a intermediate table to store the results of
94395** the select.  The template is like this:
94396**
94397**         X <- A
94398**         goto B
94399**      A: setup for the SELECT
94400**         loop over the tables in the SELECT
94401**           load value into register R..R+n
94402**           yield X
94403**         end loop
94404**         cleanup after the SELECT
94405**         end co-routine R
94406**      B: open temp table
94407**      L: yield X, at EOF goto M
94408**         insert row from R..R+n into temp table
94409**         goto L
94410**      M: open write cursor to <table> and its indices
94411**         rewind temp table
94412**      C: loop over rows of intermediate table
94413**           transfer values form intermediate table into <table>
94414**         end loop
94415**      D: cleanup
94416*/
94417SQLITE_PRIVATE void sqlite3Insert(
94418  Parse *pParse,        /* Parser context */
94419  SrcList *pTabList,    /* Name of table into which we are inserting */
94420  Select *pSelect,      /* A SELECT statement to use as the data source */
94421  IdList *pColumn,      /* Column names corresponding to IDLIST. */
94422  int onError           /* How to handle constraint errors */
94423){
94424  sqlite3 *db;          /* The main database structure */
94425  Table *pTab;          /* The table to insert into.  aka TABLE */
94426  char *zTab;           /* Name of the table into which we are inserting */
94427  const char *zDb;      /* Name of the database holding this table */
94428  int i, j, idx;        /* Loop counters */
94429  Vdbe *v;              /* Generate code into this virtual machine */
94430  Index *pIdx;          /* For looping over indices of the table */
94431  int nColumn;          /* Number of columns in the data */
94432  int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
94433  int iDataCur = 0;     /* VDBE cursor that is the main data repository */
94434  int iIdxCur = 0;      /* First index cursor */
94435  int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
94436  int endOfLoop;        /* Label for the end of the insertion loop */
94437  int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
94438  int addrInsTop = 0;   /* Jump to label "D" */
94439  int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
94440  SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
94441  int iDb;              /* Index of database holding TABLE */
94442  Db *pDb;              /* The database containing table being inserted into */
94443  u8 useTempTable = 0;  /* Store SELECT results in intermediate table */
94444  u8 appendFlag = 0;    /* True if the insert is likely to be an append */
94445  u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */
94446  u8 bIdListInOrder = 1; /* True if IDLIST is in table order */
94447  ExprList *pList = 0;  /* List of VALUES() to be inserted  */
94448
94449  /* Register allocations */
94450  int regFromSelect = 0;/* Base register for data coming from SELECT */
94451  int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
94452  int regRowCount = 0;  /* Memory cell used for the row counter */
94453  int regIns;           /* Block of regs holding rowid+data being inserted */
94454  int regRowid;         /* registers holding insert rowid */
94455  int regData;          /* register holding first column to insert */
94456  int *aRegIdx = 0;     /* One register allocated to each index */
94457
94458#ifndef SQLITE_OMIT_TRIGGER
94459  int isView;                 /* True if attempting to insert into a view */
94460  Trigger *pTrigger;          /* List of triggers on pTab, if required */
94461  int tmask;                  /* Mask of trigger times */
94462#endif
94463
94464  db = pParse->db;
94465  memset(&dest, 0, sizeof(dest));
94466  if( pParse->nErr || db->mallocFailed ){
94467    goto insert_cleanup;
94468  }
94469
94470  /* If the Select object is really just a simple VALUES() list with a
94471  ** single row values (the common case) then keep that one row of values
94472  ** and go ahead and discard the Select object
94473  */
94474  if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
94475    pList = pSelect->pEList;
94476    pSelect->pEList = 0;
94477    sqlite3SelectDelete(db, pSelect);
94478    pSelect = 0;
94479  }
94480
94481  /* Locate the table into which we will be inserting new information.
94482  */
94483  assert( pTabList->nSrc==1 );
94484  zTab = pTabList->a[0].zName;
94485  if( NEVER(zTab==0) ) goto insert_cleanup;
94486  pTab = sqlite3SrcListLookup(pParse, pTabList);
94487  if( pTab==0 ){
94488    goto insert_cleanup;
94489  }
94490  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
94491  assert( iDb<db->nDb );
94492  pDb = &db->aDb[iDb];
94493  zDb = pDb->zName;
94494  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
94495    goto insert_cleanup;
94496  }
94497  withoutRowid = !HasRowid(pTab);
94498
94499  /* Figure out if we have any triggers and if the table being
94500  ** inserted into is a view
94501  */
94502#ifndef SQLITE_OMIT_TRIGGER
94503  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
94504  isView = pTab->pSelect!=0;
94505#else
94506# define pTrigger 0
94507# define tmask 0
94508# define isView 0
94509#endif
94510#ifdef SQLITE_OMIT_VIEW
94511# undef isView
94512# define isView 0
94513#endif
94514  assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
94515
94516  /* If pTab is really a view, make sure it has been initialized.
94517  ** ViewGetColumnNames() is a no-op if pTab is not a view.
94518  */
94519  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
94520    goto insert_cleanup;
94521  }
94522
94523  /* Cannot insert into a read-only table.
94524  */
94525  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
94526    goto insert_cleanup;
94527  }
94528
94529  /* Allocate a VDBE
94530  */
94531  v = sqlite3GetVdbe(pParse);
94532  if( v==0 ) goto insert_cleanup;
94533  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
94534  sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
94535
94536#ifndef SQLITE_OMIT_XFER_OPT
94537  /* If the statement is of the form
94538  **
94539  **       INSERT INTO <table1> SELECT * FROM <table2>;
94540  **
94541  ** Then special optimizations can be applied that make the transfer
94542  ** very fast and which reduce fragmentation of indices.
94543  **
94544  ** This is the 2nd template.
94545  */
94546  if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
94547    assert( !pTrigger );
94548    assert( pList==0 );
94549    goto insert_end;
94550  }
94551#endif /* SQLITE_OMIT_XFER_OPT */
94552
94553  /* If this is an AUTOINCREMENT table, look up the sequence number in the
94554  ** sqlite_sequence table and store it in memory cell regAutoinc.
94555  */
94556  regAutoinc = autoIncBegin(pParse, iDb, pTab);
94557
94558  /* Allocate registers for holding the rowid of the new row,
94559  ** the content of the new row, and the assemblied row record.
94560  */
94561  regRowid = regIns = pParse->nMem+1;
94562  pParse->nMem += pTab->nCol + 1;
94563  if( IsVirtual(pTab) ){
94564    regRowid++;
94565    pParse->nMem++;
94566  }
94567  regData = regRowid+1;
94568
94569  /* If the INSERT statement included an IDLIST term, then make sure
94570  ** all elements of the IDLIST really are columns of the table and
94571  ** remember the column indices.
94572  **
94573  ** If the table has an INTEGER PRIMARY KEY column and that column
94574  ** is named in the IDLIST, then record in the ipkColumn variable
94575  ** the index into IDLIST of the primary key column.  ipkColumn is
94576  ** the index of the primary key as it appears in IDLIST, not as
94577  ** is appears in the original table.  (The index of the INTEGER
94578  ** PRIMARY KEY in the original table is pTab->iPKey.)
94579  */
94580  if( pColumn ){
94581    for(i=0; i<pColumn->nId; i++){
94582      pColumn->a[i].idx = -1;
94583    }
94584    for(i=0; i<pColumn->nId; i++){
94585      for(j=0; j<pTab->nCol; j++){
94586        if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
94587          pColumn->a[i].idx = j;
94588          if( i!=j ) bIdListInOrder = 0;
94589          if( j==pTab->iPKey ){
94590            ipkColumn = i;  assert( !withoutRowid );
94591          }
94592          break;
94593        }
94594      }
94595      if( j>=pTab->nCol ){
94596        if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
94597          ipkColumn = i;
94598          bIdListInOrder = 0;
94599        }else{
94600          sqlite3ErrorMsg(pParse, "table %S has no column named %s",
94601              pTabList, 0, pColumn->a[i].zName);
94602          pParse->checkSchema = 1;
94603          goto insert_cleanup;
94604        }
94605      }
94606    }
94607  }
94608
94609  /* Figure out how many columns of data are supplied.  If the data
94610  ** is coming from a SELECT statement, then generate a co-routine that
94611  ** produces a single row of the SELECT on each invocation.  The
94612  ** co-routine is the common header to the 3rd and 4th templates.
94613  */
94614  if( pSelect ){
94615    /* Data is coming from a SELECT.  Generate a co-routine to run the SELECT */
94616    int regYield;       /* Register holding co-routine entry-point */
94617    int addrTop;        /* Top of the co-routine */
94618    int rc;             /* Result code */
94619
94620    regYield = ++pParse->nMem;
94621    addrTop = sqlite3VdbeCurrentAddr(v) + 1;
94622    sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
94623    sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
94624    dest.iSdst = bIdListInOrder ? regData : 0;
94625    dest.nSdst = pTab->nCol;
94626    rc = sqlite3Select(pParse, pSelect, &dest);
94627    regFromSelect = dest.iSdst;
94628    assert( pParse->nErr==0 || rc );
94629    if( rc || db->mallocFailed ) goto insert_cleanup;
94630    sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
94631    sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
94632    assert( pSelect->pEList );
94633    nColumn = pSelect->pEList->nExpr;
94634
94635    /* Set useTempTable to TRUE if the result of the SELECT statement
94636    ** should be written into a temporary table (template 4).  Set to
94637    ** FALSE if each output row of the SELECT can be written directly into
94638    ** the destination table (template 3).
94639    **
94640    ** A temp table must be used if the table being updated is also one
94641    ** of the tables being read by the SELECT statement.  Also use a
94642    ** temp table in the case of row triggers.
94643    */
94644    if( pTrigger || readsTable(pParse, iDb, pTab) ){
94645      useTempTable = 1;
94646    }
94647
94648    if( useTempTable ){
94649      /* Invoke the coroutine to extract information from the SELECT
94650      ** and add it to a transient table srcTab.  The code generated
94651      ** here is from the 4th template:
94652      **
94653      **      B: open temp table
94654      **      L: yield X, goto M at EOF
94655      **         insert row from R..R+n into temp table
94656      **         goto L
94657      **      M: ...
94658      */
94659      int regRec;          /* Register to hold packed record */
94660      int regTempRowid;    /* Register to hold temp table ROWID */
94661      int addrL;           /* Label "L" */
94662
94663      srcTab = pParse->nTab++;
94664      regRec = sqlite3GetTempReg(pParse);
94665      regTempRowid = sqlite3GetTempReg(pParse);
94666      sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
94667      addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
94668      sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
94669      sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
94670      sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
94671      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrL);
94672      sqlite3VdbeJumpHere(v, addrL);
94673      sqlite3ReleaseTempReg(pParse, regRec);
94674      sqlite3ReleaseTempReg(pParse, regTempRowid);
94675    }
94676  }else{
94677    /* This is the case if the data for the INSERT is coming from a VALUES
94678    ** clause
94679    */
94680    NameContext sNC;
94681    memset(&sNC, 0, sizeof(sNC));
94682    sNC.pParse = pParse;
94683    srcTab = -1;
94684    assert( useTempTable==0 );
94685    nColumn = pList ? pList->nExpr : 0;
94686    for(i=0; i<nColumn; i++){
94687      if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
94688        goto insert_cleanup;
94689      }
94690    }
94691  }
94692
94693  /* If there is no IDLIST term but the table has an integer primary
94694  ** key, the set the ipkColumn variable to the integer primary key
94695  ** column index in the original table definition.
94696  */
94697  if( pColumn==0 && nColumn>0 ){
94698    ipkColumn = pTab->iPKey;
94699  }
94700
94701  /* Make sure the number of columns in the source data matches the number
94702  ** of columns to be inserted into the table.
94703  */
94704  if( IsVirtual(pTab) ){
94705    for(i=0; i<pTab->nCol; i++){
94706      nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
94707    }
94708  }
94709  if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
94710    sqlite3ErrorMsg(pParse,
94711       "table %S has %d columns but %d values were supplied",
94712       pTabList, 0, pTab->nCol-nHidden, nColumn);
94713    goto insert_cleanup;
94714  }
94715  if( pColumn!=0 && nColumn!=pColumn->nId ){
94716    sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
94717    goto insert_cleanup;
94718  }
94719
94720  /* Initialize the count of rows to be inserted
94721  */
94722  if( db->flags & SQLITE_CountRows ){
94723    regRowCount = ++pParse->nMem;
94724    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
94725  }
94726
94727  /* If this is not a view, open the table and and all indices */
94728  if( !isView ){
94729    int nIdx;
94730    nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, -1, 0,
94731                                      &iDataCur, &iIdxCur);
94732    aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
94733    if( aRegIdx==0 ){
94734      goto insert_cleanup;
94735    }
94736    for(i=0; i<nIdx; i++){
94737      aRegIdx[i] = ++pParse->nMem;
94738    }
94739  }
94740
94741  /* This is the top of the main insertion loop */
94742  if( useTempTable ){
94743    /* This block codes the top of loop only.  The complete loop is the
94744    ** following pseudocode (template 4):
94745    **
94746    **         rewind temp table, if empty goto D
94747    **      C: loop over rows of intermediate table
94748    **           transfer values form intermediate table into <table>
94749    **         end loop
94750    **      D: ...
94751    */
94752    addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
94753    addrCont = sqlite3VdbeCurrentAddr(v);
94754  }else if( pSelect ){
94755    /* This block codes the top of loop only.  The complete loop is the
94756    ** following pseudocode (template 3):
94757    **
94758    **      C: yield X, at EOF goto D
94759    **         insert the select result into <table> from R..R+n
94760    **         goto C
94761    **      D: ...
94762    */
94763    addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
94764    VdbeCoverage(v);
94765  }
94766
94767  /* Run the BEFORE and INSTEAD OF triggers, if there are any
94768  */
94769  endOfLoop = sqlite3VdbeMakeLabel(v);
94770  if( tmask & TRIGGER_BEFORE ){
94771    int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
94772
94773    /* build the NEW.* reference row.  Note that if there is an INTEGER
94774    ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
94775    ** translated into a unique ID for the row.  But on a BEFORE trigger,
94776    ** we do not know what the unique ID will be (because the insert has
94777    ** not happened yet) so we substitute a rowid of -1
94778    */
94779    if( ipkColumn<0 ){
94780      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
94781    }else{
94782      int j1;
94783      assert( !withoutRowid );
94784      if( useTempTable ){
94785        sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
94786      }else{
94787        assert( pSelect==0 );  /* Otherwise useTempTable is true */
94788        sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
94789      }
94790      j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
94791      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
94792      sqlite3VdbeJumpHere(v, j1);
94793      sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
94794    }
94795
94796    /* Cannot have triggers on a virtual table. If it were possible,
94797    ** this block would have to account for hidden column.
94798    */
94799    assert( !IsVirtual(pTab) );
94800
94801    /* Create the new column data
94802    */
94803    for(i=0; i<pTab->nCol; i++){
94804      if( pColumn==0 ){
94805        j = i;
94806      }else{
94807        for(j=0; j<pColumn->nId; j++){
94808          if( pColumn->a[j].idx==i ) break;
94809        }
94810      }
94811      if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
94812        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
94813      }else if( useTempTable ){
94814        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
94815      }else{
94816        assert( pSelect==0 ); /* Otherwise useTempTable is true */
94817        sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
94818      }
94819    }
94820
94821    /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
94822    ** do not attempt any conversions before assembling the record.
94823    ** If this is a real table, attempt conversions as required by the
94824    ** table column affinities.
94825    */
94826    if( !isView ){
94827      sqlite3TableAffinity(v, pTab, regCols+1);
94828    }
94829
94830    /* Fire BEFORE or INSTEAD OF triggers */
94831    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
94832        pTab, regCols-pTab->nCol-1, onError, endOfLoop);
94833
94834    sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
94835  }
94836
94837  /* Compute the content of the next row to insert into a range of
94838  ** registers beginning at regIns.
94839  */
94840  if( !isView ){
94841    if( IsVirtual(pTab) ){
94842      /* The row that the VUpdate opcode will delete: none */
94843      sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
94844    }
94845    if( ipkColumn>=0 ){
94846      if( useTempTable ){
94847        sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
94848      }else if( pSelect ){
94849        sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
94850      }else{
94851        VdbeOp *pOp;
94852        sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
94853        pOp = sqlite3VdbeGetOp(v, -1);
94854        if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
94855          appendFlag = 1;
94856          pOp->opcode = OP_NewRowid;
94857          pOp->p1 = iDataCur;
94858          pOp->p2 = regRowid;
94859          pOp->p3 = regAutoinc;
94860        }
94861      }
94862      /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
94863      ** to generate a unique primary key value.
94864      */
94865      if( !appendFlag ){
94866        int j1;
94867        if( !IsVirtual(pTab) ){
94868          j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
94869          sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
94870          sqlite3VdbeJumpHere(v, j1);
94871        }else{
94872          j1 = sqlite3VdbeCurrentAddr(v);
94873          sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2); VdbeCoverage(v);
94874        }
94875        sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
94876      }
94877    }else if( IsVirtual(pTab) || withoutRowid ){
94878      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
94879    }else{
94880      sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
94881      appendFlag = 1;
94882    }
94883    autoIncStep(pParse, regAutoinc, regRowid);
94884
94885    /* Compute data for all columns of the new entry, beginning
94886    ** with the first column.
94887    */
94888    nHidden = 0;
94889    for(i=0; i<pTab->nCol; i++){
94890      int iRegStore = regRowid+1+i;
94891      if( i==pTab->iPKey ){
94892        /* The value of the INTEGER PRIMARY KEY column is always a NULL.
94893        ** Whenever this column is read, the rowid will be substituted
94894        ** in its place.  Hence, fill this column with a NULL to avoid
94895        ** taking up data space with information that will never be used.
94896        ** As there may be shallow copies of this value, make it a soft-NULL */
94897        sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
94898        continue;
94899      }
94900      if( pColumn==0 ){
94901        if( IsHiddenColumn(&pTab->aCol[i]) ){
94902          assert( IsVirtual(pTab) );
94903          j = -1;
94904          nHidden++;
94905        }else{
94906          j = i - nHidden;
94907        }
94908      }else{
94909        for(j=0; j<pColumn->nId; j++){
94910          if( pColumn->a[j].idx==i ) break;
94911        }
94912      }
94913      if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
94914        sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
94915      }else if( useTempTable ){
94916        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
94917      }else if( pSelect ){
94918        if( regFromSelect!=regData ){
94919          sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
94920        }
94921      }else{
94922        sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
94923      }
94924    }
94925
94926    /* Generate code to check constraints and generate index keys and
94927    ** do the insertion.
94928    */
94929#ifndef SQLITE_OMIT_VIRTUALTABLE
94930    if( IsVirtual(pTab) ){
94931      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
94932      sqlite3VtabMakeWritable(pParse, pTab);
94933      sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
94934      sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
94935      sqlite3MayAbort(pParse);
94936    }else
94937#endif
94938    {
94939      int isReplace;    /* Set to true if constraints may cause a replace */
94940      sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
94941          regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace
94942      );
94943      sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
94944      sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
94945                               regIns, aRegIdx, 0, appendFlag, isReplace==0);
94946    }
94947  }
94948
94949  /* Update the count of rows that are inserted
94950  */
94951  if( (db->flags & SQLITE_CountRows)!=0 ){
94952    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
94953  }
94954
94955  if( pTrigger ){
94956    /* Code AFTER triggers */
94957    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
94958        pTab, regData-2-pTab->nCol, onError, endOfLoop);
94959  }
94960
94961  /* The bottom of the main insertion loop, if the data source
94962  ** is a SELECT statement.
94963  */
94964  sqlite3VdbeResolveLabel(v, endOfLoop);
94965  if( useTempTable ){
94966    sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
94967    sqlite3VdbeJumpHere(v, addrInsTop);
94968    sqlite3VdbeAddOp1(v, OP_Close, srcTab);
94969  }else if( pSelect ){
94970    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
94971    sqlite3VdbeJumpHere(v, addrInsTop);
94972  }
94973
94974  if( !IsVirtual(pTab) && !isView ){
94975    /* Close all tables opened */
94976    if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
94977    for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
94978      sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
94979    }
94980  }
94981
94982insert_end:
94983  /* Update the sqlite_sequence table by storing the content of the
94984  ** maximum rowid counter values recorded while inserting into
94985  ** autoincrement tables.
94986  */
94987  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
94988    sqlite3AutoincrementEnd(pParse);
94989  }
94990
94991  /*
94992  ** Return the number of rows inserted. If this routine is
94993  ** generating code because of a call to sqlite3NestedParse(), do not
94994  ** invoke the callback function.
94995  */
94996  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
94997    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
94998    sqlite3VdbeSetNumCols(v, 1);
94999    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
95000  }
95001
95002insert_cleanup:
95003  sqlite3SrcListDelete(db, pTabList);
95004  sqlite3ExprListDelete(db, pList);
95005  sqlite3SelectDelete(db, pSelect);
95006  sqlite3IdListDelete(db, pColumn);
95007  sqlite3DbFree(db, aRegIdx);
95008}
95009
95010/* Make sure "isView" and other macros defined above are undefined. Otherwise
95011** thely may interfere with compilation of other functions in this file
95012** (or in another file, if this file becomes part of the amalgamation).  */
95013#ifdef isView
95014 #undef isView
95015#endif
95016#ifdef pTrigger
95017 #undef pTrigger
95018#endif
95019#ifdef tmask
95020 #undef tmask
95021#endif
95022
95023/*
95024** Generate code to do constraint checks prior to an INSERT or an UPDATE
95025** on table pTab.
95026**
95027** The regNewData parameter is the first register in a range that contains
95028** the data to be inserted or the data after the update.  There will be
95029** pTab->nCol+1 registers in this range.  The first register (the one
95030** that regNewData points to) will contain the new rowid, or NULL in the
95031** case of a WITHOUT ROWID table.  The second register in the range will
95032** contain the content of the first table column.  The third register will
95033** contain the content of the second table column.  And so forth.
95034**
95035** The regOldData parameter is similar to regNewData except that it contains
95036** the data prior to an UPDATE rather than afterwards.  regOldData is zero
95037** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
95038** checking regOldData for zero.
95039**
95040** For an UPDATE, the pkChng boolean is true if the true primary key (the
95041** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
95042** might be modified by the UPDATE.  If pkChng is false, then the key of
95043** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
95044**
95045** For an INSERT, the pkChng boolean indicates whether or not the rowid
95046** was explicitly specified as part of the INSERT statement.  If pkChng
95047** is zero, it means that the either rowid is computed automatically or
95048** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
95049** pkChng will only be true if the INSERT statement provides an integer
95050** value for either the rowid column or its INTEGER PRIMARY KEY alias.
95051**
95052** The code generated by this routine will store new index entries into
95053** registers identified by aRegIdx[].  No index entry is created for
95054** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
95055** the same as the order of indices on the linked list of indices
95056** at pTab->pIndex.
95057**
95058** The caller must have already opened writeable cursors on the main
95059** table and all applicable indices (that is to say, all indices for which
95060** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
95061** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
95062** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
95063** for the first index in the pTab->pIndex list.  Cursors for other indices
95064** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
95065**
95066** This routine also generates code to check constraints.  NOT NULL,
95067** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
95068** then the appropriate action is performed.  There are five possible
95069** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
95070**
95071**  Constraint type  Action       What Happens
95072**  ---------------  ----------   ----------------------------------------
95073**  any              ROLLBACK     The current transaction is rolled back and
95074**                                sqlite3_step() returns immediately with a
95075**                                return code of SQLITE_CONSTRAINT.
95076**
95077**  any              ABORT        Back out changes from the current command
95078**                                only (do not do a complete rollback) then
95079**                                cause sqlite3_step() to return immediately
95080**                                with SQLITE_CONSTRAINT.
95081**
95082**  any              FAIL         Sqlite3_step() returns immediately with a
95083**                                return code of SQLITE_CONSTRAINT.  The
95084**                                transaction is not rolled back and any
95085**                                changes to prior rows are retained.
95086**
95087**  any              IGNORE       The attempt in insert or update the current
95088**                                row is skipped, without throwing an error.
95089**                                Processing continues with the next row.
95090**                                (There is an immediate jump to ignoreDest.)
95091**
95092**  NOT NULL         REPLACE      The NULL value is replace by the default
95093**                                value for that column.  If the default value
95094**                                is NULL, the action is the same as ABORT.
95095**
95096**  UNIQUE           REPLACE      The other row that conflicts with the row
95097**                                being inserted is removed.
95098**
95099**  CHECK            REPLACE      Illegal.  The results in an exception.
95100**
95101** Which action to take is determined by the overrideError parameter.
95102** Or if overrideError==OE_Default, then the pParse->onError parameter
95103** is used.  Or if pParse->onError==OE_Default then the onError value
95104** for the constraint is used.
95105*/
95106SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
95107  Parse *pParse,       /* The parser context */
95108  Table *pTab,         /* The table being inserted or updated */
95109  int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
95110  int iDataCur,        /* Canonical data cursor (main table or PK index) */
95111  int iIdxCur,         /* First index cursor */
95112  int regNewData,      /* First register in a range holding values to insert */
95113  int regOldData,      /* Previous content.  0 for INSERTs */
95114  u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
95115  u8 overrideError,    /* Override onError to this if not OE_Default */
95116  int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
95117  int *pbMayReplace    /* OUT: Set to true if constraint may cause a replace */
95118){
95119  Vdbe *v;             /* VDBE under constrution */
95120  Index *pIdx;         /* Pointer to one of the indices */
95121  Index *pPk = 0;      /* The PRIMARY KEY index */
95122  sqlite3 *db;         /* Database connection */
95123  int i;               /* loop counter */
95124  int ix;              /* Index loop counter */
95125  int nCol;            /* Number of columns */
95126  int onError;         /* Conflict resolution strategy */
95127  int j1;              /* Addresss of jump instruction */
95128  int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
95129  int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
95130  int ipkTop = 0;      /* Top of the rowid change constraint check */
95131  int ipkBottom = 0;   /* Bottom of the rowid change constraint check */
95132  u8 isUpdate;         /* True if this is an UPDATE operation */
95133  u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */
95134  int regRowid = -1;   /* Register holding ROWID value */
95135
95136  isUpdate = regOldData!=0;
95137  db = pParse->db;
95138  v = sqlite3GetVdbe(pParse);
95139  assert( v!=0 );
95140  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
95141  nCol = pTab->nCol;
95142
95143  /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
95144  ** normal rowid tables.  nPkField is the number of key fields in the
95145  ** pPk index or 1 for a rowid table.  In other words, nPkField is the
95146  ** number of fields in the true primary key of the table. */
95147  if( HasRowid(pTab) ){
95148    pPk = 0;
95149    nPkField = 1;
95150  }else{
95151    pPk = sqlite3PrimaryKeyIndex(pTab);
95152    nPkField = pPk->nKeyCol;
95153  }
95154
95155  /* Record that this module has started */
95156  VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
95157                     iDataCur, iIdxCur, regNewData, regOldData, pkChng));
95158
95159  /* Test all NOT NULL constraints.
95160  */
95161  for(i=0; i<nCol; i++){
95162    if( i==pTab->iPKey ){
95163      continue;
95164    }
95165    onError = pTab->aCol[i].notNull;
95166    if( onError==OE_None ) continue;
95167    if( overrideError!=OE_Default ){
95168      onError = overrideError;
95169    }else if( onError==OE_Default ){
95170      onError = OE_Abort;
95171    }
95172    if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
95173      onError = OE_Abort;
95174    }
95175    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
95176        || onError==OE_Ignore || onError==OE_Replace );
95177    switch( onError ){
95178      case OE_Abort:
95179        sqlite3MayAbort(pParse);
95180        /* Fall through */
95181      case OE_Rollback:
95182      case OE_Fail: {
95183        char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
95184                                    pTab->aCol[i].zName);
95185        sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
95186                          regNewData+1+i, zMsg, P4_DYNAMIC);
95187        sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
95188        VdbeCoverage(v);
95189        break;
95190      }
95191      case OE_Ignore: {
95192        sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
95193        VdbeCoverage(v);
95194        break;
95195      }
95196      default: {
95197        assert( onError==OE_Replace );
95198        j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i); VdbeCoverage(v);
95199        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
95200        sqlite3VdbeJumpHere(v, j1);
95201        break;
95202      }
95203    }
95204  }
95205
95206  /* Test all CHECK constraints
95207  */
95208#ifndef SQLITE_OMIT_CHECK
95209  if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
95210    ExprList *pCheck = pTab->pCheck;
95211    pParse->ckBase = regNewData+1;
95212    onError = overrideError!=OE_Default ? overrideError : OE_Abort;
95213    for(i=0; i<pCheck->nExpr; i++){
95214      int allOk = sqlite3VdbeMakeLabel(v);
95215      sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
95216      if( onError==OE_Ignore ){
95217        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
95218      }else{
95219        char *zName = pCheck->a[i].zName;
95220        if( zName==0 ) zName = pTab->zName;
95221        if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
95222        sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
95223                              onError, zName, P4_TRANSIENT,
95224                              P5_ConstraintCheck);
95225      }
95226      sqlite3VdbeResolveLabel(v, allOk);
95227    }
95228  }
95229#endif /* !defined(SQLITE_OMIT_CHECK) */
95230
95231  /* If rowid is changing, make sure the new rowid does not previously
95232  ** exist in the table.
95233  */
95234  if( pkChng && pPk==0 ){
95235    int addrRowidOk = sqlite3VdbeMakeLabel(v);
95236
95237    /* Figure out what action to take in case of a rowid collision */
95238    onError = pTab->keyConf;
95239    if( overrideError!=OE_Default ){
95240      onError = overrideError;
95241    }else if( onError==OE_Default ){
95242      onError = OE_Abort;
95243    }
95244
95245    if( isUpdate ){
95246      /* pkChng!=0 does not mean that the rowid has change, only that
95247      ** it might have changed.  Skip the conflict logic below if the rowid
95248      ** is unchanged. */
95249      sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
95250      sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
95251      VdbeCoverage(v);
95252    }
95253
95254    /* If the response to a rowid conflict is REPLACE but the response
95255    ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
95256    ** to defer the running of the rowid conflict checking until after
95257    ** the UNIQUE constraints have run.
95258    */
95259    if( onError==OE_Replace && overrideError!=OE_Replace ){
95260      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
95261        if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
95262          ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
95263          break;
95264        }
95265      }
95266    }
95267
95268    /* Check to see if the new rowid already exists in the table.  Skip
95269    ** the following conflict logic if it does not. */
95270    sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
95271    VdbeCoverage(v);
95272
95273    /* Generate code that deals with a rowid collision */
95274    switch( onError ){
95275      default: {
95276        onError = OE_Abort;
95277        /* Fall thru into the next case */
95278      }
95279      case OE_Rollback:
95280      case OE_Abort:
95281      case OE_Fail: {
95282        sqlite3RowidConstraint(pParse, onError, pTab);
95283        break;
95284      }
95285      case OE_Replace: {
95286        /* If there are DELETE triggers on this table and the
95287        ** recursive-triggers flag is set, call GenerateRowDelete() to
95288        ** remove the conflicting row from the table. This will fire
95289        ** the triggers and remove both the table and index b-tree entries.
95290        **
95291        ** Otherwise, if there are no triggers or the recursive-triggers
95292        ** flag is not set, but the table has one or more indexes, call
95293        ** GenerateRowIndexDelete(). This removes the index b-tree entries
95294        ** only. The table b-tree entry will be replaced by the new entry
95295        ** when it is inserted.
95296        **
95297        ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
95298        ** also invoke MultiWrite() to indicate that this VDBE may require
95299        ** statement rollback (if the statement is aborted after the delete
95300        ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
95301        ** but being more selective here allows statements like:
95302        **
95303        **   REPLACE INTO t(rowid) VALUES($newrowid)
95304        **
95305        ** to run without a statement journal if there are no indexes on the
95306        ** table.
95307        */
95308        Trigger *pTrigger = 0;
95309        if( db->flags&SQLITE_RecTriggers ){
95310          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
95311        }
95312        if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
95313          sqlite3MultiWrite(pParse);
95314          sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
95315                                   regNewData, 1, 0, OE_Replace, 1);
95316        }else if( pTab->pIndex ){
95317          sqlite3MultiWrite(pParse);
95318          sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
95319        }
95320        seenReplace = 1;
95321        break;
95322      }
95323      case OE_Ignore: {
95324        /*assert( seenReplace==0 );*/
95325        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
95326        break;
95327      }
95328    }
95329    sqlite3VdbeResolveLabel(v, addrRowidOk);
95330    if( ipkTop ){
95331      ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
95332      sqlite3VdbeJumpHere(v, ipkTop);
95333    }
95334  }
95335
95336  /* Test all UNIQUE constraints by creating entries for each UNIQUE
95337  ** index and making sure that duplicate entries do not already exist.
95338  ** Compute the revised record entries for indices as we go.
95339  **
95340  ** This loop also handles the case of the PRIMARY KEY index for a
95341  ** WITHOUT ROWID table.
95342  */
95343  for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
95344    int regIdx;          /* Range of registers hold conent for pIdx */
95345    int regR;            /* Range of registers holding conflicting PK */
95346    int iThisCur;        /* Cursor for this UNIQUE index */
95347    int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
95348
95349    if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
95350    if( bAffinityDone==0 ){
95351      sqlite3TableAffinity(v, pTab, regNewData+1);
95352      bAffinityDone = 1;
95353    }
95354    iThisCur = iIdxCur+ix;
95355    addrUniqueOk = sqlite3VdbeMakeLabel(v);
95356
95357    /* Skip partial indices for which the WHERE clause is not true */
95358    if( pIdx->pPartIdxWhere ){
95359      sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
95360      pParse->ckBase = regNewData+1;
95361      sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
95362                         SQLITE_JUMPIFNULL);
95363      pParse->ckBase = 0;
95364    }
95365
95366    /* Create a record for this index entry as it should appear after
95367    ** the insert or update.  Store that record in the aRegIdx[ix] register
95368    */
95369    regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
95370    for(i=0; i<pIdx->nColumn; i++){
95371      int iField = pIdx->aiColumn[i];
95372      int x;
95373      if( iField<0 || iField==pTab->iPKey ){
95374        if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */
95375        x = regNewData;
95376        regRowid =  pIdx->pPartIdxWhere ? -1 : regIdx+i;
95377      }else{
95378        x = iField + regNewData + 1;
95379      }
95380      sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
95381      VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
95382    }
95383    sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
95384    VdbeComment((v, "for %s", pIdx->zName));
95385    sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
95386
95387    /* In an UPDATE operation, if this index is the PRIMARY KEY index
95388    ** of a WITHOUT ROWID table and there has been no change the
95389    ** primary key, then no collision is possible.  The collision detection
95390    ** logic below can all be skipped. */
95391    if( isUpdate && pPk==pIdx && pkChng==0 ){
95392      sqlite3VdbeResolveLabel(v, addrUniqueOk);
95393      continue;
95394    }
95395
95396    /* Find out what action to take in case there is a uniqueness conflict */
95397    onError = pIdx->onError;
95398    if( onError==OE_None ){
95399      sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
95400      sqlite3VdbeResolveLabel(v, addrUniqueOk);
95401      continue;  /* pIdx is not a UNIQUE index */
95402    }
95403    if( overrideError!=OE_Default ){
95404      onError = overrideError;
95405    }else if( onError==OE_Default ){
95406      onError = OE_Abort;
95407    }
95408
95409    /* Check to see if the new index entry will be unique */
95410    sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
95411                         regIdx, pIdx->nKeyCol); VdbeCoverage(v);
95412
95413    /* Generate code to handle collisions */
95414    regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
95415    if( isUpdate || onError==OE_Replace ){
95416      if( HasRowid(pTab) ){
95417        sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
95418        /* Conflict only if the rowid of the existing index entry
95419        ** is different from old-rowid */
95420        if( isUpdate ){
95421          sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
95422          sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
95423          VdbeCoverage(v);
95424        }
95425      }else{
95426        int x;
95427        /* Extract the PRIMARY KEY from the end of the index entry and
95428        ** store it in registers regR..regR+nPk-1 */
95429        if( pIdx!=pPk ){
95430          for(i=0; i<pPk->nKeyCol; i++){
95431            x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
95432            sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
95433            VdbeComment((v, "%s.%s", pTab->zName,
95434                         pTab->aCol[pPk->aiColumn[i]].zName));
95435          }
95436        }
95437        if( isUpdate ){
95438          /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
95439          ** table, only conflict if the new PRIMARY KEY values are actually
95440          ** different from the old.
95441          **
95442          ** For a UNIQUE index, only conflict if the PRIMARY KEY values
95443          ** of the matched index row are different from the original PRIMARY
95444          ** KEY values of this row before the update.  */
95445          int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
95446          int op = OP_Ne;
95447          int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
95448
95449          for(i=0; i<pPk->nKeyCol; i++){
95450            char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
95451            x = pPk->aiColumn[i];
95452            if( i==(pPk->nKeyCol-1) ){
95453              addrJump = addrUniqueOk;
95454              op = OP_Eq;
95455            }
95456            sqlite3VdbeAddOp4(v, op,
95457                regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
95458            );
95459            sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
95460            VdbeCoverageIf(v, op==OP_Eq);
95461            VdbeCoverageIf(v, op==OP_Ne);
95462          }
95463        }
95464      }
95465    }
95466
95467    /* Generate code that executes if the new index entry is not unique */
95468    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
95469        || onError==OE_Ignore || onError==OE_Replace );
95470    switch( onError ){
95471      case OE_Rollback:
95472      case OE_Abort:
95473      case OE_Fail: {
95474        sqlite3UniqueConstraint(pParse, onError, pIdx);
95475        break;
95476      }
95477      case OE_Ignore: {
95478        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
95479        break;
95480      }
95481      default: {
95482        Trigger *pTrigger = 0;
95483        assert( onError==OE_Replace );
95484        sqlite3MultiWrite(pParse);
95485        if( db->flags&SQLITE_RecTriggers ){
95486          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
95487        }
95488        sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
95489                                 regR, nPkField, 0, OE_Replace, pIdx==pPk);
95490        seenReplace = 1;
95491        break;
95492      }
95493    }
95494    sqlite3VdbeResolveLabel(v, addrUniqueOk);
95495    sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
95496    if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
95497  }
95498  if( ipkTop ){
95499    sqlite3VdbeAddOp2(v, OP_Goto, 0, ipkTop+1);
95500    sqlite3VdbeJumpHere(v, ipkBottom);
95501  }
95502
95503  *pbMayReplace = seenReplace;
95504  VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
95505}
95506
95507/*
95508** This routine generates code to finish the INSERT or UPDATE operation
95509** that was started by a prior call to sqlite3GenerateConstraintChecks.
95510** A consecutive range of registers starting at regNewData contains the
95511** rowid and the content to be inserted.
95512**
95513** The arguments to this routine should be the same as the first six
95514** arguments to sqlite3GenerateConstraintChecks.
95515*/
95516SQLITE_PRIVATE void sqlite3CompleteInsertion(
95517  Parse *pParse,      /* The parser context */
95518  Table *pTab,        /* the table into which we are inserting */
95519  int iDataCur,       /* Cursor of the canonical data source */
95520  int iIdxCur,        /* First index cursor */
95521  int regNewData,     /* Range of content */
95522  int *aRegIdx,       /* Register used by each index.  0 for unused indices */
95523  int isUpdate,       /* True for UPDATE, False for INSERT */
95524  int appendBias,     /* True if this is likely to be an append */
95525  int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
95526){
95527  Vdbe *v;            /* Prepared statements under construction */
95528  Index *pIdx;        /* An index being inserted or updated */
95529  u8 pik_flags;       /* flag values passed to the btree insert */
95530  int regData;        /* Content registers (after the rowid) */
95531  int regRec;         /* Register holding assemblied record for the table */
95532  int i;              /* Loop counter */
95533  u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
95534
95535  v = sqlite3GetVdbe(pParse);
95536  assert( v!=0 );
95537  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
95538  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
95539    if( aRegIdx[i]==0 ) continue;
95540    bAffinityDone = 1;
95541    if( pIdx->pPartIdxWhere ){
95542      sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
95543      VdbeCoverage(v);
95544    }
95545    sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
95546    pik_flags = 0;
95547    if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
95548    if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
95549      assert( pParse->nested==0 );
95550      pik_flags |= OPFLAG_NCHANGE;
95551    }
95552    if( pik_flags )  sqlite3VdbeChangeP5(v, pik_flags);
95553  }
95554  if( !HasRowid(pTab) ) return;
95555  regData = regNewData + 1;
95556  regRec = sqlite3GetTempReg(pParse);
95557  sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
95558  if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0);
95559  sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
95560  if( pParse->nested ){
95561    pik_flags = 0;
95562  }else{
95563    pik_flags = OPFLAG_NCHANGE;
95564    pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
95565  }
95566  if( appendBias ){
95567    pik_flags |= OPFLAG_APPEND;
95568  }
95569  if( useSeekResult ){
95570    pik_flags |= OPFLAG_USESEEKRESULT;
95571  }
95572  sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
95573  if( !pParse->nested ){
95574    sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
95575  }
95576  sqlite3VdbeChangeP5(v, pik_flags);
95577}
95578
95579/*
95580** Allocate cursors for the pTab table and all its indices and generate
95581** code to open and initialized those cursors.
95582**
95583** The cursor for the object that contains the complete data (normally
95584** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
95585** ROWID table) is returned in *piDataCur.  The first index cursor is
95586** returned in *piIdxCur.  The number of indices is returned.
95587**
95588** Use iBase as the first cursor (either the *piDataCur for rowid tables
95589** or the first index for WITHOUT ROWID tables) if it is non-negative.
95590** If iBase is negative, then allocate the next available cursor.
95591**
95592** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
95593** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
95594** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
95595** pTab->pIndex list.
95596*/
95597SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
95598  Parse *pParse,   /* Parsing context */
95599  Table *pTab,     /* Table to be opened */
95600  int op,          /* OP_OpenRead or OP_OpenWrite */
95601  int iBase,       /* Use this for the table cursor, if there is one */
95602  u8 *aToOpen,     /* If not NULL: boolean for each table and index */
95603  int *piDataCur,  /* Write the database source cursor number here */
95604  int *piIdxCur    /* Write the first index cursor number here */
95605){
95606  int i;
95607  int iDb;
95608  int iDataCur;
95609  Index *pIdx;
95610  Vdbe *v;
95611
95612  assert( op==OP_OpenRead || op==OP_OpenWrite );
95613  if( IsVirtual(pTab) ){
95614    assert( aToOpen==0 );
95615    *piDataCur = 0;
95616    *piIdxCur = 1;
95617    return 0;
95618  }
95619  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
95620  v = sqlite3GetVdbe(pParse);
95621  assert( v!=0 );
95622  if( iBase<0 ) iBase = pParse->nTab;
95623  iDataCur = iBase++;
95624  if( piDataCur ) *piDataCur = iDataCur;
95625  if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
95626    sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
95627  }else{
95628    sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
95629  }
95630  if( piIdxCur ) *piIdxCur = iBase;
95631  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
95632    int iIdxCur = iBase++;
95633    assert( pIdx->pSchema==pTab->pSchema );
95634    if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) && piDataCur ){
95635      *piDataCur = iIdxCur;
95636    }
95637    if( aToOpen==0 || aToOpen[i+1] ){
95638      sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
95639      sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
95640      VdbeComment((v, "%s", pIdx->zName));
95641    }
95642  }
95643  if( iBase>pParse->nTab ) pParse->nTab = iBase;
95644  return i;
95645}
95646
95647
95648#ifdef SQLITE_TEST
95649/*
95650** The following global variable is incremented whenever the
95651** transfer optimization is used.  This is used for testing
95652** purposes only - to make sure the transfer optimization really
95653** is happening when it is suppose to.
95654*/
95655SQLITE_API int sqlite3_xferopt_count;
95656#endif /* SQLITE_TEST */
95657
95658
95659#ifndef SQLITE_OMIT_XFER_OPT
95660/*
95661** Check to collation names to see if they are compatible.
95662*/
95663static int xferCompatibleCollation(const char *z1, const char *z2){
95664  if( z1==0 ){
95665    return z2==0;
95666  }
95667  if( z2==0 ){
95668    return 0;
95669  }
95670  return sqlite3StrICmp(z1, z2)==0;
95671}
95672
95673
95674/*
95675** Check to see if index pSrc is compatible as a source of data
95676** for index pDest in an insert transfer optimization.  The rules
95677** for a compatible index:
95678**
95679**    *   The index is over the same set of columns
95680**    *   The same DESC and ASC markings occurs on all columns
95681**    *   The same onError processing (OE_Abort, OE_Ignore, etc)
95682**    *   The same collating sequence on each column
95683**    *   The index has the exact same WHERE clause
95684*/
95685static int xferCompatibleIndex(Index *pDest, Index *pSrc){
95686  int i;
95687  assert( pDest && pSrc );
95688  assert( pDest->pTable!=pSrc->pTable );
95689  if( pDest->nKeyCol!=pSrc->nKeyCol ){
95690    return 0;   /* Different number of columns */
95691  }
95692  if( pDest->onError!=pSrc->onError ){
95693    return 0;   /* Different conflict resolution strategies */
95694  }
95695  for(i=0; i<pSrc->nKeyCol; i++){
95696    if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
95697      return 0;   /* Different columns indexed */
95698    }
95699    if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
95700      return 0;   /* Different sort orders */
95701    }
95702    if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
95703      return 0;   /* Different collating sequences */
95704    }
95705  }
95706  if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
95707    return 0;     /* Different WHERE clauses */
95708  }
95709
95710  /* If no test above fails then the indices must be compatible */
95711  return 1;
95712}
95713
95714/*
95715** Attempt the transfer optimization on INSERTs of the form
95716**
95717**     INSERT INTO tab1 SELECT * FROM tab2;
95718**
95719** The xfer optimization transfers raw records from tab2 over to tab1.
95720** Columns are not decoded and reassemblied, which greatly improves
95721** performance.  Raw index records are transferred in the same way.
95722**
95723** The xfer optimization is only attempted if tab1 and tab2 are compatible.
95724** There are lots of rules for determining compatibility - see comments
95725** embedded in the code for details.
95726**
95727** This routine returns TRUE if the optimization is guaranteed to be used.
95728** Sometimes the xfer optimization will only work if the destination table
95729** is empty - a factor that can only be determined at run-time.  In that
95730** case, this routine generates code for the xfer optimization but also
95731** does a test to see if the destination table is empty and jumps over the
95732** xfer optimization code if the test fails.  In that case, this routine
95733** returns FALSE so that the caller will know to go ahead and generate
95734** an unoptimized transfer.  This routine also returns FALSE if there
95735** is no chance that the xfer optimization can be applied.
95736**
95737** This optimization is particularly useful at making VACUUM run faster.
95738*/
95739static int xferOptimization(
95740  Parse *pParse,        /* Parser context */
95741  Table *pDest,         /* The table we are inserting into */
95742  Select *pSelect,      /* A SELECT statement to use as the data source */
95743  int onError,          /* How to handle constraint errors */
95744  int iDbDest           /* The database of pDest */
95745){
95746  ExprList *pEList;                /* The result set of the SELECT */
95747  Table *pSrc;                     /* The table in the FROM clause of SELECT */
95748  Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
95749  struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
95750  int i;                           /* Loop counter */
95751  int iDbSrc;                      /* The database of pSrc */
95752  int iSrc, iDest;                 /* Cursors from source and destination */
95753  int addr1, addr2;                /* Loop addresses */
95754  int emptyDestTest = 0;           /* Address of test for empty pDest */
95755  int emptySrcTest = 0;            /* Address of test for empty pSrc */
95756  Vdbe *v;                         /* The VDBE we are building */
95757  int regAutoinc;                  /* Memory register used by AUTOINC */
95758  int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
95759  int regData, regRowid;           /* Registers holding data and rowid */
95760
95761  if( pSelect==0 ){
95762    return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
95763  }
95764  if( pParse->pWith || pSelect->pWith ){
95765    /* Do not attempt to process this query if there are an WITH clauses
95766    ** attached to it. Proceeding may generate a false "no such table: xxx"
95767    ** error if pSelect reads from a CTE named "xxx".  */
95768    return 0;
95769  }
95770  if( sqlite3TriggerList(pParse, pDest) ){
95771    return 0;   /* tab1 must not have triggers */
95772  }
95773#ifndef SQLITE_OMIT_VIRTUALTABLE
95774  if( pDest->tabFlags & TF_Virtual ){
95775    return 0;   /* tab1 must not be a virtual table */
95776  }
95777#endif
95778  if( onError==OE_Default ){
95779    if( pDest->iPKey>=0 ) onError = pDest->keyConf;
95780    if( onError==OE_Default ) onError = OE_Abort;
95781  }
95782  assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
95783  if( pSelect->pSrc->nSrc!=1 ){
95784    return 0;   /* FROM clause must have exactly one term */
95785  }
95786  if( pSelect->pSrc->a[0].pSelect ){
95787    return 0;   /* FROM clause cannot contain a subquery */
95788  }
95789  if( pSelect->pWhere ){
95790    return 0;   /* SELECT may not have a WHERE clause */
95791  }
95792  if( pSelect->pOrderBy ){
95793    return 0;   /* SELECT may not have an ORDER BY clause */
95794  }
95795  /* Do not need to test for a HAVING clause.  If HAVING is present but
95796  ** there is no ORDER BY, we will get an error. */
95797  if( pSelect->pGroupBy ){
95798    return 0;   /* SELECT may not have a GROUP BY clause */
95799  }
95800  if( pSelect->pLimit ){
95801    return 0;   /* SELECT may not have a LIMIT clause */
95802  }
95803  assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
95804  if( pSelect->pPrior ){
95805    return 0;   /* SELECT may not be a compound query */
95806  }
95807  if( pSelect->selFlags & SF_Distinct ){
95808    return 0;   /* SELECT may not be DISTINCT */
95809  }
95810  pEList = pSelect->pEList;
95811  assert( pEList!=0 );
95812  if( pEList->nExpr!=1 ){
95813    return 0;   /* The result set must have exactly one column */
95814  }
95815  assert( pEList->a[0].pExpr );
95816  if( pEList->a[0].pExpr->op!=TK_ALL ){
95817    return 0;   /* The result set must be the special operator "*" */
95818  }
95819
95820  /* At this point we have established that the statement is of the
95821  ** correct syntactic form to participate in this optimization.  Now
95822  ** we have to check the semantics.
95823  */
95824  pItem = pSelect->pSrc->a;
95825  pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
95826  if( pSrc==0 ){
95827    return 0;   /* FROM clause does not contain a real table */
95828  }
95829  if( pSrc==pDest ){
95830    return 0;   /* tab1 and tab2 may not be the same table */
95831  }
95832  if( HasRowid(pDest)!=HasRowid(pSrc) ){
95833    return 0;   /* source and destination must both be WITHOUT ROWID or not */
95834  }
95835#ifndef SQLITE_OMIT_VIRTUALTABLE
95836  if( pSrc->tabFlags & TF_Virtual ){
95837    return 0;   /* tab2 must not be a virtual table */
95838  }
95839#endif
95840  if( pSrc->pSelect ){
95841    return 0;   /* tab2 may not be a view */
95842  }
95843  if( pDest->nCol!=pSrc->nCol ){
95844    return 0;   /* Number of columns must be the same in tab1 and tab2 */
95845  }
95846  if( pDest->iPKey!=pSrc->iPKey ){
95847    return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
95848  }
95849  for(i=0; i<pDest->nCol; i++){
95850    Column *pDestCol = &pDest->aCol[i];
95851    Column *pSrcCol = &pSrc->aCol[i];
95852    if( pDestCol->affinity!=pSrcCol->affinity ){
95853      return 0;    /* Affinity must be the same on all columns */
95854    }
95855    if( !xferCompatibleCollation(pDestCol->zColl, pSrcCol->zColl) ){
95856      return 0;    /* Collating sequence must be the same on all columns */
95857    }
95858    if( pDestCol->notNull && !pSrcCol->notNull ){
95859      return 0;    /* tab2 must be NOT NULL if tab1 is */
95860    }
95861    /* Default values for second and subsequent columns need to match. */
95862    if( i>0
95863     && ((pDestCol->zDflt==0)!=(pSrcCol->zDflt==0)
95864         || (pDestCol->zDflt && strcmp(pDestCol->zDflt, pSrcCol->zDflt)!=0))
95865    ){
95866      return 0;    /* Default values must be the same for all columns */
95867    }
95868  }
95869  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
95870    if( pDestIdx->onError!=OE_None ){
95871      destHasUniqueIdx = 1;
95872    }
95873    for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
95874      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
95875    }
95876    if( pSrcIdx==0 ){
95877      return 0;    /* pDestIdx has no corresponding index in pSrc */
95878    }
95879  }
95880#ifndef SQLITE_OMIT_CHECK
95881  if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
95882    return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
95883  }
95884#endif
95885#ifndef SQLITE_OMIT_FOREIGN_KEY
95886  /* Disallow the transfer optimization if the destination table constains
95887  ** any foreign key constraints.  This is more restrictive than necessary.
95888  ** But the main beneficiary of the transfer optimization is the VACUUM
95889  ** command, and the VACUUM command disables foreign key constraints.  So
95890  ** the extra complication to make this rule less restrictive is probably
95891  ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
95892  */
95893  if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
95894    return 0;
95895  }
95896#endif
95897  if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
95898    return 0;  /* xfer opt does not play well with PRAGMA count_changes */
95899  }
95900
95901  /* If we get this far, it means that the xfer optimization is at
95902  ** least a possibility, though it might only work if the destination
95903  ** table (tab1) is initially empty.
95904  */
95905#ifdef SQLITE_TEST
95906  sqlite3_xferopt_count++;
95907#endif
95908  iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
95909  v = sqlite3GetVdbe(pParse);
95910  sqlite3CodeVerifySchema(pParse, iDbSrc);
95911  iSrc = pParse->nTab++;
95912  iDest = pParse->nTab++;
95913  regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
95914  regData = sqlite3GetTempReg(pParse);
95915  regRowid = sqlite3GetTempReg(pParse);
95916  sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
95917  assert( HasRowid(pDest) || destHasUniqueIdx );
95918  if( (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
95919   || destHasUniqueIdx                              /* (2) */
95920   || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
95921  ){
95922    /* In some circumstances, we are able to run the xfer optimization
95923    ** only if the destination table is initially empty.  This code makes
95924    ** that determination.  Conditions under which the destination must
95925    ** be empty:
95926    **
95927    ** (1) There is no INTEGER PRIMARY KEY but there are indices.
95928    **     (If the destination is not initially empty, the rowid fields
95929    **     of index entries might need to change.)
95930    **
95931    ** (2) The destination has a unique index.  (The xfer optimization
95932    **     is unable to test uniqueness.)
95933    **
95934    ** (3) onError is something other than OE_Abort and OE_Rollback.
95935    */
95936    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
95937    emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
95938    sqlite3VdbeJumpHere(v, addr1);
95939  }
95940  if( HasRowid(pSrc) ){
95941    sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
95942    emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
95943    if( pDest->iPKey>=0 ){
95944      addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
95945      addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
95946      VdbeCoverage(v);
95947      sqlite3RowidConstraint(pParse, onError, pDest);
95948      sqlite3VdbeJumpHere(v, addr2);
95949      autoIncStep(pParse, regAutoinc, regRowid);
95950    }else if( pDest->pIndex==0 ){
95951      addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
95952    }else{
95953      addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
95954      assert( (pDest->tabFlags & TF_Autoincrement)==0 );
95955    }
95956    sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
95957    sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
95958    sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
95959    sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
95960    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
95961    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
95962    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
95963  }else{
95964    sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
95965    sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
95966  }
95967  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
95968    for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
95969      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
95970    }
95971    assert( pSrcIdx );
95972    sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
95973    sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
95974    VdbeComment((v, "%s", pSrcIdx->zName));
95975    sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
95976    sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
95977    sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
95978    VdbeComment((v, "%s", pDestIdx->zName));
95979    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
95980    sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
95981    sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
95982    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
95983    sqlite3VdbeJumpHere(v, addr1);
95984    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
95985    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
95986  }
95987  if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
95988  sqlite3ReleaseTempReg(pParse, regRowid);
95989  sqlite3ReleaseTempReg(pParse, regData);
95990  if( emptyDestTest ){
95991    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
95992    sqlite3VdbeJumpHere(v, emptyDestTest);
95993    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
95994    return 0;
95995  }else{
95996    return 1;
95997  }
95998}
95999#endif /* SQLITE_OMIT_XFER_OPT */
96000
96001/************** End of insert.c **********************************************/
96002/************** Begin file legacy.c ******************************************/
96003/*
96004** 2001 September 15
96005**
96006** The author disclaims copyright to this source code.  In place of
96007** a legal notice, here is a blessing:
96008**
96009**    May you do good and not evil.
96010**    May you find forgiveness for yourself and forgive others.
96011**    May you share freely, never taking more than you give.
96012**
96013*************************************************************************
96014** Main file for the SQLite library.  The routines in this file
96015** implement the programmer interface to the library.  Routines in
96016** other files are for internal use by SQLite and should not be
96017** accessed by users of the library.
96018*/
96019
96020
96021/*
96022** Execute SQL code.  Return one of the SQLITE_ success/failure
96023** codes.  Also write an error message into memory obtained from
96024** malloc() and make *pzErrMsg point to that message.
96025**
96026** If the SQL is a query, then for each row in the query result
96027** the xCallback() function is called.  pArg becomes the first
96028** argument to xCallback().  If xCallback=NULL then no callback
96029** is invoked, even for queries.
96030*/
96031SQLITE_API int sqlite3_exec(
96032  sqlite3 *db,                /* The database on which the SQL executes */
96033  const char *zSql,           /* The SQL to be executed */
96034  sqlite3_callback xCallback, /* Invoke this callback routine */
96035  void *pArg,                 /* First argument to xCallback() */
96036  char **pzErrMsg             /* Write error messages here */
96037){
96038  int rc = SQLITE_OK;         /* Return code */
96039  const char *zLeftover;      /* Tail of unprocessed SQL */
96040  sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
96041  char **azCols = 0;          /* Names of result columns */
96042  int callbackIsInit;         /* True if callback data is initialized */
96043
96044  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
96045  if( zSql==0 ) zSql = "";
96046
96047  sqlite3_mutex_enter(db->mutex);
96048  sqlite3Error(db, SQLITE_OK, 0);
96049  while( rc==SQLITE_OK && zSql[0] ){
96050    int nCol;
96051    char **azVals = 0;
96052
96053    pStmt = 0;
96054    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
96055    assert( rc==SQLITE_OK || pStmt==0 );
96056    if( rc!=SQLITE_OK ){
96057      continue;
96058    }
96059    if( !pStmt ){
96060      /* this happens for a comment or white-space */
96061      zSql = zLeftover;
96062      continue;
96063    }
96064
96065    callbackIsInit = 0;
96066    nCol = sqlite3_column_count(pStmt);
96067
96068    while( 1 ){
96069      int i;
96070      rc = sqlite3_step(pStmt);
96071
96072      /* Invoke the callback function if required */
96073      if( xCallback && (SQLITE_ROW==rc ||
96074          (SQLITE_DONE==rc && !callbackIsInit
96075                           && db->flags&SQLITE_NullCallback)) ){
96076        if( !callbackIsInit ){
96077          azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
96078          if( azCols==0 ){
96079            goto exec_out;
96080          }
96081          for(i=0; i<nCol; i++){
96082            azCols[i] = (char *)sqlite3_column_name(pStmt, i);
96083            /* sqlite3VdbeSetColName() installs column names as UTF8
96084            ** strings so there is no way for sqlite3_column_name() to fail. */
96085            assert( azCols[i]!=0 );
96086          }
96087          callbackIsInit = 1;
96088        }
96089        if( rc==SQLITE_ROW ){
96090          azVals = &azCols[nCol];
96091          for(i=0; i<nCol; i++){
96092            azVals[i] = (char *)sqlite3_column_text(pStmt, i);
96093            if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
96094              db->mallocFailed = 1;
96095              goto exec_out;
96096            }
96097          }
96098        }
96099        if( xCallback(pArg, nCol, azVals, azCols) ){
96100          rc = SQLITE_ABORT;
96101          sqlite3VdbeFinalize((Vdbe *)pStmt);
96102          pStmt = 0;
96103          sqlite3Error(db, SQLITE_ABORT, 0);
96104          goto exec_out;
96105        }
96106      }
96107
96108      if( rc!=SQLITE_ROW ){
96109        rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
96110        pStmt = 0;
96111        zSql = zLeftover;
96112        while( sqlite3Isspace(zSql[0]) ) zSql++;
96113        break;
96114      }
96115    }
96116
96117    sqlite3DbFree(db, azCols);
96118    azCols = 0;
96119  }
96120
96121exec_out:
96122  if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
96123  sqlite3DbFree(db, azCols);
96124
96125  rc = sqlite3ApiExit(db, rc);
96126  if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
96127    int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
96128    *pzErrMsg = sqlite3Malloc(nErrMsg);
96129    if( *pzErrMsg ){
96130      memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
96131    }else{
96132      rc = SQLITE_NOMEM;
96133      sqlite3Error(db, SQLITE_NOMEM, 0);
96134    }
96135  }else if( pzErrMsg ){
96136    *pzErrMsg = 0;
96137  }
96138
96139  assert( (rc&db->errMask)==rc );
96140  sqlite3_mutex_leave(db->mutex);
96141  return rc;
96142}
96143
96144/************** End of legacy.c **********************************************/
96145/************** Begin file loadext.c *****************************************/
96146/*
96147** 2006 June 7
96148**
96149** The author disclaims copyright to this source code.  In place of
96150** a legal notice, here is a blessing:
96151**
96152**    May you do good and not evil.
96153**    May you find forgiveness for yourself and forgive others.
96154**    May you share freely, never taking more than you give.
96155**
96156*************************************************************************
96157** This file contains code used to dynamically load extensions into
96158** the SQLite library.
96159*/
96160
96161#ifndef SQLITE_CORE
96162  #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
96163#endif
96164/************** Include sqlite3ext.h in the middle of loadext.c **************/
96165/************** Begin file sqlite3ext.h **************************************/
96166/*
96167** 2006 June 7
96168**
96169** The author disclaims copyright to this source code.  In place of
96170** a legal notice, here is a blessing:
96171**
96172**    May you do good and not evil.
96173**    May you find forgiveness for yourself and forgive others.
96174**    May you share freely, never taking more than you give.
96175**
96176*************************************************************************
96177** This header file defines the SQLite interface for use by
96178** shared libraries that want to be imported as extensions into
96179** an SQLite instance.  Shared libraries that intend to be loaded
96180** as extensions by SQLite should #include this file instead of
96181** sqlite3.h.
96182*/
96183#ifndef _SQLITE3EXT_H_
96184#define _SQLITE3EXT_H_
96185
96186typedef struct sqlite3_api_routines sqlite3_api_routines;
96187
96188/*
96189** The following structure holds pointers to all of the SQLite API
96190** routines.
96191**
96192** WARNING:  In order to maintain backwards compatibility, add new
96193** interfaces to the end of this structure only.  If you insert new
96194** interfaces in the middle of this structure, then older different
96195** versions of SQLite will not be able to load each others' shared
96196** libraries!
96197*/
96198struct sqlite3_api_routines {
96199  void * (*aggregate_context)(sqlite3_context*,int nBytes);
96200  int  (*aggregate_count)(sqlite3_context*);
96201  int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
96202  int  (*bind_double)(sqlite3_stmt*,int,double);
96203  int  (*bind_int)(sqlite3_stmt*,int,int);
96204  int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
96205  int  (*bind_null)(sqlite3_stmt*,int);
96206  int  (*bind_parameter_count)(sqlite3_stmt*);
96207  int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
96208  const char * (*bind_parameter_name)(sqlite3_stmt*,int);
96209  int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
96210  int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
96211  int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
96212  int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
96213  int  (*busy_timeout)(sqlite3*,int ms);
96214  int  (*changes)(sqlite3*);
96215  int  (*close)(sqlite3*);
96216  int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
96217                           int eTextRep,const char*));
96218  int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
96219                             int eTextRep,const void*));
96220  const void * (*column_blob)(sqlite3_stmt*,int iCol);
96221  int  (*column_bytes)(sqlite3_stmt*,int iCol);
96222  int  (*column_bytes16)(sqlite3_stmt*,int iCol);
96223  int  (*column_count)(sqlite3_stmt*pStmt);
96224  const char * (*column_database_name)(sqlite3_stmt*,int);
96225  const void * (*column_database_name16)(sqlite3_stmt*,int);
96226  const char * (*column_decltype)(sqlite3_stmt*,int i);
96227  const void * (*column_decltype16)(sqlite3_stmt*,int);
96228  double  (*column_double)(sqlite3_stmt*,int iCol);
96229  int  (*column_int)(sqlite3_stmt*,int iCol);
96230  sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
96231  const char * (*column_name)(sqlite3_stmt*,int);
96232  const void * (*column_name16)(sqlite3_stmt*,int);
96233  const char * (*column_origin_name)(sqlite3_stmt*,int);
96234  const void * (*column_origin_name16)(sqlite3_stmt*,int);
96235  const char * (*column_table_name)(sqlite3_stmt*,int);
96236  const void * (*column_table_name16)(sqlite3_stmt*,int);
96237  const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
96238  const void * (*column_text16)(sqlite3_stmt*,int iCol);
96239  int  (*column_type)(sqlite3_stmt*,int iCol);
96240  sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
96241  void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
96242  int  (*complete)(const char*sql);
96243  int  (*complete16)(const void*sql);
96244  int  (*create_collation)(sqlite3*,const char*,int,void*,
96245                           int(*)(void*,int,const void*,int,const void*));
96246  int  (*create_collation16)(sqlite3*,const void*,int,void*,
96247                             int(*)(void*,int,const void*,int,const void*));
96248  int  (*create_function)(sqlite3*,const char*,int,int,void*,
96249                          void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
96250                          void (*xStep)(sqlite3_context*,int,sqlite3_value**),
96251                          void (*xFinal)(sqlite3_context*));
96252  int  (*create_function16)(sqlite3*,const void*,int,int,void*,
96253                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
96254                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
96255                            void (*xFinal)(sqlite3_context*));
96256  int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
96257  int  (*data_count)(sqlite3_stmt*pStmt);
96258  sqlite3 * (*db_handle)(sqlite3_stmt*);
96259  int (*declare_vtab)(sqlite3*,const char*);
96260  int  (*enable_shared_cache)(int);
96261  int  (*errcode)(sqlite3*db);
96262  const char * (*errmsg)(sqlite3*);
96263  const void * (*errmsg16)(sqlite3*);
96264  int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
96265  int  (*expired)(sqlite3_stmt*);
96266  int  (*finalize)(sqlite3_stmt*pStmt);
96267  void  (*free)(void*);
96268  void  (*free_table)(char**result);
96269  int  (*get_autocommit)(sqlite3*);
96270  void * (*get_auxdata)(sqlite3_context*,int);
96271  int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
96272  int  (*global_recover)(void);
96273  void  (*interruptx)(sqlite3*);
96274  sqlite_int64  (*last_insert_rowid)(sqlite3*);
96275  const char * (*libversion)(void);
96276  int  (*libversion_number)(void);
96277  void *(*malloc)(int);
96278  char * (*mprintf)(const char*,...);
96279  int  (*open)(const char*,sqlite3**);
96280  int  (*open16)(const void*,sqlite3**);
96281  int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
96282  int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
96283  void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
96284  void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
96285  void *(*realloc)(void*,int);
96286  int  (*reset)(sqlite3_stmt*pStmt);
96287  void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
96288  void  (*result_double)(sqlite3_context*,double);
96289  void  (*result_error)(sqlite3_context*,const char*,int);
96290  void  (*result_error16)(sqlite3_context*,const void*,int);
96291  void  (*result_int)(sqlite3_context*,int);
96292  void  (*result_int64)(sqlite3_context*,sqlite_int64);
96293  void  (*result_null)(sqlite3_context*);
96294  void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
96295  void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
96296  void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
96297  void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
96298  void  (*result_value)(sqlite3_context*,sqlite3_value*);
96299  void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
96300  int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
96301                         const char*,const char*),void*);
96302  void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
96303  char * (*snprintf)(int,char*,const char*,...);
96304  int  (*step)(sqlite3_stmt*);
96305  int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
96306                                char const**,char const**,int*,int*,int*);
96307  void  (*thread_cleanup)(void);
96308  int  (*total_changes)(sqlite3*);
96309  void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
96310  int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
96311  void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
96312                                         sqlite_int64),void*);
96313  void * (*user_data)(sqlite3_context*);
96314  const void * (*value_blob)(sqlite3_value*);
96315  int  (*value_bytes)(sqlite3_value*);
96316  int  (*value_bytes16)(sqlite3_value*);
96317  double  (*value_double)(sqlite3_value*);
96318  int  (*value_int)(sqlite3_value*);
96319  sqlite_int64  (*value_int64)(sqlite3_value*);
96320  int  (*value_numeric_type)(sqlite3_value*);
96321  const unsigned char * (*value_text)(sqlite3_value*);
96322  const void * (*value_text16)(sqlite3_value*);
96323  const void * (*value_text16be)(sqlite3_value*);
96324  const void * (*value_text16le)(sqlite3_value*);
96325  int  (*value_type)(sqlite3_value*);
96326  char *(*vmprintf)(const char*,va_list);
96327  /* Added ??? */
96328  int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
96329  /* Added by 3.3.13 */
96330  int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
96331  int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
96332  int (*clear_bindings)(sqlite3_stmt*);
96333  /* Added by 3.4.1 */
96334  int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
96335                          void (*xDestroy)(void *));
96336  /* Added by 3.5.0 */
96337  int (*bind_zeroblob)(sqlite3_stmt*,int,int);
96338  int (*blob_bytes)(sqlite3_blob*);
96339  int (*blob_close)(sqlite3_blob*);
96340  int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
96341                   int,sqlite3_blob**);
96342  int (*blob_read)(sqlite3_blob*,void*,int,int);
96343  int (*blob_write)(sqlite3_blob*,const void*,int,int);
96344  int (*create_collation_v2)(sqlite3*,const char*,int,void*,
96345                             int(*)(void*,int,const void*,int,const void*),
96346                             void(*)(void*));
96347  int (*file_control)(sqlite3*,const char*,int,void*);
96348  sqlite3_int64 (*memory_highwater)(int);
96349  sqlite3_int64 (*memory_used)(void);
96350  sqlite3_mutex *(*mutex_alloc)(int);
96351  void (*mutex_enter)(sqlite3_mutex*);
96352  void (*mutex_free)(sqlite3_mutex*);
96353  void (*mutex_leave)(sqlite3_mutex*);
96354  int (*mutex_try)(sqlite3_mutex*);
96355  int (*open_v2)(const char*,sqlite3**,int,const char*);
96356  int (*release_memory)(int);
96357  void (*result_error_nomem)(sqlite3_context*);
96358  void (*result_error_toobig)(sqlite3_context*);
96359  int (*sleep)(int);
96360  void (*soft_heap_limit)(int);
96361  sqlite3_vfs *(*vfs_find)(const char*);
96362  int (*vfs_register)(sqlite3_vfs*,int);
96363  int (*vfs_unregister)(sqlite3_vfs*);
96364  int (*xthreadsafe)(void);
96365  void (*result_zeroblob)(sqlite3_context*,int);
96366  void (*result_error_code)(sqlite3_context*,int);
96367  int (*test_control)(int, ...);
96368  void (*randomness)(int,void*);
96369  sqlite3 *(*context_db_handle)(sqlite3_context*);
96370  int (*extended_result_codes)(sqlite3*,int);
96371  int (*limit)(sqlite3*,int,int);
96372  sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
96373  const char *(*sql)(sqlite3_stmt*);
96374  int (*status)(int,int*,int*,int);
96375  int (*backup_finish)(sqlite3_backup*);
96376  sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
96377  int (*backup_pagecount)(sqlite3_backup*);
96378  int (*backup_remaining)(sqlite3_backup*);
96379  int (*backup_step)(sqlite3_backup*,int);
96380  const char *(*compileoption_get)(int);
96381  int (*compileoption_used)(const char*);
96382  int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
96383                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
96384                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
96385                            void (*xFinal)(sqlite3_context*),
96386                            void(*xDestroy)(void*));
96387  int (*db_config)(sqlite3*,int,...);
96388  sqlite3_mutex *(*db_mutex)(sqlite3*);
96389  int (*db_status)(sqlite3*,int,int*,int*,int);
96390  int (*extended_errcode)(sqlite3*);
96391  void (*log)(int,const char*,...);
96392  sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
96393  const char *(*sourceid)(void);
96394  int (*stmt_status)(sqlite3_stmt*,int,int);
96395  int (*strnicmp)(const char*,const char*,int);
96396  int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
96397  int (*wal_autocheckpoint)(sqlite3*,int);
96398  int (*wal_checkpoint)(sqlite3*,const char*);
96399  void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
96400  int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
96401  int (*vtab_config)(sqlite3*,int op,...);
96402  int (*vtab_on_conflict)(sqlite3*);
96403  /* Version 3.7.16 and later */
96404  int (*close_v2)(sqlite3*);
96405  const char *(*db_filename)(sqlite3*,const char*);
96406  int (*db_readonly)(sqlite3*,const char*);
96407  int (*db_release_memory)(sqlite3*);
96408  const char *(*errstr)(int);
96409  int (*stmt_busy)(sqlite3_stmt*);
96410  int (*stmt_readonly)(sqlite3_stmt*);
96411  int (*stricmp)(const char*,const char*);
96412  int (*uri_boolean)(const char*,const char*,int);
96413  sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
96414  const char *(*uri_parameter)(const char*,const char*);
96415  char *(*vsnprintf)(int,char*,const char*,va_list);
96416  int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
96417};
96418
96419/*
96420** The following macros redefine the API routines so that they are
96421** redirected throught the global sqlite3_api structure.
96422**
96423** This header file is also used by the loadext.c source file
96424** (part of the main SQLite library - not an extension) so that
96425** it can get access to the sqlite3_api_routines structure
96426** definition.  But the main library does not want to redefine
96427** the API.  So the redefinition macros are only valid if the
96428** SQLITE_CORE macros is undefined.
96429*/
96430#ifndef SQLITE_CORE
96431#define sqlite3_aggregate_context      sqlite3_api->aggregate_context
96432#ifndef SQLITE_OMIT_DEPRECATED
96433#define sqlite3_aggregate_count        sqlite3_api->aggregate_count
96434#endif
96435#define sqlite3_bind_blob              sqlite3_api->bind_blob
96436#define sqlite3_bind_double            sqlite3_api->bind_double
96437#define sqlite3_bind_int               sqlite3_api->bind_int
96438#define sqlite3_bind_int64             sqlite3_api->bind_int64
96439#define sqlite3_bind_null              sqlite3_api->bind_null
96440#define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
96441#define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
96442#define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
96443#define sqlite3_bind_text              sqlite3_api->bind_text
96444#define sqlite3_bind_text16            sqlite3_api->bind_text16
96445#define sqlite3_bind_value             sqlite3_api->bind_value
96446#define sqlite3_busy_handler           sqlite3_api->busy_handler
96447#define sqlite3_busy_timeout           sqlite3_api->busy_timeout
96448#define sqlite3_changes                sqlite3_api->changes
96449#define sqlite3_close                  sqlite3_api->close
96450#define sqlite3_collation_needed       sqlite3_api->collation_needed
96451#define sqlite3_collation_needed16     sqlite3_api->collation_needed16
96452#define sqlite3_column_blob            sqlite3_api->column_blob
96453#define sqlite3_column_bytes           sqlite3_api->column_bytes
96454#define sqlite3_column_bytes16         sqlite3_api->column_bytes16
96455#define sqlite3_column_count           sqlite3_api->column_count
96456#define sqlite3_column_database_name   sqlite3_api->column_database_name
96457#define sqlite3_column_database_name16 sqlite3_api->column_database_name16
96458#define sqlite3_column_decltype        sqlite3_api->column_decltype
96459#define sqlite3_column_decltype16      sqlite3_api->column_decltype16
96460#define sqlite3_column_double          sqlite3_api->column_double
96461#define sqlite3_column_int             sqlite3_api->column_int
96462#define sqlite3_column_int64           sqlite3_api->column_int64
96463#define sqlite3_column_name            sqlite3_api->column_name
96464#define sqlite3_column_name16          sqlite3_api->column_name16
96465#define sqlite3_column_origin_name     sqlite3_api->column_origin_name
96466#define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
96467#define sqlite3_column_table_name      sqlite3_api->column_table_name
96468#define sqlite3_column_table_name16    sqlite3_api->column_table_name16
96469#define sqlite3_column_text            sqlite3_api->column_text
96470#define sqlite3_column_text16          sqlite3_api->column_text16
96471#define sqlite3_column_type            sqlite3_api->column_type
96472#define sqlite3_column_value           sqlite3_api->column_value
96473#define sqlite3_commit_hook            sqlite3_api->commit_hook
96474#define sqlite3_complete               sqlite3_api->complete
96475#define sqlite3_complete16             sqlite3_api->complete16
96476#define sqlite3_create_collation       sqlite3_api->create_collation
96477#define sqlite3_create_collation16     sqlite3_api->create_collation16
96478#define sqlite3_create_function        sqlite3_api->create_function
96479#define sqlite3_create_function16      sqlite3_api->create_function16
96480#define sqlite3_create_module          sqlite3_api->create_module
96481#define sqlite3_create_module_v2       sqlite3_api->create_module_v2
96482#define sqlite3_data_count             sqlite3_api->data_count
96483#define sqlite3_db_handle              sqlite3_api->db_handle
96484#define sqlite3_declare_vtab           sqlite3_api->declare_vtab
96485#define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
96486#define sqlite3_errcode                sqlite3_api->errcode
96487#define sqlite3_errmsg                 sqlite3_api->errmsg
96488#define sqlite3_errmsg16               sqlite3_api->errmsg16
96489#define sqlite3_exec                   sqlite3_api->exec
96490#ifndef SQLITE_OMIT_DEPRECATED
96491#define sqlite3_expired                sqlite3_api->expired
96492#endif
96493#define sqlite3_finalize               sqlite3_api->finalize
96494#define sqlite3_free                   sqlite3_api->free
96495#define sqlite3_free_table             sqlite3_api->free_table
96496#define sqlite3_get_autocommit         sqlite3_api->get_autocommit
96497#define sqlite3_get_auxdata            sqlite3_api->get_auxdata
96498#define sqlite3_get_table              sqlite3_api->get_table
96499#ifndef SQLITE_OMIT_DEPRECATED
96500#define sqlite3_global_recover         sqlite3_api->global_recover
96501#endif
96502#define sqlite3_interrupt              sqlite3_api->interruptx
96503#define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
96504#define sqlite3_libversion             sqlite3_api->libversion
96505#define sqlite3_libversion_number      sqlite3_api->libversion_number
96506#define sqlite3_malloc                 sqlite3_api->malloc
96507#define sqlite3_mprintf                sqlite3_api->mprintf
96508#define sqlite3_open                   sqlite3_api->open
96509#define sqlite3_open16                 sqlite3_api->open16
96510#define sqlite3_prepare                sqlite3_api->prepare
96511#define sqlite3_prepare16              sqlite3_api->prepare16
96512#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
96513#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
96514#define sqlite3_profile                sqlite3_api->profile
96515#define sqlite3_progress_handler       sqlite3_api->progress_handler
96516#define sqlite3_realloc                sqlite3_api->realloc
96517#define sqlite3_reset                  sqlite3_api->reset
96518#define sqlite3_result_blob            sqlite3_api->result_blob
96519#define sqlite3_result_double          sqlite3_api->result_double
96520#define sqlite3_result_error           sqlite3_api->result_error
96521#define sqlite3_result_error16         sqlite3_api->result_error16
96522#define sqlite3_result_int             sqlite3_api->result_int
96523#define sqlite3_result_int64           sqlite3_api->result_int64
96524#define sqlite3_result_null            sqlite3_api->result_null
96525#define sqlite3_result_text            sqlite3_api->result_text
96526#define sqlite3_result_text16          sqlite3_api->result_text16
96527#define sqlite3_result_text16be        sqlite3_api->result_text16be
96528#define sqlite3_result_text16le        sqlite3_api->result_text16le
96529#define sqlite3_result_value           sqlite3_api->result_value
96530#define sqlite3_rollback_hook          sqlite3_api->rollback_hook
96531#define sqlite3_set_authorizer         sqlite3_api->set_authorizer
96532#define sqlite3_set_auxdata            sqlite3_api->set_auxdata
96533#define sqlite3_snprintf               sqlite3_api->snprintf
96534#define sqlite3_step                   sqlite3_api->step
96535#define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
96536#define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
96537#define sqlite3_total_changes          sqlite3_api->total_changes
96538#define sqlite3_trace                  sqlite3_api->trace
96539#ifndef SQLITE_OMIT_DEPRECATED
96540#define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
96541#endif
96542#define sqlite3_update_hook            sqlite3_api->update_hook
96543#define sqlite3_user_data              sqlite3_api->user_data
96544#define sqlite3_value_blob             sqlite3_api->value_blob
96545#define sqlite3_value_bytes            sqlite3_api->value_bytes
96546#define sqlite3_value_bytes16          sqlite3_api->value_bytes16
96547#define sqlite3_value_double           sqlite3_api->value_double
96548#define sqlite3_value_int              sqlite3_api->value_int
96549#define sqlite3_value_int64            sqlite3_api->value_int64
96550#define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
96551#define sqlite3_value_text             sqlite3_api->value_text
96552#define sqlite3_value_text16           sqlite3_api->value_text16
96553#define sqlite3_value_text16be         sqlite3_api->value_text16be
96554#define sqlite3_value_text16le         sqlite3_api->value_text16le
96555#define sqlite3_value_type             sqlite3_api->value_type
96556#define sqlite3_vmprintf               sqlite3_api->vmprintf
96557#define sqlite3_overload_function      sqlite3_api->overload_function
96558#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
96559#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
96560#define sqlite3_clear_bindings         sqlite3_api->clear_bindings
96561#define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
96562#define sqlite3_blob_bytes             sqlite3_api->blob_bytes
96563#define sqlite3_blob_close             sqlite3_api->blob_close
96564#define sqlite3_blob_open              sqlite3_api->blob_open
96565#define sqlite3_blob_read              sqlite3_api->blob_read
96566#define sqlite3_blob_write             sqlite3_api->blob_write
96567#define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
96568#define sqlite3_file_control           sqlite3_api->file_control
96569#define sqlite3_memory_highwater       sqlite3_api->memory_highwater
96570#define sqlite3_memory_used            sqlite3_api->memory_used
96571#define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
96572#define sqlite3_mutex_enter            sqlite3_api->mutex_enter
96573#define sqlite3_mutex_free             sqlite3_api->mutex_free
96574#define sqlite3_mutex_leave            sqlite3_api->mutex_leave
96575#define sqlite3_mutex_try              sqlite3_api->mutex_try
96576#define sqlite3_open_v2                sqlite3_api->open_v2
96577#define sqlite3_release_memory         sqlite3_api->release_memory
96578#define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
96579#define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
96580#define sqlite3_sleep                  sqlite3_api->sleep
96581#define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
96582#define sqlite3_vfs_find               sqlite3_api->vfs_find
96583#define sqlite3_vfs_register           sqlite3_api->vfs_register
96584#define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
96585#define sqlite3_threadsafe             sqlite3_api->xthreadsafe
96586#define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
96587#define sqlite3_result_error_code      sqlite3_api->result_error_code
96588#define sqlite3_test_control           sqlite3_api->test_control
96589#define sqlite3_randomness             sqlite3_api->randomness
96590#define sqlite3_context_db_handle      sqlite3_api->context_db_handle
96591#define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
96592#define sqlite3_limit                  sqlite3_api->limit
96593#define sqlite3_next_stmt              sqlite3_api->next_stmt
96594#define sqlite3_sql                    sqlite3_api->sql
96595#define sqlite3_status                 sqlite3_api->status
96596#define sqlite3_backup_finish          sqlite3_api->backup_finish
96597#define sqlite3_backup_init            sqlite3_api->backup_init
96598#define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
96599#define sqlite3_backup_remaining       sqlite3_api->backup_remaining
96600#define sqlite3_backup_step            sqlite3_api->backup_step
96601#define sqlite3_compileoption_get      sqlite3_api->compileoption_get
96602#define sqlite3_compileoption_used     sqlite3_api->compileoption_used
96603#define sqlite3_create_function_v2     sqlite3_api->create_function_v2
96604#define sqlite3_db_config              sqlite3_api->db_config
96605#define sqlite3_db_mutex               sqlite3_api->db_mutex
96606#define sqlite3_db_status              sqlite3_api->db_status
96607#define sqlite3_extended_errcode       sqlite3_api->extended_errcode
96608#define sqlite3_log                    sqlite3_api->log
96609#define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
96610#define sqlite3_sourceid               sqlite3_api->sourceid
96611#define sqlite3_stmt_status            sqlite3_api->stmt_status
96612#define sqlite3_strnicmp               sqlite3_api->strnicmp
96613#define sqlite3_unlock_notify          sqlite3_api->unlock_notify
96614#define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
96615#define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
96616#define sqlite3_wal_hook               sqlite3_api->wal_hook
96617#define sqlite3_blob_reopen            sqlite3_api->blob_reopen
96618#define sqlite3_vtab_config            sqlite3_api->vtab_config
96619#define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
96620/* Version 3.7.16 and later */
96621#define sqlite3_close_v2               sqlite3_api->close_v2
96622#define sqlite3_db_filename            sqlite3_api->db_filename
96623#define sqlite3_db_readonly            sqlite3_api->db_readonly
96624#define sqlite3_db_release_memory      sqlite3_api->db_release_memory
96625#define sqlite3_errstr                 sqlite3_api->errstr
96626#define sqlite3_stmt_busy              sqlite3_api->stmt_busy
96627#define sqlite3_stmt_readonly          sqlite3_api->stmt_readonly
96628#define sqlite3_stricmp                sqlite3_api->stricmp
96629#define sqlite3_uri_boolean            sqlite3_api->uri_boolean
96630#define sqlite3_uri_int64              sqlite3_api->uri_int64
96631#define sqlite3_uri_parameter          sqlite3_api->uri_parameter
96632#define sqlite3_uri_vsnprintf          sqlite3_api->vsnprintf
96633#define sqlite3_wal_checkpoint_v2      sqlite3_api->wal_checkpoint_v2
96634#endif /* SQLITE_CORE */
96635
96636#ifndef SQLITE_CORE
96637  /* This case when the file really is being compiled as a loadable
96638  ** extension */
96639# define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api=0;
96640# define SQLITE_EXTENSION_INIT2(v)  sqlite3_api=v;
96641# define SQLITE_EXTENSION_INIT3     \
96642    extern const sqlite3_api_routines *sqlite3_api;
96643#else
96644  /* This case when the file is being statically linked into the
96645  ** application */
96646# define SQLITE_EXTENSION_INIT1     /*no-op*/
96647# define SQLITE_EXTENSION_INIT2(v)  (void)v; /* unused parameter */
96648# define SQLITE_EXTENSION_INIT3     /*no-op*/
96649#endif
96650
96651#endif /* _SQLITE3EXT_H_ */
96652
96653/************** End of sqlite3ext.h ******************************************/
96654/************** Continuing where we left off in loadext.c ********************/
96655/* #include <string.h> */
96656
96657#ifndef SQLITE_OMIT_LOAD_EXTENSION
96658
96659/*
96660** Some API routines are omitted when various features are
96661** excluded from a build of SQLite.  Substitute a NULL pointer
96662** for any missing APIs.
96663*/
96664#ifndef SQLITE_ENABLE_COLUMN_METADATA
96665# define sqlite3_column_database_name   0
96666# define sqlite3_column_database_name16 0
96667# define sqlite3_column_table_name      0
96668# define sqlite3_column_table_name16    0
96669# define sqlite3_column_origin_name     0
96670# define sqlite3_column_origin_name16   0
96671# define sqlite3_table_column_metadata  0
96672#endif
96673
96674#ifdef SQLITE_OMIT_AUTHORIZATION
96675# define sqlite3_set_authorizer         0
96676#endif
96677
96678#ifdef SQLITE_OMIT_UTF16
96679# define sqlite3_bind_text16            0
96680# define sqlite3_collation_needed16     0
96681# define sqlite3_column_decltype16      0
96682# define sqlite3_column_name16          0
96683# define sqlite3_column_text16          0
96684# define sqlite3_complete16             0
96685# define sqlite3_create_collation16     0
96686# define sqlite3_create_function16      0
96687# define sqlite3_errmsg16               0
96688# define sqlite3_open16                 0
96689# define sqlite3_prepare16              0
96690# define sqlite3_prepare16_v2           0
96691# define sqlite3_result_error16         0
96692# define sqlite3_result_text16          0
96693# define sqlite3_result_text16be        0
96694# define sqlite3_result_text16le        0
96695# define sqlite3_value_text16           0
96696# define sqlite3_value_text16be         0
96697# define sqlite3_value_text16le         0
96698# define sqlite3_column_database_name16 0
96699# define sqlite3_column_table_name16    0
96700# define sqlite3_column_origin_name16   0
96701#endif
96702
96703#ifdef SQLITE_OMIT_COMPLETE
96704# define sqlite3_complete 0
96705# define sqlite3_complete16 0
96706#endif
96707
96708#ifdef SQLITE_OMIT_DECLTYPE
96709# define sqlite3_column_decltype16      0
96710# define sqlite3_column_decltype        0
96711#endif
96712
96713#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
96714# define sqlite3_progress_handler 0
96715#endif
96716
96717#ifdef SQLITE_OMIT_VIRTUALTABLE
96718# define sqlite3_create_module 0
96719# define sqlite3_create_module_v2 0
96720# define sqlite3_declare_vtab 0
96721# define sqlite3_vtab_config 0
96722# define sqlite3_vtab_on_conflict 0
96723#endif
96724
96725#ifdef SQLITE_OMIT_SHARED_CACHE
96726# define sqlite3_enable_shared_cache 0
96727#endif
96728
96729#ifdef SQLITE_OMIT_TRACE
96730# define sqlite3_profile       0
96731# define sqlite3_trace         0
96732#endif
96733
96734#ifdef SQLITE_OMIT_GET_TABLE
96735# define sqlite3_free_table    0
96736# define sqlite3_get_table     0
96737#endif
96738
96739#ifdef SQLITE_OMIT_INCRBLOB
96740#define sqlite3_bind_zeroblob  0
96741#define sqlite3_blob_bytes     0
96742#define sqlite3_blob_close     0
96743#define sqlite3_blob_open      0
96744#define sqlite3_blob_read      0
96745#define sqlite3_blob_write     0
96746#define sqlite3_blob_reopen    0
96747#endif
96748
96749/*
96750** The following structure contains pointers to all SQLite API routines.
96751** A pointer to this structure is passed into extensions when they are
96752** loaded so that the extension can make calls back into the SQLite
96753** library.
96754**
96755** When adding new APIs, add them to the bottom of this structure
96756** in order to preserve backwards compatibility.
96757**
96758** Extensions that use newer APIs should first call the
96759** sqlite3_libversion_number() to make sure that the API they
96760** intend to use is supported by the library.  Extensions should
96761** also check to make sure that the pointer to the function is
96762** not NULL before calling it.
96763*/
96764static const sqlite3_api_routines sqlite3Apis = {
96765  sqlite3_aggregate_context,
96766#ifndef SQLITE_OMIT_DEPRECATED
96767  sqlite3_aggregate_count,
96768#else
96769  0,
96770#endif
96771  sqlite3_bind_blob,
96772  sqlite3_bind_double,
96773  sqlite3_bind_int,
96774  sqlite3_bind_int64,
96775  sqlite3_bind_null,
96776  sqlite3_bind_parameter_count,
96777  sqlite3_bind_parameter_index,
96778  sqlite3_bind_parameter_name,
96779  sqlite3_bind_text,
96780  sqlite3_bind_text16,
96781  sqlite3_bind_value,
96782  sqlite3_busy_handler,
96783  sqlite3_busy_timeout,
96784  sqlite3_changes,
96785  sqlite3_close,
96786  sqlite3_collation_needed,
96787  sqlite3_collation_needed16,
96788  sqlite3_column_blob,
96789  sqlite3_column_bytes,
96790  sqlite3_column_bytes16,
96791  sqlite3_column_count,
96792  sqlite3_column_database_name,
96793  sqlite3_column_database_name16,
96794  sqlite3_column_decltype,
96795  sqlite3_column_decltype16,
96796  sqlite3_column_double,
96797  sqlite3_column_int,
96798  sqlite3_column_int64,
96799  sqlite3_column_name,
96800  sqlite3_column_name16,
96801  sqlite3_column_origin_name,
96802  sqlite3_column_origin_name16,
96803  sqlite3_column_table_name,
96804  sqlite3_column_table_name16,
96805  sqlite3_column_text,
96806  sqlite3_column_text16,
96807  sqlite3_column_type,
96808  sqlite3_column_value,
96809  sqlite3_commit_hook,
96810  sqlite3_complete,
96811  sqlite3_complete16,
96812  sqlite3_create_collation,
96813  sqlite3_create_collation16,
96814  sqlite3_create_function,
96815  sqlite3_create_function16,
96816  sqlite3_create_module,
96817  sqlite3_data_count,
96818  sqlite3_db_handle,
96819  sqlite3_declare_vtab,
96820  sqlite3_enable_shared_cache,
96821  sqlite3_errcode,
96822  sqlite3_errmsg,
96823  sqlite3_errmsg16,
96824  sqlite3_exec,
96825#ifndef SQLITE_OMIT_DEPRECATED
96826  sqlite3_expired,
96827#else
96828  0,
96829#endif
96830  sqlite3_finalize,
96831  sqlite3_free,
96832  sqlite3_free_table,
96833  sqlite3_get_autocommit,
96834  sqlite3_get_auxdata,
96835  sqlite3_get_table,
96836  0,     /* Was sqlite3_global_recover(), but that function is deprecated */
96837  sqlite3_interrupt,
96838  sqlite3_last_insert_rowid,
96839  sqlite3_libversion,
96840  sqlite3_libversion_number,
96841  sqlite3_malloc,
96842  sqlite3_mprintf,
96843  sqlite3_open,
96844  sqlite3_open16,
96845  sqlite3_prepare,
96846  sqlite3_prepare16,
96847  sqlite3_profile,
96848  sqlite3_progress_handler,
96849  sqlite3_realloc,
96850  sqlite3_reset,
96851  sqlite3_result_blob,
96852  sqlite3_result_double,
96853  sqlite3_result_error,
96854  sqlite3_result_error16,
96855  sqlite3_result_int,
96856  sqlite3_result_int64,
96857  sqlite3_result_null,
96858  sqlite3_result_text,
96859  sqlite3_result_text16,
96860  sqlite3_result_text16be,
96861  sqlite3_result_text16le,
96862  sqlite3_result_value,
96863  sqlite3_rollback_hook,
96864  sqlite3_set_authorizer,
96865  sqlite3_set_auxdata,
96866  sqlite3_snprintf,
96867  sqlite3_step,
96868  sqlite3_table_column_metadata,
96869#ifndef SQLITE_OMIT_DEPRECATED
96870  sqlite3_thread_cleanup,
96871#else
96872  0,
96873#endif
96874  sqlite3_total_changes,
96875  sqlite3_trace,
96876#ifndef SQLITE_OMIT_DEPRECATED
96877  sqlite3_transfer_bindings,
96878#else
96879  0,
96880#endif
96881  sqlite3_update_hook,
96882  sqlite3_user_data,
96883  sqlite3_value_blob,
96884  sqlite3_value_bytes,
96885  sqlite3_value_bytes16,
96886  sqlite3_value_double,
96887  sqlite3_value_int,
96888  sqlite3_value_int64,
96889  sqlite3_value_numeric_type,
96890  sqlite3_value_text,
96891  sqlite3_value_text16,
96892  sqlite3_value_text16be,
96893  sqlite3_value_text16le,
96894  sqlite3_value_type,
96895  sqlite3_vmprintf,
96896  /*
96897  ** The original API set ends here.  All extensions can call any
96898  ** of the APIs above provided that the pointer is not NULL.  But
96899  ** before calling APIs that follow, extension should check the
96900  ** sqlite3_libversion_number() to make sure they are dealing with
96901  ** a library that is new enough to support that API.
96902  *************************************************************************
96903  */
96904  sqlite3_overload_function,
96905
96906  /*
96907  ** Added after 3.3.13
96908  */
96909  sqlite3_prepare_v2,
96910  sqlite3_prepare16_v2,
96911  sqlite3_clear_bindings,
96912
96913  /*
96914  ** Added for 3.4.1
96915  */
96916  sqlite3_create_module_v2,
96917
96918  /*
96919  ** Added for 3.5.0
96920  */
96921  sqlite3_bind_zeroblob,
96922  sqlite3_blob_bytes,
96923  sqlite3_blob_close,
96924  sqlite3_blob_open,
96925  sqlite3_blob_read,
96926  sqlite3_blob_write,
96927  sqlite3_create_collation_v2,
96928  sqlite3_file_control,
96929  sqlite3_memory_highwater,
96930  sqlite3_memory_used,
96931#ifdef SQLITE_MUTEX_OMIT
96932  0,
96933  0,
96934  0,
96935  0,
96936  0,
96937#else
96938  sqlite3_mutex_alloc,
96939  sqlite3_mutex_enter,
96940  sqlite3_mutex_free,
96941  sqlite3_mutex_leave,
96942  sqlite3_mutex_try,
96943#endif
96944  sqlite3_open_v2,
96945  sqlite3_release_memory,
96946  sqlite3_result_error_nomem,
96947  sqlite3_result_error_toobig,
96948  sqlite3_sleep,
96949  sqlite3_soft_heap_limit,
96950  sqlite3_vfs_find,
96951  sqlite3_vfs_register,
96952  sqlite3_vfs_unregister,
96953
96954  /*
96955  ** Added for 3.5.8
96956  */
96957  sqlite3_threadsafe,
96958  sqlite3_result_zeroblob,
96959  sqlite3_result_error_code,
96960  sqlite3_test_control,
96961  sqlite3_randomness,
96962  sqlite3_context_db_handle,
96963
96964  /*
96965  ** Added for 3.6.0
96966  */
96967  sqlite3_extended_result_codes,
96968  sqlite3_limit,
96969  sqlite3_next_stmt,
96970  sqlite3_sql,
96971  sqlite3_status,
96972
96973  /*
96974  ** Added for 3.7.4
96975  */
96976  sqlite3_backup_finish,
96977  sqlite3_backup_init,
96978  sqlite3_backup_pagecount,
96979  sqlite3_backup_remaining,
96980  sqlite3_backup_step,
96981#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
96982  sqlite3_compileoption_get,
96983  sqlite3_compileoption_used,
96984#else
96985  0,
96986  0,
96987#endif
96988  sqlite3_create_function_v2,
96989  sqlite3_db_config,
96990  sqlite3_db_mutex,
96991  sqlite3_db_status,
96992  sqlite3_extended_errcode,
96993  sqlite3_log,
96994  sqlite3_soft_heap_limit64,
96995  sqlite3_sourceid,
96996  sqlite3_stmt_status,
96997  sqlite3_strnicmp,
96998#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
96999  sqlite3_unlock_notify,
97000#else
97001  0,
97002#endif
97003#ifndef SQLITE_OMIT_WAL
97004  sqlite3_wal_autocheckpoint,
97005  sqlite3_wal_checkpoint,
97006  sqlite3_wal_hook,
97007#else
97008  0,
97009  0,
97010  0,
97011#endif
97012  sqlite3_blob_reopen,
97013  sqlite3_vtab_config,
97014  sqlite3_vtab_on_conflict,
97015  sqlite3_close_v2,
97016  sqlite3_db_filename,
97017  sqlite3_db_readonly,
97018  sqlite3_db_release_memory,
97019  sqlite3_errstr,
97020  sqlite3_stmt_busy,
97021  sqlite3_stmt_readonly,
97022  sqlite3_stricmp,
97023  sqlite3_uri_boolean,
97024  sqlite3_uri_int64,
97025  sqlite3_uri_parameter,
97026  sqlite3_vsnprintf,
97027  sqlite3_wal_checkpoint_v2
97028};
97029
97030/*
97031** Attempt to load an SQLite extension library contained in the file
97032** zFile.  The entry point is zProc.  zProc may be 0 in which case a
97033** default entry point name (sqlite3_extension_init) is used.  Use
97034** of the default name is recommended.
97035**
97036** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
97037**
97038** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
97039** error message text.  The calling function should free this memory
97040** by calling sqlite3DbFree(db, ).
97041*/
97042static int sqlite3LoadExtension(
97043  sqlite3 *db,          /* Load the extension into this database connection */
97044  const char *zFile,    /* Name of the shared library containing extension */
97045  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
97046  char **pzErrMsg       /* Put error message here if not 0 */
97047){
97048  sqlite3_vfs *pVfs = db->pVfs;
97049  void *handle;
97050  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
97051  char *zErrmsg = 0;
97052  const char *zEntry;
97053  char *zAltEntry = 0;
97054  void **aHandle;
97055  int nMsg = 300 + sqlite3Strlen30(zFile);
97056  int ii;
97057
97058  /* Shared library endings to try if zFile cannot be loaded as written */
97059  static const char *azEndings[] = {
97060#if SQLITE_OS_WIN
97061     "dll"
97062#elif defined(__APPLE__)
97063     "dylib"
97064#else
97065     "so"
97066#endif
97067  };
97068
97069
97070  if( pzErrMsg ) *pzErrMsg = 0;
97071
97072  /* Ticket #1863.  To avoid a creating security problems for older
97073  ** applications that relink against newer versions of SQLite, the
97074  ** ability to run load_extension is turned off by default.  One
97075  ** must call sqlite3_enable_load_extension() to turn on extension
97076  ** loading.  Otherwise you get the following error.
97077  */
97078  if( (db->flags & SQLITE_LoadExtension)==0 ){
97079    if( pzErrMsg ){
97080      *pzErrMsg = sqlite3_mprintf("not authorized");
97081    }
97082    return SQLITE_ERROR;
97083  }
97084
97085  zEntry = zProc ? zProc : "sqlite3_extension_init";
97086
97087  handle = sqlite3OsDlOpen(pVfs, zFile);
97088#if SQLITE_OS_UNIX || SQLITE_OS_WIN
97089  for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
97090    char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
97091    if( zAltFile==0 ) return SQLITE_NOMEM;
97092    handle = sqlite3OsDlOpen(pVfs, zAltFile);
97093    sqlite3_free(zAltFile);
97094  }
97095#endif
97096  if( handle==0 ){
97097    if( pzErrMsg ){
97098      *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
97099      if( zErrmsg ){
97100        sqlite3_snprintf(nMsg, zErrmsg,
97101            "unable to open shared library [%s]", zFile);
97102        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
97103      }
97104    }
97105    return SQLITE_ERROR;
97106  }
97107  xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
97108                   sqlite3OsDlSym(pVfs, handle, zEntry);
97109
97110  /* If no entry point was specified and the default legacy
97111  ** entry point name "sqlite3_extension_init" was not found, then
97112  ** construct an entry point name "sqlite3_X_init" where the X is
97113  ** replaced by the lowercase value of every ASCII alphabetic
97114  ** character in the filename after the last "/" upto the first ".",
97115  ** and eliding the first three characters if they are "lib".
97116  ** Examples:
97117  **
97118  **    /usr/local/lib/libExample5.4.3.so ==>  sqlite3_example_init
97119  **    C:/lib/mathfuncs.dll              ==>  sqlite3_mathfuncs_init
97120  */
97121  if( xInit==0 && zProc==0 ){
97122    int iFile, iEntry, c;
97123    int ncFile = sqlite3Strlen30(zFile);
97124    zAltEntry = sqlite3_malloc(ncFile+30);
97125    if( zAltEntry==0 ){
97126      sqlite3OsDlClose(pVfs, handle);
97127      return SQLITE_NOMEM;
97128    }
97129    memcpy(zAltEntry, "sqlite3_", 8);
97130    for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
97131    iFile++;
97132    if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
97133    for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
97134      if( sqlite3Isalpha(c) ){
97135        zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
97136      }
97137    }
97138    memcpy(zAltEntry+iEntry, "_init", 6);
97139    zEntry = zAltEntry;
97140    xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
97141                     sqlite3OsDlSym(pVfs, handle, zEntry);
97142  }
97143  if( xInit==0 ){
97144    if( pzErrMsg ){
97145      nMsg += sqlite3Strlen30(zEntry);
97146      *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
97147      if( zErrmsg ){
97148        sqlite3_snprintf(nMsg, zErrmsg,
97149            "no entry point [%s] in shared library [%s]", zEntry, zFile);
97150        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
97151      }
97152    }
97153    sqlite3OsDlClose(pVfs, handle);
97154    sqlite3_free(zAltEntry);
97155    return SQLITE_ERROR;
97156  }
97157  sqlite3_free(zAltEntry);
97158  if( xInit(db, &zErrmsg, &sqlite3Apis) ){
97159    if( pzErrMsg ){
97160      *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
97161    }
97162    sqlite3_free(zErrmsg);
97163    sqlite3OsDlClose(pVfs, handle);
97164    return SQLITE_ERROR;
97165  }
97166
97167  /* Append the new shared library handle to the db->aExtension array. */
97168  aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
97169  if( aHandle==0 ){
97170    return SQLITE_NOMEM;
97171  }
97172  if( db->nExtension>0 ){
97173    memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
97174  }
97175  sqlite3DbFree(db, db->aExtension);
97176  db->aExtension = aHandle;
97177
97178  db->aExtension[db->nExtension++] = handle;
97179  return SQLITE_OK;
97180}
97181SQLITE_API int sqlite3_load_extension(
97182  sqlite3 *db,          /* Load the extension into this database connection */
97183  const char *zFile,    /* Name of the shared library containing extension */
97184  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
97185  char **pzErrMsg       /* Put error message here if not 0 */
97186){
97187  int rc;
97188  sqlite3_mutex_enter(db->mutex);
97189  rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
97190  rc = sqlite3ApiExit(db, rc);
97191  sqlite3_mutex_leave(db->mutex);
97192  return rc;
97193}
97194
97195/*
97196** Call this routine when the database connection is closing in order
97197** to clean up loaded extensions
97198*/
97199SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
97200  int i;
97201  assert( sqlite3_mutex_held(db->mutex) );
97202  for(i=0; i<db->nExtension; i++){
97203    sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
97204  }
97205  sqlite3DbFree(db, db->aExtension);
97206}
97207
97208/*
97209** Enable or disable extension loading.  Extension loading is disabled by
97210** default so as not to open security holes in older applications.
97211*/
97212SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
97213  sqlite3_mutex_enter(db->mutex);
97214  if( onoff ){
97215    db->flags |= SQLITE_LoadExtension;
97216  }else{
97217    db->flags &= ~SQLITE_LoadExtension;
97218  }
97219  sqlite3_mutex_leave(db->mutex);
97220  return SQLITE_OK;
97221}
97222
97223#endif /* SQLITE_OMIT_LOAD_EXTENSION */
97224
97225/*
97226** The auto-extension code added regardless of whether or not extension
97227** loading is supported.  We need a dummy sqlite3Apis pointer for that
97228** code if regular extension loading is not available.  This is that
97229** dummy pointer.
97230*/
97231#ifdef SQLITE_OMIT_LOAD_EXTENSION
97232static const sqlite3_api_routines sqlite3Apis = { 0 };
97233#endif
97234
97235
97236/*
97237** The following object holds the list of automatically loaded
97238** extensions.
97239**
97240** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
97241** mutex must be held while accessing this list.
97242*/
97243typedef struct sqlite3AutoExtList sqlite3AutoExtList;
97244static SQLITE_WSD struct sqlite3AutoExtList {
97245  int nExt;              /* Number of entries in aExt[] */
97246  void (**aExt)(void);   /* Pointers to the extension init functions */
97247} sqlite3Autoext = { 0, 0 };
97248
97249/* The "wsdAutoext" macro will resolve to the autoextension
97250** state vector.  If writable static data is unsupported on the target,
97251** we have to locate the state vector at run-time.  In the more common
97252** case where writable static data is supported, wsdStat can refer directly
97253** to the "sqlite3Autoext" state vector declared above.
97254*/
97255#ifdef SQLITE_OMIT_WSD
97256# define wsdAutoextInit \
97257  sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
97258# define wsdAutoext x[0]
97259#else
97260# define wsdAutoextInit
97261# define wsdAutoext sqlite3Autoext
97262#endif
97263
97264
97265/*
97266** Register a statically linked extension that is automatically
97267** loaded by every new database connection.
97268*/
97269SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
97270  int rc = SQLITE_OK;
97271#ifndef SQLITE_OMIT_AUTOINIT
97272  rc = sqlite3_initialize();
97273  if( rc ){
97274    return rc;
97275  }else
97276#endif
97277  {
97278    int i;
97279#if SQLITE_THREADSAFE
97280    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
97281#endif
97282    wsdAutoextInit;
97283    sqlite3_mutex_enter(mutex);
97284    for(i=0; i<wsdAutoext.nExt; i++){
97285      if( wsdAutoext.aExt[i]==xInit ) break;
97286    }
97287    if( i==wsdAutoext.nExt ){
97288      int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
97289      void (**aNew)(void);
97290      aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
97291      if( aNew==0 ){
97292        rc = SQLITE_NOMEM;
97293      }else{
97294        wsdAutoext.aExt = aNew;
97295        wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
97296        wsdAutoext.nExt++;
97297      }
97298    }
97299    sqlite3_mutex_leave(mutex);
97300    assert( (rc&0xff)==rc );
97301    return rc;
97302  }
97303}
97304
97305/*
97306** Cancel a prior call to sqlite3_auto_extension.  Remove xInit from the
97307** set of routines that is invoked for each new database connection, if it
97308** is currently on the list.  If xInit is not on the list, then this
97309** routine is a no-op.
97310**
97311** Return 1 if xInit was found on the list and removed.  Return 0 if xInit
97312** was not on the list.
97313*/
97314SQLITE_API int sqlite3_cancel_auto_extension(void (*xInit)(void)){
97315#if SQLITE_THREADSAFE
97316  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
97317#endif
97318  int i;
97319  int n = 0;
97320  wsdAutoextInit;
97321  sqlite3_mutex_enter(mutex);
97322  for(i=wsdAutoext.nExt-1; i>=0; i--){
97323    if( wsdAutoext.aExt[i]==xInit ){
97324      wsdAutoext.nExt--;
97325      wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
97326      n++;
97327      break;
97328    }
97329  }
97330  sqlite3_mutex_leave(mutex);
97331  return n;
97332}
97333
97334/*
97335** Reset the automatic extension loading mechanism.
97336*/
97337SQLITE_API void sqlite3_reset_auto_extension(void){
97338#ifndef SQLITE_OMIT_AUTOINIT
97339  if( sqlite3_initialize()==SQLITE_OK )
97340#endif
97341  {
97342#if SQLITE_THREADSAFE
97343    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
97344#endif
97345    wsdAutoextInit;
97346    sqlite3_mutex_enter(mutex);
97347    sqlite3_free(wsdAutoext.aExt);
97348    wsdAutoext.aExt = 0;
97349    wsdAutoext.nExt = 0;
97350    sqlite3_mutex_leave(mutex);
97351  }
97352}
97353
97354/*
97355** Load all automatic extensions.
97356**
97357** If anything goes wrong, set an error in the database connection.
97358*/
97359SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
97360  int i;
97361  int go = 1;
97362  int rc;
97363  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
97364
97365  wsdAutoextInit;
97366  if( wsdAutoext.nExt==0 ){
97367    /* Common case: early out without every having to acquire a mutex */
97368    return;
97369  }
97370  for(i=0; go; i++){
97371    char *zErrmsg;
97372#if SQLITE_THREADSAFE
97373    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
97374#endif
97375    sqlite3_mutex_enter(mutex);
97376    if( i>=wsdAutoext.nExt ){
97377      xInit = 0;
97378      go = 0;
97379    }else{
97380      xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
97381              wsdAutoext.aExt[i];
97382    }
97383    sqlite3_mutex_leave(mutex);
97384    zErrmsg = 0;
97385    if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
97386      sqlite3Error(db, rc,
97387            "automatic extension loading failed: %s", zErrmsg);
97388      go = 0;
97389    }
97390    sqlite3_free(zErrmsg);
97391  }
97392}
97393
97394/************** End of loadext.c *********************************************/
97395/************** Begin file pragma.c ******************************************/
97396/*
97397** 2003 April 6
97398**
97399** The author disclaims copyright to this source code.  In place of
97400** a legal notice, here is a blessing:
97401**
97402**    May you do good and not evil.
97403**    May you find forgiveness for yourself and forgive others.
97404**    May you share freely, never taking more than you give.
97405**
97406*************************************************************************
97407** This file contains code used to implement the PRAGMA command.
97408*/
97409
97410#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
97411#  if defined(__APPLE__)
97412#    define SQLITE_ENABLE_LOCKING_STYLE 1
97413#  else
97414#    define SQLITE_ENABLE_LOCKING_STYLE 0
97415#  endif
97416#endif
97417
97418/***************************************************************************
97419** The next block of code, including the PragTyp_XXXX macro definitions and
97420** the aPragmaName[] object is composed of generated code. DO NOT EDIT.
97421**
97422** To add new pragmas, edit the code in ../tool/mkpragmatab.tcl and rerun
97423** that script.  Then copy/paste the output in place of the following:
97424*/
97425#define PragTyp_HEADER_VALUE                   0
97426#define PragTyp_AUTO_VACUUM                    1
97427#define PragTyp_FLAG                           2
97428#define PragTyp_BUSY_TIMEOUT                   3
97429#define PragTyp_CACHE_SIZE                     4
97430#define PragTyp_CASE_SENSITIVE_LIKE            5
97431#define PragTyp_COLLATION_LIST                 6
97432#define PragTyp_COMPILE_OPTIONS                7
97433#define PragTyp_DATA_STORE_DIRECTORY           8
97434#define PragTyp_DATABASE_LIST                  9
97435#define PragTyp_DEFAULT_CACHE_SIZE            10
97436#define PragTyp_ENCODING                      11
97437#define PragTyp_FOREIGN_KEY_CHECK             12
97438#define PragTyp_FOREIGN_KEY_LIST              13
97439#define PragTyp_INCREMENTAL_VACUUM            14
97440#define PragTyp_INDEX_INFO                    15
97441#define PragTyp_INDEX_LIST                    16
97442#define PragTyp_INTEGRITY_CHECK               17
97443#define PragTyp_JOURNAL_MODE                  18
97444#define PragTyp_JOURNAL_SIZE_LIMIT            19
97445#define PragTyp_LOCK_PROXY_FILE               20
97446#define PragTyp_LOCKING_MODE                  21
97447#define PragTyp_PAGE_COUNT                    22
97448#define PragTyp_MMAP_SIZE                     23
97449#define PragTyp_PAGE_SIZE                     24
97450#define PragTyp_SECURE_DELETE                 25
97451#define PragTyp_SHRINK_MEMORY                 26
97452#define PragTyp_SOFT_HEAP_LIMIT               27
97453#define PragTyp_STATS                         28
97454#define PragTyp_SYNCHRONOUS                   29
97455#define PragTyp_TABLE_INFO                    30
97456#define PragTyp_TEMP_STORE                    31
97457#define PragTyp_TEMP_STORE_DIRECTORY          32
97458#define PragTyp_WAL_AUTOCHECKPOINT            33
97459#define PragTyp_WAL_CHECKPOINT                34
97460#define PragTyp_ACTIVATE_EXTENSIONS           35
97461#define PragTyp_HEXKEY                        36
97462#define PragTyp_KEY                           37
97463#define PragTyp_REKEY                         38
97464#define PragTyp_LOCK_STATUS                   39
97465#define PragTyp_PARSER_TRACE                  40
97466#define PragFlag_NeedSchema           0x01
97467static const struct sPragmaNames {
97468  const char *const zName;  /* Name of pragma */
97469  u8 ePragTyp;              /* PragTyp_XXX value */
97470  u8 mPragFlag;             /* Zero or more PragFlag_XXX values */
97471  u32 iArg;                 /* Extra argument */
97472} aPragmaNames[] = {
97473#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
97474  { /* zName:     */ "activate_extensions",
97475    /* ePragTyp:  */ PragTyp_ACTIVATE_EXTENSIONS,
97476    /* ePragFlag: */ 0,
97477    /* iArg:      */ 0 },
97478#endif
97479#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
97480  { /* zName:     */ "application_id",
97481    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
97482    /* ePragFlag: */ 0,
97483    /* iArg:      */ 0 },
97484#endif
97485#if !defined(SQLITE_OMIT_AUTOVACUUM)
97486  { /* zName:     */ "auto_vacuum",
97487    /* ePragTyp:  */ PragTyp_AUTO_VACUUM,
97488    /* ePragFlag: */ PragFlag_NeedSchema,
97489    /* iArg:      */ 0 },
97490#endif
97491#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
97492#if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
97493  { /* zName:     */ "automatic_index",
97494    /* ePragTyp:  */ PragTyp_FLAG,
97495    /* ePragFlag: */ 0,
97496    /* iArg:      */ SQLITE_AutoIndex },
97497#endif
97498#endif
97499  { /* zName:     */ "busy_timeout",
97500    /* ePragTyp:  */ PragTyp_BUSY_TIMEOUT,
97501    /* ePragFlag: */ 0,
97502    /* iArg:      */ 0 },
97503#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
97504  { /* zName:     */ "cache_size",
97505    /* ePragTyp:  */ PragTyp_CACHE_SIZE,
97506    /* ePragFlag: */ PragFlag_NeedSchema,
97507    /* iArg:      */ 0 },
97508#endif
97509#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
97510  { /* zName:     */ "cache_spill",
97511    /* ePragTyp:  */ PragTyp_FLAG,
97512    /* ePragFlag: */ 0,
97513    /* iArg:      */ SQLITE_CacheSpill },
97514#endif
97515  { /* zName:     */ "case_sensitive_like",
97516    /* ePragTyp:  */ PragTyp_CASE_SENSITIVE_LIKE,
97517    /* ePragFlag: */ 0,
97518    /* iArg:      */ 0 },
97519#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
97520  { /* zName:     */ "checkpoint_fullfsync",
97521    /* ePragTyp:  */ PragTyp_FLAG,
97522    /* ePragFlag: */ 0,
97523    /* iArg:      */ SQLITE_CkptFullFSync },
97524#endif
97525#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
97526  { /* zName:     */ "collation_list",
97527    /* ePragTyp:  */ PragTyp_COLLATION_LIST,
97528    /* ePragFlag: */ 0,
97529    /* iArg:      */ 0 },
97530#endif
97531#if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
97532  { /* zName:     */ "compile_options",
97533    /* ePragTyp:  */ PragTyp_COMPILE_OPTIONS,
97534    /* ePragFlag: */ 0,
97535    /* iArg:      */ 0 },
97536#endif
97537#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
97538  { /* zName:     */ "count_changes",
97539    /* ePragTyp:  */ PragTyp_FLAG,
97540    /* ePragFlag: */ 0,
97541    /* iArg:      */ SQLITE_CountRows },
97542#endif
97543#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
97544  { /* zName:     */ "data_store_directory",
97545    /* ePragTyp:  */ PragTyp_DATA_STORE_DIRECTORY,
97546    /* ePragFlag: */ 0,
97547    /* iArg:      */ 0 },
97548#endif
97549#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
97550  { /* zName:     */ "database_list",
97551    /* ePragTyp:  */ PragTyp_DATABASE_LIST,
97552    /* ePragFlag: */ PragFlag_NeedSchema,
97553    /* iArg:      */ 0 },
97554#endif
97555#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
97556  { /* zName:     */ "default_cache_size",
97557    /* ePragTyp:  */ PragTyp_DEFAULT_CACHE_SIZE,
97558    /* ePragFlag: */ PragFlag_NeedSchema,
97559    /* iArg:      */ 0 },
97560#endif
97561#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
97562#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
97563  { /* zName:     */ "defer_foreign_keys",
97564    /* ePragTyp:  */ PragTyp_FLAG,
97565    /* ePragFlag: */ 0,
97566    /* iArg:      */ SQLITE_DeferFKs },
97567#endif
97568#endif
97569#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
97570  { /* zName:     */ "empty_result_callbacks",
97571    /* ePragTyp:  */ PragTyp_FLAG,
97572    /* ePragFlag: */ 0,
97573    /* iArg:      */ SQLITE_NullCallback },
97574#endif
97575#if !defined(SQLITE_OMIT_UTF16)
97576  { /* zName:     */ "encoding",
97577    /* ePragTyp:  */ PragTyp_ENCODING,
97578    /* ePragFlag: */ 0,
97579    /* iArg:      */ 0 },
97580#endif
97581#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
97582  { /* zName:     */ "foreign_key_check",
97583    /* ePragTyp:  */ PragTyp_FOREIGN_KEY_CHECK,
97584    /* ePragFlag: */ PragFlag_NeedSchema,
97585    /* iArg:      */ 0 },
97586#endif
97587#if !defined(SQLITE_OMIT_FOREIGN_KEY)
97588  { /* zName:     */ "foreign_key_list",
97589    /* ePragTyp:  */ PragTyp_FOREIGN_KEY_LIST,
97590    /* ePragFlag: */ PragFlag_NeedSchema,
97591    /* iArg:      */ 0 },
97592#endif
97593#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
97594#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
97595  { /* zName:     */ "foreign_keys",
97596    /* ePragTyp:  */ PragTyp_FLAG,
97597    /* ePragFlag: */ 0,
97598    /* iArg:      */ SQLITE_ForeignKeys },
97599#endif
97600#endif
97601#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
97602  { /* zName:     */ "freelist_count",
97603    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
97604    /* ePragFlag: */ 0,
97605    /* iArg:      */ 0 },
97606#endif
97607#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
97608  { /* zName:     */ "full_column_names",
97609    /* ePragTyp:  */ PragTyp_FLAG,
97610    /* ePragFlag: */ 0,
97611    /* iArg:      */ SQLITE_FullColNames },
97612  { /* zName:     */ "fullfsync",
97613    /* ePragTyp:  */ PragTyp_FLAG,
97614    /* ePragFlag: */ 0,
97615    /* iArg:      */ SQLITE_FullFSync },
97616#endif
97617#if defined(SQLITE_HAS_CODEC)
97618  { /* zName:     */ "hexkey",
97619    /* ePragTyp:  */ PragTyp_HEXKEY,
97620    /* ePragFlag: */ 0,
97621    /* iArg:      */ 0 },
97622  { /* zName:     */ "hexrekey",
97623    /* ePragTyp:  */ PragTyp_HEXKEY,
97624    /* ePragFlag: */ 0,
97625    /* iArg:      */ 0 },
97626#endif
97627#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
97628#if !defined(SQLITE_OMIT_CHECK)
97629  { /* zName:     */ "ignore_check_constraints",
97630    /* ePragTyp:  */ PragTyp_FLAG,
97631    /* ePragFlag: */ 0,
97632    /* iArg:      */ SQLITE_IgnoreChecks },
97633#endif
97634#endif
97635#if !defined(SQLITE_OMIT_AUTOVACUUM)
97636  { /* zName:     */ "incremental_vacuum",
97637    /* ePragTyp:  */ PragTyp_INCREMENTAL_VACUUM,
97638    /* ePragFlag: */ PragFlag_NeedSchema,
97639    /* iArg:      */ 0 },
97640#endif
97641#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
97642  { /* zName:     */ "index_info",
97643    /* ePragTyp:  */ PragTyp_INDEX_INFO,
97644    /* ePragFlag: */ PragFlag_NeedSchema,
97645    /* iArg:      */ 0 },
97646  { /* zName:     */ "index_list",
97647    /* ePragTyp:  */ PragTyp_INDEX_LIST,
97648    /* ePragFlag: */ PragFlag_NeedSchema,
97649    /* iArg:      */ 0 },
97650#endif
97651#if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
97652  { /* zName:     */ "integrity_check",
97653    /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
97654    /* ePragFlag: */ PragFlag_NeedSchema,
97655    /* iArg:      */ 0 },
97656#endif
97657#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
97658  { /* zName:     */ "journal_mode",
97659    /* ePragTyp:  */ PragTyp_JOURNAL_MODE,
97660    /* ePragFlag: */ PragFlag_NeedSchema,
97661    /* iArg:      */ 0 },
97662  { /* zName:     */ "journal_size_limit",
97663    /* ePragTyp:  */ PragTyp_JOURNAL_SIZE_LIMIT,
97664    /* ePragFlag: */ 0,
97665    /* iArg:      */ 0 },
97666#endif
97667#if defined(SQLITE_HAS_CODEC)
97668  { /* zName:     */ "key",
97669    /* ePragTyp:  */ PragTyp_KEY,
97670    /* ePragFlag: */ 0,
97671    /* iArg:      */ 0 },
97672#endif
97673#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
97674  { /* zName:     */ "legacy_file_format",
97675    /* ePragTyp:  */ PragTyp_FLAG,
97676    /* ePragFlag: */ 0,
97677    /* iArg:      */ SQLITE_LegacyFileFmt },
97678#endif
97679#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
97680  { /* zName:     */ "lock_proxy_file",
97681    /* ePragTyp:  */ PragTyp_LOCK_PROXY_FILE,
97682    /* ePragFlag: */ 0,
97683    /* iArg:      */ 0 },
97684#endif
97685#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
97686  { /* zName:     */ "lock_status",
97687    /* ePragTyp:  */ PragTyp_LOCK_STATUS,
97688    /* ePragFlag: */ 0,
97689    /* iArg:      */ 0 },
97690#endif
97691#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
97692  { /* zName:     */ "locking_mode",
97693    /* ePragTyp:  */ PragTyp_LOCKING_MODE,
97694    /* ePragFlag: */ 0,
97695    /* iArg:      */ 0 },
97696  { /* zName:     */ "max_page_count",
97697    /* ePragTyp:  */ PragTyp_PAGE_COUNT,
97698    /* ePragFlag: */ PragFlag_NeedSchema,
97699    /* iArg:      */ 0 },
97700  { /* zName:     */ "mmap_size",
97701    /* ePragTyp:  */ PragTyp_MMAP_SIZE,
97702    /* ePragFlag: */ 0,
97703    /* iArg:      */ 0 },
97704  { /* zName:     */ "page_count",
97705    /* ePragTyp:  */ PragTyp_PAGE_COUNT,
97706    /* ePragFlag: */ PragFlag_NeedSchema,
97707    /* iArg:      */ 0 },
97708  { /* zName:     */ "page_size",
97709    /* ePragTyp:  */ PragTyp_PAGE_SIZE,
97710    /* ePragFlag: */ 0,
97711    /* iArg:      */ 0 },
97712#endif
97713#if defined(SQLITE_DEBUG)
97714  { /* zName:     */ "parser_trace",
97715    /* ePragTyp:  */ PragTyp_PARSER_TRACE,
97716    /* ePragFlag: */ 0,
97717    /* iArg:      */ 0 },
97718#endif
97719#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
97720  { /* zName:     */ "query_only",
97721    /* ePragTyp:  */ PragTyp_FLAG,
97722    /* ePragFlag: */ 0,
97723    /* iArg:      */ SQLITE_QueryOnly },
97724#endif
97725#if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
97726  { /* zName:     */ "quick_check",
97727    /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
97728    /* ePragFlag: */ PragFlag_NeedSchema,
97729    /* iArg:      */ 0 },
97730#endif
97731#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
97732  { /* zName:     */ "read_uncommitted",
97733    /* ePragTyp:  */ PragTyp_FLAG,
97734    /* ePragFlag: */ 0,
97735    /* iArg:      */ SQLITE_ReadUncommitted },
97736  { /* zName:     */ "recursive_triggers",
97737    /* ePragTyp:  */ PragTyp_FLAG,
97738    /* ePragFlag: */ 0,
97739    /* iArg:      */ SQLITE_RecTriggers },
97740#endif
97741#if defined(SQLITE_HAS_CODEC)
97742  { /* zName:     */ "rekey",
97743    /* ePragTyp:  */ PragTyp_REKEY,
97744    /* ePragFlag: */ 0,
97745    /* iArg:      */ 0 },
97746#endif
97747#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
97748  { /* zName:     */ "reverse_unordered_selects",
97749    /* ePragTyp:  */ PragTyp_FLAG,
97750    /* ePragFlag: */ 0,
97751    /* iArg:      */ SQLITE_ReverseOrder },
97752#endif
97753#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
97754  { /* zName:     */ "schema_version",
97755    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
97756    /* ePragFlag: */ 0,
97757    /* iArg:      */ 0 },
97758#endif
97759#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
97760  { /* zName:     */ "secure_delete",
97761    /* ePragTyp:  */ PragTyp_SECURE_DELETE,
97762    /* ePragFlag: */ 0,
97763    /* iArg:      */ 0 },
97764#endif
97765#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
97766  { /* zName:     */ "short_column_names",
97767    /* ePragTyp:  */ PragTyp_FLAG,
97768    /* ePragFlag: */ 0,
97769    /* iArg:      */ SQLITE_ShortColNames },
97770#endif
97771  { /* zName:     */ "shrink_memory",
97772    /* ePragTyp:  */ PragTyp_SHRINK_MEMORY,
97773    /* ePragFlag: */ 0,
97774    /* iArg:      */ 0 },
97775  { /* zName:     */ "soft_heap_limit",
97776    /* ePragTyp:  */ PragTyp_SOFT_HEAP_LIMIT,
97777    /* ePragFlag: */ 0,
97778    /* iArg:      */ 0 },
97779#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
97780#if defined(SQLITE_DEBUG)
97781  { /* zName:     */ "sql_trace",
97782    /* ePragTyp:  */ PragTyp_FLAG,
97783    /* ePragFlag: */ 0,
97784    /* iArg:      */ SQLITE_SqlTrace },
97785#endif
97786#endif
97787#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
97788  { /* zName:     */ "stats",
97789    /* ePragTyp:  */ PragTyp_STATS,
97790    /* ePragFlag: */ PragFlag_NeedSchema,
97791    /* iArg:      */ 0 },
97792#endif
97793#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
97794  { /* zName:     */ "synchronous",
97795    /* ePragTyp:  */ PragTyp_SYNCHRONOUS,
97796    /* ePragFlag: */ PragFlag_NeedSchema,
97797    /* iArg:      */ 0 },
97798#endif
97799#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
97800  { /* zName:     */ "table_info",
97801    /* ePragTyp:  */ PragTyp_TABLE_INFO,
97802    /* ePragFlag: */ PragFlag_NeedSchema,
97803    /* iArg:      */ 0 },
97804#endif
97805#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
97806  { /* zName:     */ "temp_store",
97807    /* ePragTyp:  */ PragTyp_TEMP_STORE,
97808    /* ePragFlag: */ 0,
97809    /* iArg:      */ 0 },
97810  { /* zName:     */ "temp_store_directory",
97811    /* ePragTyp:  */ PragTyp_TEMP_STORE_DIRECTORY,
97812    /* ePragFlag: */ 0,
97813    /* iArg:      */ 0 },
97814#endif
97815#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
97816  { /* zName:     */ "user_version",
97817    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
97818    /* ePragFlag: */ 0,
97819    /* iArg:      */ 0 },
97820#endif
97821#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
97822#if defined(SQLITE_DEBUG)
97823  { /* zName:     */ "vdbe_addoptrace",
97824    /* ePragTyp:  */ PragTyp_FLAG,
97825    /* ePragFlag: */ 0,
97826    /* iArg:      */ SQLITE_VdbeAddopTrace },
97827  { /* zName:     */ "vdbe_debug",
97828    /* ePragTyp:  */ PragTyp_FLAG,
97829    /* ePragFlag: */ 0,
97830    /* iArg:      */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
97831  { /* zName:     */ "vdbe_eqp",
97832    /* ePragTyp:  */ PragTyp_FLAG,
97833    /* ePragFlag: */ 0,
97834    /* iArg:      */ SQLITE_VdbeEQP },
97835  { /* zName:     */ "vdbe_listing",
97836    /* ePragTyp:  */ PragTyp_FLAG,
97837    /* ePragFlag: */ 0,
97838    /* iArg:      */ SQLITE_VdbeListing },
97839  { /* zName:     */ "vdbe_trace",
97840    /* ePragTyp:  */ PragTyp_FLAG,
97841    /* ePragFlag: */ 0,
97842    /* iArg:      */ SQLITE_VdbeTrace },
97843#endif
97844#endif
97845#if !defined(SQLITE_OMIT_WAL)
97846  { /* zName:     */ "wal_autocheckpoint",
97847    /* ePragTyp:  */ PragTyp_WAL_AUTOCHECKPOINT,
97848    /* ePragFlag: */ 0,
97849    /* iArg:      */ 0 },
97850  { /* zName:     */ "wal_checkpoint",
97851    /* ePragTyp:  */ PragTyp_WAL_CHECKPOINT,
97852    /* ePragFlag: */ PragFlag_NeedSchema,
97853    /* iArg:      */ 0 },
97854#endif
97855#if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
97856  { /* zName:     */ "writable_schema",
97857    /* ePragTyp:  */ PragTyp_FLAG,
97858    /* ePragFlag: */ 0,
97859    /* iArg:      */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
97860#endif
97861};
97862/* Number of pragmas: 56 on by default, 69 total. */
97863/* End of the automatically generated pragma table.
97864***************************************************************************/
97865
97866/*
97867** Interpret the given string as a safety level.  Return 0 for OFF,
97868** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or
97869** unrecognized string argument.  The FULL option is disallowed
97870** if the omitFull parameter it 1.
97871**
97872** Note that the values returned are one less that the values that
97873** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
97874** to support legacy SQL code.  The safety level used to be boolean
97875** and older scripts may have used numbers 0 for OFF and 1 for ON.
97876*/
97877static u8 getSafetyLevel(const char *z, int omitFull, int dflt){
97878                             /* 123456789 123456789 */
97879  static const char zText[] = "onoffalseyestruefull";
97880  static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
97881  static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
97882  static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
97883  int i, n;
97884  if( sqlite3Isdigit(*z) ){
97885    return (u8)sqlite3Atoi(z);
97886  }
97887  n = sqlite3Strlen30(z);
97888  for(i=0; i<ArraySize(iLength)-omitFull; i++){
97889    if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
97890      return iValue[i];
97891    }
97892  }
97893  return dflt;
97894}
97895
97896/*
97897** Interpret the given string as a boolean value.
97898*/
97899SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, int dflt){
97900  return getSafetyLevel(z,1,dflt)!=0;
97901}
97902
97903/* The sqlite3GetBoolean() function is used by other modules but the
97904** remainder of this file is specific to PRAGMA processing.  So omit
97905** the rest of the file if PRAGMAs are omitted from the build.
97906*/
97907#if !defined(SQLITE_OMIT_PRAGMA)
97908
97909/*
97910** Interpret the given string as a locking mode value.
97911*/
97912static int getLockingMode(const char *z){
97913  if( z ){
97914    if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
97915    if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
97916  }
97917  return PAGER_LOCKINGMODE_QUERY;
97918}
97919
97920#ifndef SQLITE_OMIT_AUTOVACUUM
97921/*
97922** Interpret the given string as an auto-vacuum mode value.
97923**
97924** The following strings, "none", "full" and "incremental" are
97925** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
97926*/
97927static int getAutoVacuum(const char *z){
97928  int i;
97929  if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
97930  if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
97931  if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
97932  i = sqlite3Atoi(z);
97933  return (u8)((i>=0&&i<=2)?i:0);
97934}
97935#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
97936
97937#ifndef SQLITE_OMIT_PAGER_PRAGMAS
97938/*
97939** Interpret the given string as a temp db location. Return 1 for file
97940** backed temporary databases, 2 for the Red-Black tree in memory database
97941** and 0 to use the compile-time default.
97942*/
97943static int getTempStore(const char *z){
97944  if( z[0]>='0' && z[0]<='2' ){
97945    return z[0] - '0';
97946  }else if( sqlite3StrICmp(z, "file")==0 ){
97947    return 1;
97948  }else if( sqlite3StrICmp(z, "memory")==0 ){
97949    return 2;
97950  }else{
97951    return 0;
97952  }
97953}
97954#endif /* SQLITE_PAGER_PRAGMAS */
97955
97956#ifndef SQLITE_OMIT_PAGER_PRAGMAS
97957/*
97958** Invalidate temp storage, either when the temp storage is changed
97959** from default, or when 'file' and the temp_store_directory has changed
97960*/
97961static int invalidateTempStorage(Parse *pParse){
97962  sqlite3 *db = pParse->db;
97963  if( db->aDb[1].pBt!=0 ){
97964    if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
97965      sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
97966        "from within a transaction");
97967      return SQLITE_ERROR;
97968    }
97969    sqlite3BtreeClose(db->aDb[1].pBt);
97970    db->aDb[1].pBt = 0;
97971    sqlite3ResetAllSchemasOfConnection(db);
97972  }
97973  return SQLITE_OK;
97974}
97975#endif /* SQLITE_PAGER_PRAGMAS */
97976
97977#ifndef SQLITE_OMIT_PAGER_PRAGMAS
97978/*
97979** If the TEMP database is open, close it and mark the database schema
97980** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
97981** or DEFAULT_TEMP_STORE pragmas.
97982*/
97983static int changeTempStorage(Parse *pParse, const char *zStorageType){
97984  int ts = getTempStore(zStorageType);
97985  sqlite3 *db = pParse->db;
97986  if( db->temp_store==ts ) return SQLITE_OK;
97987  if( invalidateTempStorage( pParse ) != SQLITE_OK ){
97988    return SQLITE_ERROR;
97989  }
97990  db->temp_store = (u8)ts;
97991  return SQLITE_OK;
97992}
97993#endif /* SQLITE_PAGER_PRAGMAS */
97994
97995/*
97996** Generate code to return a single integer value.
97997*/
97998static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
97999  Vdbe *v = sqlite3GetVdbe(pParse);
98000  int mem = ++pParse->nMem;
98001  i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
98002  if( pI64 ){
98003    memcpy(pI64, &value, sizeof(value));
98004  }
98005  sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
98006  sqlite3VdbeSetNumCols(v, 1);
98007  sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
98008  sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
98009}
98010
98011
98012/*
98013** Set the safety_level and pager flags for pager iDb.  Or if iDb<0
98014** set these values for all pagers.
98015*/
98016#ifndef SQLITE_OMIT_PAGER_PRAGMAS
98017static void setAllPagerFlags(sqlite3 *db){
98018  if( db->autoCommit ){
98019    Db *pDb = db->aDb;
98020    int n = db->nDb;
98021    assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
98022    assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
98023    assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
98024    assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
98025             ==  PAGER_FLAGS_MASK );
98026    assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
98027    while( (n--) > 0 ){
98028      if( pDb->pBt ){
98029        sqlite3BtreeSetPagerFlags(pDb->pBt,
98030                 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
98031      }
98032      pDb++;
98033    }
98034  }
98035}
98036#else
98037# define setAllPagerFlags(X)  /* no-op */
98038#endif
98039
98040
98041/*
98042** Return a human-readable name for a constraint resolution action.
98043*/
98044#ifndef SQLITE_OMIT_FOREIGN_KEY
98045static const char *actionName(u8 action){
98046  const char *zName;
98047  switch( action ){
98048    case OE_SetNull:  zName = "SET NULL";        break;
98049    case OE_SetDflt:  zName = "SET DEFAULT";     break;
98050    case OE_Cascade:  zName = "CASCADE";         break;
98051    case OE_Restrict: zName = "RESTRICT";        break;
98052    default:          zName = "NO ACTION";
98053                      assert( action==OE_None ); break;
98054  }
98055  return zName;
98056}
98057#endif
98058
98059
98060/*
98061** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
98062** defined in pager.h. This function returns the associated lowercase
98063** journal-mode name.
98064*/
98065SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
98066  static char * const azModeName[] = {
98067    "delete", "persist", "off", "truncate", "memory"
98068#ifndef SQLITE_OMIT_WAL
98069     , "wal"
98070#endif
98071  };
98072  assert( PAGER_JOURNALMODE_DELETE==0 );
98073  assert( PAGER_JOURNALMODE_PERSIST==1 );
98074  assert( PAGER_JOURNALMODE_OFF==2 );
98075  assert( PAGER_JOURNALMODE_TRUNCATE==3 );
98076  assert( PAGER_JOURNALMODE_MEMORY==4 );
98077  assert( PAGER_JOURNALMODE_WAL==5 );
98078  assert( eMode>=0 && eMode<=ArraySize(azModeName) );
98079
98080  if( eMode==ArraySize(azModeName) ) return 0;
98081  return azModeName[eMode];
98082}
98083
98084/*
98085** Process a pragma statement.
98086**
98087** Pragmas are of this form:
98088**
98089**      PRAGMA [database.]id [= value]
98090**
98091** The identifier might also be a string.  The value is a string, and
98092** identifier, or a number.  If minusFlag is true, then the value is
98093** a number that was preceded by a minus sign.
98094**
98095** If the left side is "database.id" then pId1 is the database name
98096** and pId2 is the id.  If the left side is just "id" then pId1 is the
98097** id and pId2 is any empty string.
98098*/
98099SQLITE_PRIVATE void sqlite3Pragma(
98100  Parse *pParse,
98101  Token *pId1,        /* First part of [database.]id field */
98102  Token *pId2,        /* Second part of [database.]id field, or NULL */
98103  Token *pValue,      /* Token for <value>, or NULL */
98104  int minusFlag       /* True if a '-' sign preceded <value> */
98105){
98106  char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
98107  char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
98108  const char *zDb = 0;   /* The database name */
98109  Token *pId;            /* Pointer to <id> token */
98110  char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
98111  int iDb;               /* Database index for <database> */
98112  int lwr, upr, mid;           /* Binary search bounds */
98113  int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
98114  sqlite3 *db = pParse->db;    /* The database connection */
98115  Db *pDb;                     /* The specific database being pragmaed */
98116  Vdbe *v = sqlite3GetVdbe(pParse);  /* Prepared statement */
98117
98118  if( v==0 ) return;
98119  sqlite3VdbeRunOnlyOnce(v);
98120  pParse->nMem = 2;
98121
98122  /* Interpret the [database.] part of the pragma statement. iDb is the
98123  ** index of the database this pragma is being applied to in db.aDb[]. */
98124  iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
98125  if( iDb<0 ) return;
98126  pDb = &db->aDb[iDb];
98127
98128  /* If the temp database has been explicitly named as part of the
98129  ** pragma, make sure it is open.
98130  */
98131  if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
98132    return;
98133  }
98134
98135  zLeft = sqlite3NameFromToken(db, pId);
98136  if( !zLeft ) return;
98137  if( minusFlag ){
98138    zRight = sqlite3MPrintf(db, "-%T", pValue);
98139  }else{
98140    zRight = sqlite3NameFromToken(db, pValue);
98141  }
98142
98143  assert( pId2 );
98144  zDb = pId2->n>0 ? pDb->zName : 0;
98145  if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
98146    goto pragma_out;
98147  }
98148
98149  /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
98150  ** connection.  If it returns SQLITE_OK, then assume that the VFS
98151  ** handled the pragma and generate a no-op prepared statement.
98152  */
98153  aFcntl[0] = 0;
98154  aFcntl[1] = zLeft;
98155  aFcntl[2] = zRight;
98156  aFcntl[3] = 0;
98157  db->busyHandler.nBusy = 0;
98158  rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
98159  if( rc==SQLITE_OK ){
98160    if( aFcntl[0] ){
98161      int mem = ++pParse->nMem;
98162      sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
98163      sqlite3VdbeSetNumCols(v, 1);
98164      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
98165      sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
98166      sqlite3_free(aFcntl[0]);
98167    }
98168    goto pragma_out;
98169  }
98170  if( rc!=SQLITE_NOTFOUND ){
98171    if( aFcntl[0] ){
98172      sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
98173      sqlite3_free(aFcntl[0]);
98174    }
98175    pParse->nErr++;
98176    pParse->rc = rc;
98177    goto pragma_out;
98178  }
98179
98180  /* Locate the pragma in the lookup table */
98181  lwr = 0;
98182  upr = ArraySize(aPragmaNames)-1;
98183  while( lwr<=upr ){
98184    mid = (lwr+upr)/2;
98185    rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
98186    if( rc==0 ) break;
98187    if( rc<0 ){
98188      upr = mid - 1;
98189    }else{
98190      lwr = mid + 1;
98191    }
98192  }
98193  if( lwr>upr ) goto pragma_out;
98194
98195  /* Make sure the database schema is loaded if the pragma requires that */
98196  if( (aPragmaNames[mid].mPragFlag & PragFlag_NeedSchema)!=0 ){
98197    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
98198  }
98199
98200  /* Jump to the appropriate pragma handler */
98201  switch( aPragmaNames[mid].ePragTyp ){
98202
98203#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
98204  /*
98205  **  PRAGMA [database.]default_cache_size
98206  **  PRAGMA [database.]default_cache_size=N
98207  **
98208  ** The first form reports the current persistent setting for the
98209  ** page cache size.  The value returned is the maximum number of
98210  ** pages in the page cache.  The second form sets both the current
98211  ** page cache size value and the persistent page cache size value
98212  ** stored in the database file.
98213  **
98214  ** Older versions of SQLite would set the default cache size to a
98215  ** negative number to indicate synchronous=OFF.  These days, synchronous
98216  ** is always on by default regardless of the sign of the default cache
98217  ** size.  But continue to take the absolute value of the default cache
98218  ** size of historical compatibility.
98219  */
98220  case PragTyp_DEFAULT_CACHE_SIZE: {
98221    static const int iLn = VDBE_OFFSET_LINENO(2);
98222    static const VdbeOpList getCacheSize[] = {
98223      { OP_Transaction, 0, 0,        0},                         /* 0 */
98224      { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
98225      { OP_IfPos,       1, 8,        0},
98226      { OP_Integer,     0, 2,        0},
98227      { OP_Subtract,    1, 2,        1},
98228      { OP_IfPos,       1, 8,        0},
98229      { OP_Integer,     0, 1,        0},                         /* 6 */
98230      { OP_Noop,        0, 0,        0},
98231      { OP_ResultRow,   1, 1,        0},
98232    };
98233    int addr;
98234    sqlite3VdbeUsesBtree(v, iDb);
98235    if( !zRight ){
98236      sqlite3VdbeSetNumCols(v, 1);
98237      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
98238      pParse->nMem += 2;
98239      addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize,iLn);
98240      sqlite3VdbeChangeP1(v, addr, iDb);
98241      sqlite3VdbeChangeP1(v, addr+1, iDb);
98242      sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
98243    }else{
98244      int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
98245      sqlite3BeginWriteOperation(pParse, 0, iDb);
98246      sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
98247      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
98248      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
98249      pDb->pSchema->cache_size = size;
98250      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
98251    }
98252    break;
98253  }
98254#endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
98255
98256#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
98257  /*
98258  **  PRAGMA [database.]page_size
98259  **  PRAGMA [database.]page_size=N
98260  **
98261  ** The first form reports the current setting for the
98262  ** database page size in bytes.  The second form sets the
98263  ** database page size value.  The value can only be set if
98264  ** the database has not yet been created.
98265  */
98266  case PragTyp_PAGE_SIZE: {
98267    Btree *pBt = pDb->pBt;
98268    assert( pBt!=0 );
98269    if( !zRight ){
98270      int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
98271      returnSingleInt(pParse, "page_size", size);
98272    }else{
98273      /* Malloc may fail when setting the page-size, as there is an internal
98274      ** buffer that the pager module resizes using sqlite3_realloc().
98275      */
98276      db->nextPagesize = sqlite3Atoi(zRight);
98277      if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
98278        db->mallocFailed = 1;
98279      }
98280    }
98281    break;
98282  }
98283
98284  /*
98285  **  PRAGMA [database.]secure_delete
98286  **  PRAGMA [database.]secure_delete=ON/OFF
98287  **
98288  ** The first form reports the current setting for the
98289  ** secure_delete flag.  The second form changes the secure_delete
98290  ** flag setting and reports thenew value.
98291  */
98292  case PragTyp_SECURE_DELETE: {
98293    Btree *pBt = pDb->pBt;
98294    int b = -1;
98295    assert( pBt!=0 );
98296    if( zRight ){
98297      b = sqlite3GetBoolean(zRight, 0);
98298    }
98299    if( pId2->n==0 && b>=0 ){
98300      int ii;
98301      for(ii=0; ii<db->nDb; ii++){
98302        sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
98303      }
98304    }
98305    b = sqlite3BtreeSecureDelete(pBt, b);
98306    returnSingleInt(pParse, "secure_delete", b);
98307    break;
98308  }
98309
98310  /*
98311  **  PRAGMA [database.]max_page_count
98312  **  PRAGMA [database.]max_page_count=N
98313  **
98314  ** The first form reports the current setting for the
98315  ** maximum number of pages in the database file.  The
98316  ** second form attempts to change this setting.  Both
98317  ** forms return the current setting.
98318  **
98319  ** The absolute value of N is used.  This is undocumented and might
98320  ** change.  The only purpose is to provide an easy way to test
98321  ** the sqlite3AbsInt32() function.
98322  **
98323  **  PRAGMA [database.]page_count
98324  **
98325  ** Return the number of pages in the specified database.
98326  */
98327  case PragTyp_PAGE_COUNT: {
98328    int iReg;
98329    sqlite3CodeVerifySchema(pParse, iDb);
98330    iReg = ++pParse->nMem;
98331    if( sqlite3Tolower(zLeft[0])=='p' ){
98332      sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
98333    }else{
98334      sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
98335                        sqlite3AbsInt32(sqlite3Atoi(zRight)));
98336    }
98337    sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
98338    sqlite3VdbeSetNumCols(v, 1);
98339    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
98340    break;
98341  }
98342
98343  /*
98344  **  PRAGMA [database.]locking_mode
98345  **  PRAGMA [database.]locking_mode = (normal|exclusive)
98346  */
98347  case PragTyp_LOCKING_MODE: {
98348    const char *zRet = "normal";
98349    int eMode = getLockingMode(zRight);
98350
98351    if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
98352      /* Simple "PRAGMA locking_mode;" statement. This is a query for
98353      ** the current default locking mode (which may be different to
98354      ** the locking-mode of the main database).
98355      */
98356      eMode = db->dfltLockMode;
98357    }else{
98358      Pager *pPager;
98359      if( pId2->n==0 ){
98360        /* This indicates that no database name was specified as part
98361        ** of the PRAGMA command. In this case the locking-mode must be
98362        ** set on all attached databases, as well as the main db file.
98363        **
98364        ** Also, the sqlite3.dfltLockMode variable is set so that
98365        ** any subsequently attached databases also use the specified
98366        ** locking mode.
98367        */
98368        int ii;
98369        assert(pDb==&db->aDb[0]);
98370        for(ii=2; ii<db->nDb; ii++){
98371          pPager = sqlite3BtreePager(db->aDb[ii].pBt);
98372          sqlite3PagerLockingMode(pPager, eMode);
98373        }
98374        db->dfltLockMode = (u8)eMode;
98375      }
98376      pPager = sqlite3BtreePager(pDb->pBt);
98377      eMode = sqlite3PagerLockingMode(pPager, eMode);
98378    }
98379
98380    assert( eMode==PAGER_LOCKINGMODE_NORMAL
98381            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
98382    if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
98383      zRet = "exclusive";
98384    }
98385    sqlite3VdbeSetNumCols(v, 1);
98386    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
98387    sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
98388    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
98389    break;
98390  }
98391
98392  /*
98393  **  PRAGMA [database.]journal_mode
98394  **  PRAGMA [database.]journal_mode =
98395  **                      (delete|persist|off|truncate|memory|wal|off)
98396  */
98397  case PragTyp_JOURNAL_MODE: {
98398    int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
98399    int ii;           /* Loop counter */
98400
98401    sqlite3VdbeSetNumCols(v, 1);
98402    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
98403
98404    if( zRight==0 ){
98405      /* If there is no "=MODE" part of the pragma, do a query for the
98406      ** current mode */
98407      eMode = PAGER_JOURNALMODE_QUERY;
98408    }else{
98409      const char *zMode;
98410      int n = sqlite3Strlen30(zRight);
98411      for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
98412        if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
98413      }
98414      if( !zMode ){
98415        /* If the "=MODE" part does not match any known journal mode,
98416        ** then do a query */
98417        eMode = PAGER_JOURNALMODE_QUERY;
98418      }
98419    }
98420    if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
98421      /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
98422      iDb = 0;
98423      pId2->n = 1;
98424    }
98425    for(ii=db->nDb-1; ii>=0; ii--){
98426      if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
98427        sqlite3VdbeUsesBtree(v, ii);
98428        sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
98429      }
98430    }
98431    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
98432    break;
98433  }
98434
98435  /*
98436  **  PRAGMA [database.]journal_size_limit
98437  **  PRAGMA [database.]journal_size_limit=N
98438  **
98439  ** Get or set the size limit on rollback journal files.
98440  */
98441  case PragTyp_JOURNAL_SIZE_LIMIT: {
98442    Pager *pPager = sqlite3BtreePager(pDb->pBt);
98443    i64 iLimit = -2;
98444    if( zRight ){
98445      sqlite3Atoi64(zRight, &iLimit, sqlite3Strlen30(zRight), SQLITE_UTF8);
98446      if( iLimit<-1 ) iLimit = -1;
98447    }
98448    iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
98449    returnSingleInt(pParse, "journal_size_limit", iLimit);
98450    break;
98451  }
98452
98453#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
98454
98455  /*
98456  **  PRAGMA [database.]auto_vacuum
98457  **  PRAGMA [database.]auto_vacuum=N
98458  **
98459  ** Get or set the value of the database 'auto-vacuum' parameter.
98460  ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
98461  */
98462#ifndef SQLITE_OMIT_AUTOVACUUM
98463  case PragTyp_AUTO_VACUUM: {
98464    Btree *pBt = pDb->pBt;
98465    assert( pBt!=0 );
98466    if( !zRight ){
98467      returnSingleInt(pParse, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
98468    }else{
98469      int eAuto = getAutoVacuum(zRight);
98470      assert( eAuto>=0 && eAuto<=2 );
98471      db->nextAutovac = (u8)eAuto;
98472      /* Call SetAutoVacuum() to set initialize the internal auto and
98473      ** incr-vacuum flags. This is required in case this connection
98474      ** creates the database file. It is important that it is created
98475      ** as an auto-vacuum capable db.
98476      */
98477      rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
98478      if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
98479        /* When setting the auto_vacuum mode to either "full" or
98480        ** "incremental", write the value of meta[6] in the database
98481        ** file. Before writing to meta[6], check that meta[3] indicates
98482        ** that this really is an auto-vacuum capable database.
98483        */
98484        static const int iLn = VDBE_OFFSET_LINENO(2);
98485        static const VdbeOpList setMeta6[] = {
98486          { OP_Transaction,    0,         1,                 0},    /* 0 */
98487          { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
98488          { OP_If,             1,         0,                 0},    /* 2 */
98489          { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
98490          { OP_Integer,        0,         1,                 0},    /* 4 */
98491          { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
98492        };
98493        int iAddr;
98494        iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
98495        sqlite3VdbeChangeP1(v, iAddr, iDb);
98496        sqlite3VdbeChangeP1(v, iAddr+1, iDb);
98497        sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
98498        sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
98499        sqlite3VdbeChangeP1(v, iAddr+5, iDb);
98500        sqlite3VdbeUsesBtree(v, iDb);
98501      }
98502    }
98503    break;
98504  }
98505#endif
98506
98507  /*
98508  **  PRAGMA [database.]incremental_vacuum(N)
98509  **
98510  ** Do N steps of incremental vacuuming on a database.
98511  */
98512#ifndef SQLITE_OMIT_AUTOVACUUM
98513  case PragTyp_INCREMENTAL_VACUUM: {
98514    int iLimit, addr;
98515    if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
98516      iLimit = 0x7fffffff;
98517    }
98518    sqlite3BeginWriteOperation(pParse, 0, iDb);
98519    sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
98520    addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
98521    sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
98522    sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
98523    sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
98524    sqlite3VdbeJumpHere(v, addr);
98525    break;
98526  }
98527#endif
98528
98529#ifndef SQLITE_OMIT_PAGER_PRAGMAS
98530  /*
98531  **  PRAGMA [database.]cache_size
98532  **  PRAGMA [database.]cache_size=N
98533  **
98534  ** The first form reports the current local setting for the
98535  ** page cache size. The second form sets the local
98536  ** page cache size value.  If N is positive then that is the
98537  ** number of pages in the cache.  If N is negative, then the
98538  ** number of pages is adjusted so that the cache uses -N kibibytes
98539  ** of memory.
98540  */
98541  case PragTyp_CACHE_SIZE: {
98542    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
98543    if( !zRight ){
98544      returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
98545    }else{
98546      int size = sqlite3Atoi(zRight);
98547      pDb->pSchema->cache_size = size;
98548      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
98549    }
98550    break;
98551  }
98552
98553  /*
98554  **  PRAGMA [database.]mmap_size(N)
98555  **
98556  ** Used to set mapping size limit. The mapping size limit is
98557  ** used to limit the aggregate size of all memory mapped regions of the
98558  ** database file. If this parameter is set to zero, then memory mapping
98559  ** is not used at all.  If N is negative, then the default memory map
98560  ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
98561  ** The parameter N is measured in bytes.
98562  **
98563  ** This value is advisory.  The underlying VFS is free to memory map
98564  ** as little or as much as it wants.  Except, if N is set to 0 then the
98565  ** upper layers will never invoke the xFetch interfaces to the VFS.
98566  */
98567  case PragTyp_MMAP_SIZE: {
98568    sqlite3_int64 sz;
98569#if SQLITE_MAX_MMAP_SIZE>0
98570    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
98571    if( zRight ){
98572      int ii;
98573      sqlite3Atoi64(zRight, &sz, sqlite3Strlen30(zRight), SQLITE_UTF8);
98574      if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
98575      if( pId2->n==0 ) db->szMmap = sz;
98576      for(ii=db->nDb-1; ii>=0; ii--){
98577        if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
98578          sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
98579        }
98580      }
98581    }
98582    sz = -1;
98583    rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
98584#else
98585    sz = 0;
98586    rc = SQLITE_OK;
98587#endif
98588    if( rc==SQLITE_OK ){
98589      returnSingleInt(pParse, "mmap_size", sz);
98590    }else if( rc!=SQLITE_NOTFOUND ){
98591      pParse->nErr++;
98592      pParse->rc = rc;
98593    }
98594    break;
98595  }
98596
98597  /*
98598  **   PRAGMA temp_store
98599  **   PRAGMA temp_store = "default"|"memory"|"file"
98600  **
98601  ** Return or set the local value of the temp_store flag.  Changing
98602  ** the local value does not make changes to the disk file and the default
98603  ** value will be restored the next time the database is opened.
98604  **
98605  ** Note that it is possible for the library compile-time options to
98606  ** override this setting
98607  */
98608  case PragTyp_TEMP_STORE: {
98609    if( !zRight ){
98610      returnSingleInt(pParse, "temp_store", db->temp_store);
98611    }else{
98612      changeTempStorage(pParse, zRight);
98613    }
98614    break;
98615  }
98616
98617  /*
98618  **   PRAGMA temp_store_directory
98619  **   PRAGMA temp_store_directory = ""|"directory_name"
98620  **
98621  ** Return or set the local value of the temp_store_directory flag.  Changing
98622  ** the value sets a specific directory to be used for temporary files.
98623  ** Setting to a null string reverts to the default temporary directory search.
98624  ** If temporary directory is changed, then invalidateTempStorage.
98625  **
98626  */
98627  case PragTyp_TEMP_STORE_DIRECTORY: {
98628    if( !zRight ){
98629      if( sqlite3_temp_directory ){
98630        sqlite3VdbeSetNumCols(v, 1);
98631        sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
98632            "temp_store_directory", SQLITE_STATIC);
98633        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
98634        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
98635      }
98636    }else{
98637#ifndef SQLITE_OMIT_WSD
98638      if( zRight[0] ){
98639        int res;
98640        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
98641        if( rc!=SQLITE_OK || res==0 ){
98642          sqlite3ErrorMsg(pParse, "not a writable directory");
98643          goto pragma_out;
98644        }
98645      }
98646      if( SQLITE_TEMP_STORE==0
98647       || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
98648       || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
98649      ){
98650        invalidateTempStorage(pParse);
98651      }
98652      sqlite3_free(sqlite3_temp_directory);
98653      if( zRight[0] ){
98654        sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
98655      }else{
98656        sqlite3_temp_directory = 0;
98657      }
98658#endif /* SQLITE_OMIT_WSD */
98659    }
98660    break;
98661  }
98662
98663#if SQLITE_OS_WIN
98664  /*
98665  **   PRAGMA data_store_directory
98666  **   PRAGMA data_store_directory = ""|"directory_name"
98667  **
98668  ** Return or set the local value of the data_store_directory flag.  Changing
98669  ** the value sets a specific directory to be used for database files that
98670  ** were specified with a relative pathname.  Setting to a null string reverts
98671  ** to the default database directory, which for database files specified with
98672  ** a relative path will probably be based on the current directory for the
98673  ** process.  Database file specified with an absolute path are not impacted
98674  ** by this setting, regardless of its value.
98675  **
98676  */
98677  case PragTyp_DATA_STORE_DIRECTORY: {
98678    if( !zRight ){
98679      if( sqlite3_data_directory ){
98680        sqlite3VdbeSetNumCols(v, 1);
98681        sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
98682            "data_store_directory", SQLITE_STATIC);
98683        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);
98684        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
98685      }
98686    }else{
98687#ifndef SQLITE_OMIT_WSD
98688      if( zRight[0] ){
98689        int res;
98690        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
98691        if( rc!=SQLITE_OK || res==0 ){
98692          sqlite3ErrorMsg(pParse, "not a writable directory");
98693          goto pragma_out;
98694        }
98695      }
98696      sqlite3_free(sqlite3_data_directory);
98697      if( zRight[0] ){
98698        sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
98699      }else{
98700        sqlite3_data_directory = 0;
98701      }
98702#endif /* SQLITE_OMIT_WSD */
98703    }
98704    break;
98705  }
98706#endif
98707
98708#if SQLITE_ENABLE_LOCKING_STYLE
98709  /*
98710  **   PRAGMA [database.]lock_proxy_file
98711  **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
98712  **
98713  ** Return or set the value of the lock_proxy_file flag.  Changing
98714  ** the value sets a specific file to be used for database access locks.
98715  **
98716  */
98717  case PragTyp_LOCK_PROXY_FILE: {
98718    if( !zRight ){
98719      Pager *pPager = sqlite3BtreePager(pDb->pBt);
98720      char *proxy_file_path = NULL;
98721      sqlite3_file *pFile = sqlite3PagerFile(pPager);
98722      sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
98723                           &proxy_file_path);
98724
98725      if( proxy_file_path ){
98726        sqlite3VdbeSetNumCols(v, 1);
98727        sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
98728                              "lock_proxy_file", SQLITE_STATIC);
98729        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
98730        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
98731      }
98732    }else{
98733      Pager *pPager = sqlite3BtreePager(pDb->pBt);
98734      sqlite3_file *pFile = sqlite3PagerFile(pPager);
98735      int res;
98736      if( zRight[0] ){
98737        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
98738                                     zRight);
98739      } else {
98740        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
98741                                     NULL);
98742      }
98743      if( res!=SQLITE_OK ){
98744        sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
98745        goto pragma_out;
98746      }
98747    }
98748    break;
98749  }
98750#endif /* SQLITE_ENABLE_LOCKING_STYLE */
98751
98752  /*
98753  **   PRAGMA [database.]synchronous
98754  **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
98755  **
98756  ** Return or set the local value of the synchronous flag.  Changing
98757  ** the local value does not make changes to the disk file and the
98758  ** default value will be restored the next time the database is
98759  ** opened.
98760  */
98761  case PragTyp_SYNCHRONOUS: {
98762    if( !zRight ){
98763      returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
98764    }else{
98765      if( !db->autoCommit ){
98766        sqlite3ErrorMsg(pParse,
98767            "Safety level may not be changed inside a transaction");
98768      }else{
98769        pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
98770        setAllPagerFlags(db);
98771      }
98772    }
98773    break;
98774  }
98775#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
98776
98777#ifndef SQLITE_OMIT_FLAG_PRAGMAS
98778  case PragTyp_FLAG: {
98779    if( zRight==0 ){
98780      returnSingleInt(pParse, aPragmaNames[mid].zName,
98781                     (db->flags & aPragmaNames[mid].iArg)!=0 );
98782    }else{
98783      int mask = aPragmaNames[mid].iArg;    /* Mask of bits to set or clear. */
98784      if( db->autoCommit==0 ){
98785        /* Foreign key support may not be enabled or disabled while not
98786        ** in auto-commit mode.  */
98787        mask &= ~(SQLITE_ForeignKeys);
98788      }
98789
98790      if( sqlite3GetBoolean(zRight, 0) ){
98791        db->flags |= mask;
98792      }else{
98793        db->flags &= ~mask;
98794        if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
98795      }
98796
98797      /* Many of the flag-pragmas modify the code generated by the SQL
98798      ** compiler (eg. count_changes). So add an opcode to expire all
98799      ** compiled SQL statements after modifying a pragma value.
98800      */
98801      sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
98802      setAllPagerFlags(db);
98803    }
98804    break;
98805  }
98806#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
98807
98808#ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
98809  /*
98810  **   PRAGMA table_info(<table>)
98811  **
98812  ** Return a single row for each column of the named table. The columns of
98813  ** the returned data set are:
98814  **
98815  ** cid:        Column id (numbered from left to right, starting at 0)
98816  ** name:       Column name
98817  ** type:       Column declaration type.
98818  ** notnull:    True if 'NOT NULL' is part of column declaration
98819  ** dflt_value: The default value for the column, if any.
98820  */
98821  case PragTyp_TABLE_INFO: if( zRight ){
98822    Table *pTab;
98823    pTab = sqlite3FindTable(db, zRight, zDb);
98824    if( pTab ){
98825      int i, k;
98826      int nHidden = 0;
98827      Column *pCol;
98828      Index *pPk = sqlite3PrimaryKeyIndex(pTab);
98829      sqlite3VdbeSetNumCols(v, 6);
98830      pParse->nMem = 6;
98831      sqlite3CodeVerifySchema(pParse, iDb);
98832      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
98833      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
98834      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
98835      sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
98836      sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
98837      sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
98838      sqlite3ViewGetColumnNames(pParse, pTab);
98839      for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
98840        if( IsHiddenColumn(pCol) ){
98841          nHidden++;
98842          continue;
98843        }
98844        sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
98845        sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
98846        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
98847           pCol->zType ? pCol->zType : "", 0);
98848        sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
98849        if( pCol->zDflt ){
98850          sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
98851        }else{
98852          sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
98853        }
98854        if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
98855          k = 0;
98856        }else if( pPk==0 ){
98857          k = 1;
98858        }else{
98859          for(k=1; ALWAYS(k<=pTab->nCol) && pPk->aiColumn[k-1]!=i; k++){}
98860        }
98861        sqlite3VdbeAddOp2(v, OP_Integer, k, 6);
98862        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
98863      }
98864    }
98865  }
98866  break;
98867
98868  case PragTyp_STATS: {
98869    Index *pIdx;
98870    HashElem *i;
98871    v = sqlite3GetVdbe(pParse);
98872    sqlite3VdbeSetNumCols(v, 4);
98873    pParse->nMem = 4;
98874    sqlite3CodeVerifySchema(pParse, iDb);
98875    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
98876    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "index", SQLITE_STATIC);
98877    sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "width", SQLITE_STATIC);
98878    sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "height", SQLITE_STATIC);
98879    for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
98880      Table *pTab = sqliteHashData(i);
98881      sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, pTab->zName, 0);
98882      sqlite3VdbeAddOp2(v, OP_Null, 0, 2);
98883      sqlite3VdbeAddOp2(v, OP_Integer,
98884                           (int)sqlite3LogEstToInt(pTab->szTabRow), 3);
98885      sqlite3VdbeAddOp2(v, OP_Integer,
98886          (int)sqlite3LogEstToInt(pTab->nRowLogEst), 4);
98887      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
98888      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
98889        sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
98890        sqlite3VdbeAddOp2(v, OP_Integer,
98891                             (int)sqlite3LogEstToInt(pIdx->szIdxRow), 3);
98892        sqlite3VdbeAddOp2(v, OP_Integer,
98893            (int)sqlite3LogEstToInt(pIdx->aiRowLogEst[0]), 4);
98894        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
98895      }
98896    }
98897  }
98898  break;
98899
98900  case PragTyp_INDEX_INFO: if( zRight ){
98901    Index *pIdx;
98902    Table *pTab;
98903    pIdx = sqlite3FindIndex(db, zRight, zDb);
98904    if( pIdx ){
98905      int i;
98906      pTab = pIdx->pTable;
98907      sqlite3VdbeSetNumCols(v, 3);
98908      pParse->nMem = 3;
98909      sqlite3CodeVerifySchema(pParse, iDb);
98910      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
98911      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
98912      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
98913      for(i=0; i<pIdx->nKeyCol; i++){
98914        i16 cnum = pIdx->aiColumn[i];
98915        sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
98916        sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
98917        assert( pTab->nCol>cnum );
98918        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
98919        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
98920      }
98921    }
98922  }
98923  break;
98924
98925  case PragTyp_INDEX_LIST: if( zRight ){
98926    Index *pIdx;
98927    Table *pTab;
98928    int i;
98929    pTab = sqlite3FindTable(db, zRight, zDb);
98930    if( pTab ){
98931      v = sqlite3GetVdbe(pParse);
98932      sqlite3VdbeSetNumCols(v, 3);
98933      pParse->nMem = 3;
98934      sqlite3CodeVerifySchema(pParse, iDb);
98935      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
98936      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
98937      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
98938      for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
98939        sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
98940        sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
98941        sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
98942        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
98943      }
98944    }
98945  }
98946  break;
98947
98948  case PragTyp_DATABASE_LIST: {
98949    int i;
98950    sqlite3VdbeSetNumCols(v, 3);
98951    pParse->nMem = 3;
98952    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
98953    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
98954    sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
98955    for(i=0; i<db->nDb; i++){
98956      if( db->aDb[i].pBt==0 ) continue;
98957      assert( db->aDb[i].zName!=0 );
98958      sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
98959      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
98960      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
98961           sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
98962      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
98963    }
98964  }
98965  break;
98966
98967  case PragTyp_COLLATION_LIST: {
98968    int i = 0;
98969    HashElem *p;
98970    sqlite3VdbeSetNumCols(v, 2);
98971    pParse->nMem = 2;
98972    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
98973    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
98974    for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
98975      CollSeq *pColl = (CollSeq *)sqliteHashData(p);
98976      sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
98977      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
98978      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
98979    }
98980  }
98981  break;
98982#endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
98983
98984#ifndef SQLITE_OMIT_FOREIGN_KEY
98985  case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
98986    FKey *pFK;
98987    Table *pTab;
98988    pTab = sqlite3FindTable(db, zRight, zDb);
98989    if( pTab ){
98990      v = sqlite3GetVdbe(pParse);
98991      pFK = pTab->pFKey;
98992      if( pFK ){
98993        int i = 0;
98994        sqlite3VdbeSetNumCols(v, 8);
98995        pParse->nMem = 8;
98996        sqlite3CodeVerifySchema(pParse, iDb);
98997        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
98998        sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
98999        sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
99000        sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
99001        sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
99002        sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
99003        sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
99004        sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
99005        while(pFK){
99006          int j;
99007          for(j=0; j<pFK->nCol; j++){
99008            char *zCol = pFK->aCol[j].zCol;
99009            char *zOnDelete = (char *)actionName(pFK->aAction[0]);
99010            char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
99011            sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
99012            sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
99013            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
99014            sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
99015                              pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
99016            sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
99017            sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
99018            sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
99019            sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
99020            sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
99021          }
99022          ++i;
99023          pFK = pFK->pNextFrom;
99024        }
99025      }
99026    }
99027  }
99028  break;
99029#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
99030
99031#ifndef SQLITE_OMIT_FOREIGN_KEY
99032#ifndef SQLITE_OMIT_TRIGGER
99033  case PragTyp_FOREIGN_KEY_CHECK: {
99034    FKey *pFK;             /* A foreign key constraint */
99035    Table *pTab;           /* Child table contain "REFERENCES" keyword */
99036    Table *pParent;        /* Parent table that child points to */
99037    Index *pIdx;           /* Index in the parent table */
99038    int i;                 /* Loop counter:  Foreign key number for pTab */
99039    int j;                 /* Loop counter:  Field of the foreign key */
99040    HashElem *k;           /* Loop counter:  Next table in schema */
99041    int x;                 /* result variable */
99042    int regResult;         /* 3 registers to hold a result row */
99043    int regKey;            /* Register to hold key for checking the FK */
99044    int regRow;            /* Registers to hold a row from pTab */
99045    int addrTop;           /* Top of a loop checking foreign keys */
99046    int addrOk;            /* Jump here if the key is OK */
99047    int *aiCols;           /* child to parent column mapping */
99048
99049    regResult = pParse->nMem+1;
99050    pParse->nMem += 4;
99051    regKey = ++pParse->nMem;
99052    regRow = ++pParse->nMem;
99053    v = sqlite3GetVdbe(pParse);
99054    sqlite3VdbeSetNumCols(v, 4);
99055    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
99056    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "rowid", SQLITE_STATIC);
99057    sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "parent", SQLITE_STATIC);
99058    sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "fkid", SQLITE_STATIC);
99059    sqlite3CodeVerifySchema(pParse, iDb);
99060    k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
99061    while( k ){
99062      if( zRight ){
99063        pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
99064        k = 0;
99065      }else{
99066        pTab = (Table*)sqliteHashData(k);
99067        k = sqliteHashNext(k);
99068      }
99069      if( pTab==0 || pTab->pFKey==0 ) continue;
99070      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
99071      if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
99072      sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
99073      sqlite3VdbeAddOp4(v, OP_String8, 0, regResult, 0, pTab->zName,
99074                        P4_TRANSIENT);
99075      for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
99076        pParent = sqlite3FindTable(db, pFK->zTo, zDb);
99077        if( pParent==0 ) continue;
99078        pIdx = 0;
99079        sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
99080        x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
99081        if( x==0 ){
99082          if( pIdx==0 ){
99083            sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
99084          }else{
99085            sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
99086            sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
99087          }
99088        }else{
99089          k = 0;
99090          break;
99091        }
99092      }
99093      assert( pParse->nErr>0 || pFK==0 );
99094      if( pFK ) break;
99095      if( pParse->nTab<i ) pParse->nTab = i;
99096      addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
99097      for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
99098        pParent = sqlite3FindTable(db, pFK->zTo, zDb);
99099        pIdx = 0;
99100        aiCols = 0;
99101        if( pParent ){
99102          x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
99103          assert( x==0 );
99104        }
99105        addrOk = sqlite3VdbeMakeLabel(v);
99106        if( pParent && pIdx==0 ){
99107          int iKey = pFK->aCol[0].iFrom;
99108          assert( iKey>=0 && iKey<pTab->nCol );
99109          if( iKey!=pTab->iPKey ){
99110            sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
99111            sqlite3ColumnDefault(v, pTab, iKey, regRow);
99112            sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v);
99113            sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow,
99114               sqlite3VdbeCurrentAddr(v)+3); VdbeCoverage(v);
99115          }else{
99116            sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
99117          }
99118          sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow); VdbeCoverage(v);
99119          sqlite3VdbeAddOp2(v, OP_Goto, 0, addrOk);
99120          sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
99121        }else{
99122          for(j=0; j<pFK->nCol; j++){
99123            sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
99124                            aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
99125            sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
99126          }
99127          if( pParent ){
99128            sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
99129                              sqlite3IndexAffinityStr(v,pIdx), pFK->nCol);
99130            sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
99131            VdbeCoverage(v);
99132          }
99133        }
99134        sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
99135        sqlite3VdbeAddOp4(v, OP_String8, 0, regResult+2, 0,
99136                          pFK->zTo, P4_TRANSIENT);
99137        sqlite3VdbeAddOp2(v, OP_Integer, i-1, regResult+3);
99138        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
99139        sqlite3VdbeResolveLabel(v, addrOk);
99140        sqlite3DbFree(db, aiCols);
99141      }
99142      sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
99143      sqlite3VdbeJumpHere(v, addrTop);
99144    }
99145  }
99146  break;
99147#endif /* !defined(SQLITE_OMIT_TRIGGER) */
99148#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
99149
99150#ifndef NDEBUG
99151  case PragTyp_PARSER_TRACE: {
99152    if( zRight ){
99153      if( sqlite3GetBoolean(zRight, 0) ){
99154        sqlite3ParserTrace(stderr, "parser: ");
99155      }else{
99156        sqlite3ParserTrace(0, 0);
99157      }
99158    }
99159  }
99160  break;
99161#endif
99162
99163  /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
99164  ** used will be case sensitive or not depending on the RHS.
99165  */
99166  case PragTyp_CASE_SENSITIVE_LIKE: {
99167    if( zRight ){
99168      sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
99169    }
99170  }
99171  break;
99172
99173#ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
99174# define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
99175#endif
99176
99177#ifndef SQLITE_OMIT_INTEGRITY_CHECK
99178  /* Pragma "quick_check" is reduced version of
99179  ** integrity_check designed to detect most database corruption
99180  ** without most of the overhead of a full integrity-check.
99181  */
99182  case PragTyp_INTEGRITY_CHECK: {
99183    int i, j, addr, mxErr;
99184
99185    /* Code that appears at the end of the integrity check.  If no error
99186    ** messages have been generated, output OK.  Otherwise output the
99187    ** error message
99188    */
99189    static const int iLn = VDBE_OFFSET_LINENO(2);
99190    static const VdbeOpList endCode[] = {
99191      { OP_AddImm,      1, 0,        0},    /* 0 */
99192      { OP_IfNeg,       1, 0,        0},    /* 1 */
99193      { OP_String8,     0, 3,        0},    /* 2 */
99194      { OP_ResultRow,   3, 1,        0},
99195    };
99196
99197    int isQuick = (sqlite3Tolower(zLeft[0])=='q');
99198
99199    /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
99200    ** then iDb is set to the index of the database identified by <db>.
99201    ** In this case, the integrity of database iDb only is verified by
99202    ** the VDBE created below.
99203    **
99204    ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
99205    ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
99206    ** to -1 here, to indicate that the VDBE should verify the integrity
99207    ** of all attached databases.  */
99208    assert( iDb>=0 );
99209    assert( iDb==0 || pId2->z );
99210    if( pId2->z==0 ) iDb = -1;
99211
99212    /* Initialize the VDBE program */
99213    pParse->nMem = 6;
99214    sqlite3VdbeSetNumCols(v, 1);
99215    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
99216
99217    /* Set the maximum error count */
99218    mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
99219    if( zRight ){
99220      sqlite3GetInt32(zRight, &mxErr);
99221      if( mxErr<=0 ){
99222        mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
99223      }
99224    }
99225    sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
99226
99227    /* Do an integrity check on each database file */
99228    for(i=0; i<db->nDb; i++){
99229      HashElem *x;
99230      Hash *pTbls;
99231      int cnt = 0;
99232
99233      if( OMIT_TEMPDB && i==1 ) continue;
99234      if( iDb>=0 && i!=iDb ) continue;
99235
99236      sqlite3CodeVerifySchema(pParse, i);
99237      addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
99238      VdbeCoverage(v);
99239      sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
99240      sqlite3VdbeJumpHere(v, addr);
99241
99242      /* Do an integrity check of the B-Tree
99243      **
99244      ** Begin by filling registers 2, 3, ... with the root pages numbers
99245      ** for all tables and indices in the database.
99246      */
99247      assert( sqlite3SchemaMutexHeld(db, i, 0) );
99248      pTbls = &db->aDb[i].pSchema->tblHash;
99249      for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
99250        Table *pTab = sqliteHashData(x);
99251        Index *pIdx;
99252        if( HasRowid(pTab) ){
99253          sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
99254          VdbeComment((v, "%s", pTab->zName));
99255          cnt++;
99256        }
99257        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
99258          sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
99259          VdbeComment((v, "%s", pIdx->zName));
99260          cnt++;
99261        }
99262      }
99263
99264      /* Make sure sufficient number of registers have been allocated */
99265      pParse->nMem = MAX( pParse->nMem, cnt+8 );
99266
99267      /* Do the b-tree integrity checks */
99268      sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
99269      sqlite3VdbeChangeP5(v, (u8)i);
99270      addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
99271      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
99272         sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
99273         P4_DYNAMIC);
99274      sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
99275      sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
99276      sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
99277      sqlite3VdbeJumpHere(v, addr);
99278
99279      /* Make sure all the indices are constructed correctly.
99280      */
99281      for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
99282        Table *pTab = sqliteHashData(x);
99283        Index *pIdx, *pPk;
99284        Index *pPrior = 0;
99285        int loopTop;
99286        int iDataCur, iIdxCur;
99287        int r1 = -1;
99288
99289        if( pTab->pIndex==0 ) continue;
99290        pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
99291        addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
99292        VdbeCoverage(v);
99293        sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
99294        sqlite3VdbeJumpHere(v, addr);
99295        sqlite3ExprCacheClear(pParse);
99296        sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead,
99297                                   1, 0, &iDataCur, &iIdxCur);
99298        sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
99299        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
99300          sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
99301        }
99302        pParse->nMem = MAX(pParse->nMem, 8+j);
99303        sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
99304        loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
99305        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
99306          int jmp2, jmp3, jmp4;
99307          if( pPk==pIdx ) continue;
99308          r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
99309                                       pPrior, r1);
99310          pPrior = pIdx;
99311          sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);  /* increment entry count */
99312          jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, 0, r1,
99313                                      pIdx->nColumn); VdbeCoverage(v);
99314          sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
99315          sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, "row ", P4_STATIC);
99316          sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
99317          sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0, " missing from index ",
99318                            P4_STATIC);
99319          sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
99320          sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0, pIdx->zName, P4_TRANSIENT);
99321          sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
99322          sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
99323          jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
99324          sqlite3VdbeAddOp0(v, OP_Halt);
99325          sqlite3VdbeJumpHere(v, jmp4);
99326          sqlite3VdbeJumpHere(v, jmp2);
99327          sqlite3ResolvePartIdxLabel(pParse, jmp3);
99328        }
99329        sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
99330        sqlite3VdbeJumpHere(v, loopTop-1);
99331#ifndef SQLITE_OMIT_BTREECOUNT
99332        sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0,
99333                     "wrong # of entries in index ", P4_STATIC);
99334        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
99335          if( pPk==pIdx ) continue;
99336          addr = sqlite3VdbeCurrentAddr(v);
99337          sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); VdbeCoverage(v);
99338          sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
99339          sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
99340          sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3); VdbeCoverage(v);
99341          sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
99342          sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
99343          sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pIdx->zName, P4_TRANSIENT);
99344          sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
99345          sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
99346        }
99347#endif /* SQLITE_OMIT_BTREECOUNT */
99348      }
99349    }
99350    addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
99351    sqlite3VdbeChangeP2(v, addr, -mxErr);
99352    sqlite3VdbeJumpHere(v, addr+1);
99353    sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
99354  }
99355  break;
99356#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
99357
99358#ifndef SQLITE_OMIT_UTF16
99359  /*
99360  **   PRAGMA encoding
99361  **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
99362  **
99363  ** In its first form, this pragma returns the encoding of the main
99364  ** database. If the database is not initialized, it is initialized now.
99365  **
99366  ** The second form of this pragma is a no-op if the main database file
99367  ** has not already been initialized. In this case it sets the default
99368  ** encoding that will be used for the main database file if a new file
99369  ** is created. If an existing main database file is opened, then the
99370  ** default text encoding for the existing database is used.
99371  **
99372  ** In all cases new databases created using the ATTACH command are
99373  ** created to use the same default text encoding as the main database. If
99374  ** the main database has not been initialized and/or created when ATTACH
99375  ** is executed, this is done before the ATTACH operation.
99376  **
99377  ** In the second form this pragma sets the text encoding to be used in
99378  ** new database files created using this database handle. It is only
99379  ** useful if invoked immediately after the main database i
99380  */
99381  case PragTyp_ENCODING: {
99382    static const struct EncName {
99383      char *zName;
99384      u8 enc;
99385    } encnames[] = {
99386      { "UTF8",     SQLITE_UTF8        },
99387      { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
99388      { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
99389      { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
99390      { "UTF16le",  SQLITE_UTF16LE     },
99391      { "UTF16be",  SQLITE_UTF16BE     },
99392      { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
99393      { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
99394      { 0, 0 }
99395    };
99396    const struct EncName *pEnc;
99397    if( !zRight ){    /* "PRAGMA encoding" */
99398      if( sqlite3ReadSchema(pParse) ) goto pragma_out;
99399      sqlite3VdbeSetNumCols(v, 1);
99400      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
99401      sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
99402      assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
99403      assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
99404      assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
99405      sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
99406      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
99407    }else{                        /* "PRAGMA encoding = XXX" */
99408      /* Only change the value of sqlite.enc if the database handle is not
99409      ** initialized. If the main database exists, the new sqlite.enc value
99410      ** will be overwritten when the schema is next loaded. If it does not
99411      ** already exists, it will be created to use the new encoding value.
99412      */
99413      if(
99414        !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
99415        DbHasProperty(db, 0, DB_Empty)
99416      ){
99417        for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
99418          if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
99419            ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
99420            break;
99421          }
99422        }
99423        if( !pEnc->zName ){
99424          sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
99425        }
99426      }
99427    }
99428  }
99429  break;
99430#endif /* SQLITE_OMIT_UTF16 */
99431
99432#ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
99433  /*
99434  **   PRAGMA [database.]schema_version
99435  **   PRAGMA [database.]schema_version = <integer>
99436  **
99437  **   PRAGMA [database.]user_version
99438  **   PRAGMA [database.]user_version = <integer>
99439  **
99440  **   PRAGMA [database.]freelist_count = <integer>
99441  **
99442  **   PRAGMA [database.]application_id
99443  **   PRAGMA [database.]application_id = <integer>
99444  **
99445  ** The pragma's schema_version and user_version are used to set or get
99446  ** the value of the schema-version and user-version, respectively. Both
99447  ** the schema-version and the user-version are 32-bit signed integers
99448  ** stored in the database header.
99449  **
99450  ** The schema-cookie is usually only manipulated internally by SQLite. It
99451  ** is incremented by SQLite whenever the database schema is modified (by
99452  ** creating or dropping a table or index). The schema version is used by
99453  ** SQLite each time a query is executed to ensure that the internal cache
99454  ** of the schema used when compiling the SQL query matches the schema of
99455  ** the database against which the compiled query is actually executed.
99456  ** Subverting this mechanism by using "PRAGMA schema_version" to modify
99457  ** the schema-version is potentially dangerous and may lead to program
99458  ** crashes or database corruption. Use with caution!
99459  **
99460  ** The user-version is not used internally by SQLite. It may be used by
99461  ** applications for any purpose.
99462  */
99463  case PragTyp_HEADER_VALUE: {
99464    int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
99465    sqlite3VdbeUsesBtree(v, iDb);
99466    switch( zLeft[0] ){
99467      case 'a': case 'A':
99468        iCookie = BTREE_APPLICATION_ID;
99469        break;
99470      case 'f': case 'F':
99471        iCookie = BTREE_FREE_PAGE_COUNT;
99472        break;
99473      case 's': case 'S':
99474        iCookie = BTREE_SCHEMA_VERSION;
99475        break;
99476      default:
99477        iCookie = BTREE_USER_VERSION;
99478        break;
99479    }
99480
99481    if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
99482      /* Write the specified cookie value */
99483      static const VdbeOpList setCookie[] = {
99484        { OP_Transaction,    0,  1,  0},    /* 0 */
99485        { OP_Integer,        0,  1,  0},    /* 1 */
99486        { OP_SetCookie,      0,  0,  1},    /* 2 */
99487      };
99488      int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
99489      sqlite3VdbeChangeP1(v, addr, iDb);
99490      sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
99491      sqlite3VdbeChangeP1(v, addr+2, iDb);
99492      sqlite3VdbeChangeP2(v, addr+2, iCookie);
99493    }else{
99494      /* Read the specified cookie value */
99495      static const VdbeOpList readCookie[] = {
99496        { OP_Transaction,     0,  0,  0},    /* 0 */
99497        { OP_ReadCookie,      0,  1,  0},    /* 1 */
99498        { OP_ResultRow,       1,  1,  0}
99499      };
99500      int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie, 0);
99501      sqlite3VdbeChangeP1(v, addr, iDb);
99502      sqlite3VdbeChangeP1(v, addr+1, iDb);
99503      sqlite3VdbeChangeP3(v, addr+1, iCookie);
99504      sqlite3VdbeSetNumCols(v, 1);
99505      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
99506    }
99507  }
99508  break;
99509#endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
99510
99511#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
99512  /*
99513  **   PRAGMA compile_options
99514  **
99515  ** Return the names of all compile-time options used in this build,
99516  ** one option per row.
99517  */
99518  case PragTyp_COMPILE_OPTIONS: {
99519    int i = 0;
99520    const char *zOpt;
99521    sqlite3VdbeSetNumCols(v, 1);
99522    pParse->nMem = 1;
99523    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
99524    while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
99525      sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
99526      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
99527    }
99528  }
99529  break;
99530#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
99531
99532#ifndef SQLITE_OMIT_WAL
99533  /*
99534  **   PRAGMA [database.]wal_checkpoint = passive|full|restart
99535  **
99536  ** Checkpoint the database.
99537  */
99538  case PragTyp_WAL_CHECKPOINT: {
99539    int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
99540    int eMode = SQLITE_CHECKPOINT_PASSIVE;
99541    if( zRight ){
99542      if( sqlite3StrICmp(zRight, "full")==0 ){
99543        eMode = SQLITE_CHECKPOINT_FULL;
99544      }else if( sqlite3StrICmp(zRight, "restart")==0 ){
99545        eMode = SQLITE_CHECKPOINT_RESTART;
99546      }
99547    }
99548    sqlite3VdbeSetNumCols(v, 3);
99549    pParse->nMem = 3;
99550    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
99551    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
99552    sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
99553
99554    sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
99555    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
99556  }
99557  break;
99558
99559  /*
99560  **   PRAGMA wal_autocheckpoint
99561  **   PRAGMA wal_autocheckpoint = N
99562  **
99563  ** Configure a database connection to automatically checkpoint a database
99564  ** after accumulating N frames in the log. Or query for the current value
99565  ** of N.
99566  */
99567  case PragTyp_WAL_AUTOCHECKPOINT: {
99568    if( zRight ){
99569      sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
99570    }
99571    returnSingleInt(pParse, "wal_autocheckpoint",
99572       db->xWalCallback==sqlite3WalDefaultHook ?
99573           SQLITE_PTR_TO_INT(db->pWalArg) : 0);
99574  }
99575  break;
99576#endif
99577
99578  /*
99579  **  PRAGMA shrink_memory
99580  **
99581  ** This pragma attempts to free as much memory as possible from the
99582  ** current database connection.
99583  */
99584  case PragTyp_SHRINK_MEMORY: {
99585    sqlite3_db_release_memory(db);
99586    break;
99587  }
99588
99589  /*
99590  **   PRAGMA busy_timeout
99591  **   PRAGMA busy_timeout = N
99592  **
99593  ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value
99594  ** if one is set.  If no busy handler or a different busy handler is set
99595  ** then 0 is returned.  Setting the busy_timeout to 0 or negative
99596  ** disables the timeout.
99597  */
99598  /*case PragTyp_BUSY_TIMEOUT*/ default: {
99599    assert( aPragmaNames[mid].ePragTyp==PragTyp_BUSY_TIMEOUT );
99600    if( zRight ){
99601      sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
99602    }
99603    returnSingleInt(pParse, "timeout",  db->busyTimeout);
99604    break;
99605  }
99606
99607  /*
99608  **   PRAGMA soft_heap_limit
99609  **   PRAGMA soft_heap_limit = N
99610  **
99611  ** Call sqlite3_soft_heap_limit64(N).  Return the result.  If N is omitted,
99612  ** use -1.
99613  */
99614  case PragTyp_SOFT_HEAP_LIMIT: {
99615    sqlite3_int64 N;
99616    if( zRight && sqlite3Atoi64(zRight, &N, 1000000, SQLITE_UTF8)==SQLITE_OK ){
99617      sqlite3_soft_heap_limit64(N);
99618    }
99619    returnSingleInt(pParse, "soft_heap_limit",  sqlite3_soft_heap_limit64(-1));
99620    break;
99621  }
99622
99623#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
99624  /*
99625  ** Report the current state of file logs for all databases
99626  */
99627  case PragTyp_LOCK_STATUS: {
99628    static const char *const azLockName[] = {
99629      "unlocked", "shared", "reserved", "pending", "exclusive"
99630    };
99631    int i;
99632    sqlite3VdbeSetNumCols(v, 2);
99633    pParse->nMem = 2;
99634    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
99635    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
99636    for(i=0; i<db->nDb; i++){
99637      Btree *pBt;
99638      const char *zState = "unknown";
99639      int j;
99640      if( db->aDb[i].zName==0 ) continue;
99641      sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
99642      pBt = db->aDb[i].pBt;
99643      if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
99644        zState = "closed";
99645      }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
99646                                     SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
99647         zState = azLockName[j];
99648      }
99649      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
99650      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
99651    }
99652    break;
99653  }
99654#endif
99655
99656#ifdef SQLITE_HAS_CODEC
99657  case PragTyp_KEY: {
99658    if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
99659    break;
99660  }
99661  case PragTyp_REKEY: {
99662    if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
99663    break;
99664  }
99665  case PragTyp_HEXKEY: {
99666    if( zRight ){
99667      u8 iByte;
99668      int i;
99669      char zKey[40];
99670      for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
99671        iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
99672        if( (i&1)!=0 ) zKey[i/2] = iByte;
99673      }
99674      if( (zLeft[3] & 0xf)==0xb ){
99675        sqlite3_key_v2(db, zDb, zKey, i/2);
99676      }else{
99677        sqlite3_rekey_v2(db, zDb, zKey, i/2);
99678      }
99679    }
99680    break;
99681  }
99682#endif
99683#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
99684  case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
99685#ifdef SQLITE_HAS_CODEC
99686    if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
99687      sqlite3_activate_see(&zRight[4]);
99688    }
99689#endif
99690#ifdef SQLITE_ENABLE_CEROD
99691    if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
99692      sqlite3_activate_cerod(&zRight[6]);
99693    }
99694#endif
99695  }
99696  break;
99697#endif
99698
99699  } /* End of the PRAGMA switch */
99700
99701pragma_out:
99702  sqlite3DbFree(db, zLeft);
99703  sqlite3DbFree(db, zRight);
99704}
99705
99706#endif /* SQLITE_OMIT_PRAGMA */
99707
99708/************** End of pragma.c **********************************************/
99709/************** Begin file prepare.c *****************************************/
99710/*
99711** 2005 May 25
99712**
99713** The author disclaims copyright to this source code.  In place of
99714** a legal notice, here is a blessing:
99715**
99716**    May you do good and not evil.
99717**    May you find forgiveness for yourself and forgive others.
99718**    May you share freely, never taking more than you give.
99719**
99720*************************************************************************
99721** This file contains the implementation of the sqlite3_prepare()
99722** interface, and routines that contribute to loading the database schema
99723** from disk.
99724*/
99725
99726/*
99727** Fill the InitData structure with an error message that indicates
99728** that the database is corrupt.
99729*/
99730static void corruptSchema(
99731  InitData *pData,     /* Initialization context */
99732  const char *zObj,    /* Object being parsed at the point of error */
99733  const char *zExtra   /* Error information */
99734){
99735  sqlite3 *db = pData->db;
99736  if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
99737    if( zObj==0 ) zObj = "?";
99738    sqlite3SetString(pData->pzErrMsg, db,
99739      "malformed database schema (%s)", zObj);
99740    if( zExtra ){
99741      *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
99742                                 "%s - %s", *pData->pzErrMsg, zExtra);
99743    }
99744  }
99745  pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
99746}
99747
99748/*
99749** This is the callback routine for the code that initializes the
99750** database.  See sqlite3Init() below for additional information.
99751** This routine is also called from the OP_ParseSchema opcode of the VDBE.
99752**
99753** Each callback contains the following information:
99754**
99755**     argv[0] = name of thing being created
99756**     argv[1] = root page number for table or index. 0 for trigger or view.
99757**     argv[2] = SQL text for the CREATE statement.
99758**
99759*/
99760SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
99761  InitData *pData = (InitData*)pInit;
99762  sqlite3 *db = pData->db;
99763  int iDb = pData->iDb;
99764
99765  assert( argc==3 );
99766  UNUSED_PARAMETER2(NotUsed, argc);
99767  assert( sqlite3_mutex_held(db->mutex) );
99768  DbClearProperty(db, iDb, DB_Empty);
99769  if( db->mallocFailed ){
99770    corruptSchema(pData, argv[0], 0);
99771    return 1;
99772  }
99773
99774  assert( iDb>=0 && iDb<db->nDb );
99775  if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
99776  if( argv[1]==0 ){
99777    corruptSchema(pData, argv[0], 0);
99778  }else if( argv[2] && argv[2][0] ){
99779    /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
99780    ** But because db->init.busy is set to 1, no VDBE code is generated
99781    ** or executed.  All the parser does is build the internal data
99782    ** structures that describe the table, index, or view.
99783    */
99784    int rc;
99785    sqlite3_stmt *pStmt;
99786    TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
99787
99788    assert( db->init.busy );
99789    db->init.iDb = iDb;
99790    db->init.newTnum = sqlite3Atoi(argv[1]);
99791    db->init.orphanTrigger = 0;
99792    TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
99793    rc = db->errCode;
99794    assert( (rc&0xFF)==(rcp&0xFF) );
99795    db->init.iDb = 0;
99796    if( SQLITE_OK!=rc ){
99797      if( db->init.orphanTrigger ){
99798        assert( iDb==1 );
99799      }else{
99800        pData->rc = rc;
99801        if( rc==SQLITE_NOMEM ){
99802          db->mallocFailed = 1;
99803        }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
99804          corruptSchema(pData, argv[0], sqlite3_errmsg(db));
99805        }
99806      }
99807    }
99808    sqlite3_finalize(pStmt);
99809  }else if( argv[0]==0 ){
99810    corruptSchema(pData, 0, 0);
99811  }else{
99812    /* If the SQL column is blank it means this is an index that
99813    ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
99814    ** constraint for a CREATE TABLE.  The index should have already
99815    ** been created when we processed the CREATE TABLE.  All we have
99816    ** to do here is record the root page number for that index.
99817    */
99818    Index *pIndex;
99819    pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
99820    if( pIndex==0 ){
99821      /* This can occur if there exists an index on a TEMP table which
99822      ** has the same name as another index on a permanent index.  Since
99823      ** the permanent table is hidden by the TEMP table, we can also
99824      ** safely ignore the index on the permanent table.
99825      */
99826      /* Do Nothing */;
99827    }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
99828      corruptSchema(pData, argv[0], "invalid rootpage");
99829    }
99830  }
99831  return 0;
99832}
99833
99834/*
99835** Attempt to read the database schema and initialize internal
99836** data structures for a single database file.  The index of the
99837** database file is given by iDb.  iDb==0 is used for the main
99838** database.  iDb==1 should never be used.  iDb>=2 is used for
99839** auxiliary databases.  Return one of the SQLITE_ error codes to
99840** indicate success or failure.
99841*/
99842static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
99843  int rc;
99844  int i;
99845#ifndef SQLITE_OMIT_DEPRECATED
99846  int size;
99847#endif
99848  Table *pTab;
99849  Db *pDb;
99850  char const *azArg[4];
99851  int meta[5];
99852  InitData initData;
99853  char const *zMasterSchema;
99854  char const *zMasterName;
99855  int openedTransaction = 0;
99856
99857  /*
99858  ** The master database table has a structure like this
99859  */
99860  static const char master_schema[] =
99861     "CREATE TABLE sqlite_master(\n"
99862     "  type text,\n"
99863     "  name text,\n"
99864     "  tbl_name text,\n"
99865     "  rootpage integer,\n"
99866     "  sql text\n"
99867     ")"
99868  ;
99869#ifndef SQLITE_OMIT_TEMPDB
99870  static const char temp_master_schema[] =
99871     "CREATE TEMP TABLE sqlite_temp_master(\n"
99872     "  type text,\n"
99873     "  name text,\n"
99874     "  tbl_name text,\n"
99875     "  rootpage integer,\n"
99876     "  sql text\n"
99877     ")"
99878  ;
99879#else
99880  #define temp_master_schema 0
99881#endif
99882
99883  assert( iDb>=0 && iDb<db->nDb );
99884  assert( db->aDb[iDb].pSchema );
99885  assert( sqlite3_mutex_held(db->mutex) );
99886  assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
99887
99888  /* zMasterSchema and zInitScript are set to point at the master schema
99889  ** and initialisation script appropriate for the database being
99890  ** initialized. zMasterName is the name of the master table.
99891  */
99892  if( !OMIT_TEMPDB && iDb==1 ){
99893    zMasterSchema = temp_master_schema;
99894  }else{
99895    zMasterSchema = master_schema;
99896  }
99897  zMasterName = SCHEMA_TABLE(iDb);
99898
99899  /* Construct the schema tables.  */
99900  azArg[0] = zMasterName;
99901  azArg[1] = "1";
99902  azArg[2] = zMasterSchema;
99903  azArg[3] = 0;
99904  initData.db = db;
99905  initData.iDb = iDb;
99906  initData.rc = SQLITE_OK;
99907  initData.pzErrMsg = pzErrMsg;
99908  sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
99909  if( initData.rc ){
99910    rc = initData.rc;
99911    goto error_out;
99912  }
99913  pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
99914  if( ALWAYS(pTab) ){
99915    pTab->tabFlags |= TF_Readonly;
99916  }
99917
99918  /* Create a cursor to hold the database open
99919  */
99920  pDb = &db->aDb[iDb];
99921  if( pDb->pBt==0 ){
99922    if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
99923      DbSetProperty(db, 1, DB_SchemaLoaded);
99924    }
99925    return SQLITE_OK;
99926  }
99927
99928  /* If there is not already a read-only (or read-write) transaction opened
99929  ** on the b-tree database, open one now. If a transaction is opened, it
99930  ** will be closed before this function returns.  */
99931  sqlite3BtreeEnter(pDb->pBt);
99932  if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
99933    rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
99934    if( rc!=SQLITE_OK ){
99935      sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
99936      goto initone_error_out;
99937    }
99938    openedTransaction = 1;
99939  }
99940
99941  /* Get the database meta information.
99942  **
99943  ** Meta values are as follows:
99944  **    meta[0]   Schema cookie.  Changes with each schema change.
99945  **    meta[1]   File format of schema layer.
99946  **    meta[2]   Size of the page cache.
99947  **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
99948  **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
99949  **    meta[5]   User version
99950  **    meta[6]   Incremental vacuum mode
99951  **    meta[7]   unused
99952  **    meta[8]   unused
99953  **    meta[9]   unused
99954  **
99955  ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
99956  ** the possible values of meta[4].
99957  */
99958  for(i=0; i<ArraySize(meta); i++){
99959    sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
99960  }
99961  pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
99962
99963  /* If opening a non-empty database, check the text encoding. For the
99964  ** main database, set sqlite3.enc to the encoding of the main database.
99965  ** For an attached db, it is an error if the encoding is not the same
99966  ** as sqlite3.enc.
99967  */
99968  if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
99969    if( iDb==0 ){
99970#ifndef SQLITE_OMIT_UTF16
99971      u8 encoding;
99972      /* If opening the main database, set ENC(db). */
99973      encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
99974      if( encoding==0 ) encoding = SQLITE_UTF8;
99975      ENC(db) = encoding;
99976#else
99977      ENC(db) = SQLITE_UTF8;
99978#endif
99979    }else{
99980      /* If opening an attached database, the encoding much match ENC(db) */
99981      if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
99982        sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
99983            " text encoding as main database");
99984        rc = SQLITE_ERROR;
99985        goto initone_error_out;
99986      }
99987    }
99988  }else{
99989    DbSetProperty(db, iDb, DB_Empty);
99990  }
99991  pDb->pSchema->enc = ENC(db);
99992
99993  if( pDb->pSchema->cache_size==0 ){
99994#ifndef SQLITE_OMIT_DEPRECATED
99995    size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
99996    if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
99997    pDb->pSchema->cache_size = size;
99998#else
99999    pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
100000#endif
100001    sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
100002  }
100003
100004  /*
100005  ** file_format==1    Version 3.0.0.
100006  ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
100007  ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
100008  ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
100009  */
100010  pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
100011  if( pDb->pSchema->file_format==0 ){
100012    pDb->pSchema->file_format = 1;
100013  }
100014  if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
100015    sqlite3SetString(pzErrMsg, db, "unsupported file format");
100016    rc = SQLITE_ERROR;
100017    goto initone_error_out;
100018  }
100019
100020  /* Ticket #2804:  When we open a database in the newer file format,
100021  ** clear the legacy_file_format pragma flag so that a VACUUM will
100022  ** not downgrade the database and thus invalidate any descending
100023  ** indices that the user might have created.
100024  */
100025  if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
100026    db->flags &= ~SQLITE_LegacyFileFmt;
100027  }
100028
100029  /* Read the schema information out of the schema tables
100030  */
100031  assert( db->init.busy );
100032  {
100033    char *zSql;
100034    zSql = sqlite3MPrintf(db,
100035        "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
100036        db->aDb[iDb].zName, zMasterName);
100037#ifndef SQLITE_OMIT_AUTHORIZATION
100038    {
100039      int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
100040      xAuth = db->xAuth;
100041      db->xAuth = 0;
100042#endif
100043      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
100044#ifndef SQLITE_OMIT_AUTHORIZATION
100045      db->xAuth = xAuth;
100046    }
100047#endif
100048    if( rc==SQLITE_OK ) rc = initData.rc;
100049    sqlite3DbFree(db, zSql);
100050#ifndef SQLITE_OMIT_ANALYZE
100051    if( rc==SQLITE_OK ){
100052      sqlite3AnalysisLoad(db, iDb);
100053    }
100054#endif
100055  }
100056  if( db->mallocFailed ){
100057    rc = SQLITE_NOMEM;
100058    sqlite3ResetAllSchemasOfConnection(db);
100059  }
100060  if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
100061    /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
100062    ** the schema loaded, even if errors occurred. In this situation the
100063    ** current sqlite3_prepare() operation will fail, but the following one
100064    ** will attempt to compile the supplied statement against whatever subset
100065    ** of the schema was loaded before the error occurred. The primary
100066    ** purpose of this is to allow access to the sqlite_master table
100067    ** even when its contents have been corrupted.
100068    */
100069    DbSetProperty(db, iDb, DB_SchemaLoaded);
100070    rc = SQLITE_OK;
100071  }
100072
100073  /* Jump here for an error that occurs after successfully allocating
100074  ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
100075  ** before that point, jump to error_out.
100076  */
100077initone_error_out:
100078  if( openedTransaction ){
100079    sqlite3BtreeCommit(pDb->pBt);
100080  }
100081  sqlite3BtreeLeave(pDb->pBt);
100082
100083error_out:
100084  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
100085    db->mallocFailed = 1;
100086  }
100087  return rc;
100088}
100089
100090/*
100091** Initialize all database files - the main database file, the file
100092** used to store temporary tables, and any additional database files
100093** created using ATTACH statements.  Return a success code.  If an
100094** error occurs, write an error message into *pzErrMsg.
100095**
100096** After a database is initialized, the DB_SchemaLoaded bit is set
100097** bit is set in the flags field of the Db structure. If the database
100098** file was of zero-length, then the DB_Empty flag is also set.
100099*/
100100SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
100101  int i, rc;
100102  int commit_internal = !(db->flags&SQLITE_InternChanges);
100103
100104  assert( sqlite3_mutex_held(db->mutex) );
100105  rc = SQLITE_OK;
100106  db->init.busy = 1;
100107  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
100108    if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
100109    rc = sqlite3InitOne(db, i, pzErrMsg);
100110    if( rc ){
100111      sqlite3ResetOneSchema(db, i);
100112    }
100113  }
100114
100115  /* Once all the other databases have been initialized, load the schema
100116  ** for the TEMP database. This is loaded last, as the TEMP database
100117  ** schema may contain references to objects in other databases.
100118  */
100119#ifndef SQLITE_OMIT_TEMPDB
100120  if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
100121                    && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
100122    rc = sqlite3InitOne(db, 1, pzErrMsg);
100123    if( rc ){
100124      sqlite3ResetOneSchema(db, 1);
100125    }
100126  }
100127#endif
100128
100129  db->init.busy = 0;
100130  if( rc==SQLITE_OK && commit_internal ){
100131    sqlite3CommitInternalChanges(db);
100132  }
100133
100134  return rc;
100135}
100136
100137/*
100138** This routine is a no-op if the database schema is already initialized.
100139** Otherwise, the schema is loaded. An error code is returned.
100140*/
100141SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
100142  int rc = SQLITE_OK;
100143  sqlite3 *db = pParse->db;
100144  assert( sqlite3_mutex_held(db->mutex) );
100145  if( !db->init.busy ){
100146    rc = sqlite3Init(db, &pParse->zErrMsg);
100147  }
100148  if( rc!=SQLITE_OK ){
100149    pParse->rc = rc;
100150    pParse->nErr++;
100151  }
100152  return rc;
100153}
100154
100155
100156/*
100157** Check schema cookies in all databases.  If any cookie is out
100158** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
100159** make no changes to pParse->rc.
100160*/
100161static void schemaIsValid(Parse *pParse){
100162  sqlite3 *db = pParse->db;
100163  int iDb;
100164  int rc;
100165  int cookie;
100166
100167  assert( pParse->checkSchema );
100168  assert( sqlite3_mutex_held(db->mutex) );
100169  for(iDb=0; iDb<db->nDb; iDb++){
100170    int openedTransaction = 0;         /* True if a transaction is opened */
100171    Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
100172    if( pBt==0 ) continue;
100173
100174    /* If there is not already a read-only (or read-write) transaction opened
100175    ** on the b-tree database, open one now. If a transaction is opened, it
100176    ** will be closed immediately after reading the meta-value. */
100177    if( !sqlite3BtreeIsInReadTrans(pBt) ){
100178      rc = sqlite3BtreeBeginTrans(pBt, 0);
100179      if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
100180        db->mallocFailed = 1;
100181      }
100182      if( rc!=SQLITE_OK ) return;
100183      openedTransaction = 1;
100184    }
100185
100186    /* Read the schema cookie from the database. If it does not match the
100187    ** value stored as part of the in-memory schema representation,
100188    ** set Parse.rc to SQLITE_SCHEMA. */
100189    sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
100190    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
100191    if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
100192      sqlite3ResetOneSchema(db, iDb);
100193      pParse->rc = SQLITE_SCHEMA;
100194    }
100195
100196    /* Close the transaction, if one was opened. */
100197    if( openedTransaction ){
100198      sqlite3BtreeCommit(pBt);
100199    }
100200  }
100201}
100202
100203/*
100204** Convert a schema pointer into the iDb index that indicates
100205** which database file in db->aDb[] the schema refers to.
100206**
100207** If the same database is attached more than once, the first
100208** attached database is returned.
100209*/
100210SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
100211  int i = -1000000;
100212
100213  /* If pSchema is NULL, then return -1000000. This happens when code in
100214  ** expr.c is trying to resolve a reference to a transient table (i.e. one
100215  ** created by a sub-select). In this case the return value of this
100216  ** function should never be used.
100217  **
100218  ** We return -1000000 instead of the more usual -1 simply because using
100219  ** -1000000 as the incorrect index into db->aDb[] is much
100220  ** more likely to cause a segfault than -1 (of course there are assert()
100221  ** statements too, but it never hurts to play the odds).
100222  */
100223  assert( sqlite3_mutex_held(db->mutex) );
100224  if( pSchema ){
100225    for(i=0; ALWAYS(i<db->nDb); i++){
100226      if( db->aDb[i].pSchema==pSchema ){
100227        break;
100228      }
100229    }
100230    assert( i>=0 && i<db->nDb );
100231  }
100232  return i;
100233}
100234
100235/*
100236** Free all memory allocations in the pParse object
100237*/
100238SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
100239  if( pParse ){
100240    sqlite3 *db = pParse->db;
100241    sqlite3DbFree(db, pParse->aLabel);
100242    sqlite3ExprListDelete(db, pParse->pConstExpr);
100243  }
100244}
100245
100246/*
100247** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
100248*/
100249static int sqlite3Prepare(
100250  sqlite3 *db,              /* Database handle. */
100251  const char *zSql,         /* UTF-8 encoded SQL statement. */
100252  int nBytes,               /* Length of zSql in bytes. */
100253  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
100254  Vdbe *pReprepare,         /* VM being reprepared */
100255  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
100256  const char **pzTail       /* OUT: End of parsed string */
100257){
100258  Parse *pParse;            /* Parsing context */
100259  char *zErrMsg = 0;        /* Error message */
100260  int rc = SQLITE_OK;       /* Result code */
100261  int i;                    /* Loop counter */
100262
100263  /* Allocate the parsing context */
100264  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
100265  if( pParse==0 ){
100266    rc = SQLITE_NOMEM;
100267    goto end_prepare;
100268  }
100269  pParse->pReprepare = pReprepare;
100270  assert( ppStmt && *ppStmt==0 );
100271  assert( !db->mallocFailed );
100272  assert( sqlite3_mutex_held(db->mutex) );
100273
100274  /* Check to verify that it is possible to get a read lock on all
100275  ** database schemas.  The inability to get a read lock indicates that
100276  ** some other database connection is holding a write-lock, which in
100277  ** turn means that the other connection has made uncommitted changes
100278  ** to the schema.
100279  **
100280  ** Were we to proceed and prepare the statement against the uncommitted
100281  ** schema changes and if those schema changes are subsequently rolled
100282  ** back and different changes are made in their place, then when this
100283  ** prepared statement goes to run the schema cookie would fail to detect
100284  ** the schema change.  Disaster would follow.
100285  **
100286  ** This thread is currently holding mutexes on all Btrees (because
100287  ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
100288  ** is not possible for another thread to start a new schema change
100289  ** while this routine is running.  Hence, we do not need to hold
100290  ** locks on the schema, we just need to make sure nobody else is
100291  ** holding them.
100292  **
100293  ** Note that setting READ_UNCOMMITTED overrides most lock detection,
100294  ** but it does *not* override schema lock detection, so this all still
100295  ** works even if READ_UNCOMMITTED is set.
100296  */
100297  for(i=0; i<db->nDb; i++) {
100298    Btree *pBt = db->aDb[i].pBt;
100299    if( pBt ){
100300      assert( sqlite3BtreeHoldsMutex(pBt) );
100301      rc = sqlite3BtreeSchemaLocked(pBt);
100302      if( rc ){
100303        const char *zDb = db->aDb[i].zName;
100304        sqlite3Error(db, rc, "database schema is locked: %s", zDb);
100305        testcase( db->flags & SQLITE_ReadUncommitted );
100306        goto end_prepare;
100307      }
100308    }
100309  }
100310
100311  sqlite3VtabUnlockList(db);
100312
100313  pParse->db = db;
100314  pParse->nQueryLoop = 0;  /* Logarithmic, so 0 really means 1 */
100315  if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
100316    char *zSqlCopy;
100317    int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
100318    testcase( nBytes==mxLen );
100319    testcase( nBytes==mxLen+1 );
100320    if( nBytes>mxLen ){
100321      sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
100322      rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
100323      goto end_prepare;
100324    }
100325    zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
100326    if( zSqlCopy ){
100327      sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
100328      sqlite3DbFree(db, zSqlCopy);
100329      pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
100330    }else{
100331      pParse->zTail = &zSql[nBytes];
100332    }
100333  }else{
100334    sqlite3RunParser(pParse, zSql, &zErrMsg);
100335  }
100336  assert( 0==pParse->nQueryLoop );
100337
100338  if( db->mallocFailed ){
100339    pParse->rc = SQLITE_NOMEM;
100340  }
100341  if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
100342  if( pParse->checkSchema ){
100343    schemaIsValid(pParse);
100344  }
100345  if( db->mallocFailed ){
100346    pParse->rc = SQLITE_NOMEM;
100347  }
100348  if( pzTail ){
100349    *pzTail = pParse->zTail;
100350  }
100351  rc = pParse->rc;
100352
100353#ifndef SQLITE_OMIT_EXPLAIN
100354  if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
100355    static const char * const azColName[] = {
100356       "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
100357       "selectid", "order", "from", "detail"
100358    };
100359    int iFirst, mx;
100360    if( pParse->explain==2 ){
100361      sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
100362      iFirst = 8;
100363      mx = 12;
100364    }else{
100365      sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
100366      iFirst = 0;
100367      mx = 8;
100368    }
100369    for(i=iFirst; i<mx; i++){
100370      sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
100371                            azColName[i], SQLITE_STATIC);
100372    }
100373  }
100374#endif
100375
100376  if( db->init.busy==0 ){
100377    Vdbe *pVdbe = pParse->pVdbe;
100378    sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
100379  }
100380  if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
100381    sqlite3VdbeFinalize(pParse->pVdbe);
100382    assert(!(*ppStmt));
100383  }else{
100384    *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
100385  }
100386
100387  if( zErrMsg ){
100388    sqlite3Error(db, rc, "%s", zErrMsg);
100389    sqlite3DbFree(db, zErrMsg);
100390  }else{
100391    sqlite3Error(db, rc, 0);
100392  }
100393
100394  /* Delete any TriggerPrg structures allocated while parsing this statement. */
100395  while( pParse->pTriggerPrg ){
100396    TriggerPrg *pT = pParse->pTriggerPrg;
100397    pParse->pTriggerPrg = pT->pNext;
100398    sqlite3DbFree(db, pT);
100399  }
100400
100401end_prepare:
100402
100403  sqlite3ParserReset(pParse);
100404  sqlite3StackFree(db, pParse);
100405  rc = sqlite3ApiExit(db, rc);
100406  assert( (rc&db->errMask)==rc );
100407  return rc;
100408}
100409static int sqlite3LockAndPrepare(
100410  sqlite3 *db,              /* Database handle. */
100411  const char *zSql,         /* UTF-8 encoded SQL statement. */
100412  int nBytes,               /* Length of zSql in bytes. */
100413  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
100414  Vdbe *pOld,               /* VM being reprepared */
100415  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
100416  const char **pzTail       /* OUT: End of parsed string */
100417){
100418  int rc;
100419  assert( ppStmt!=0 );
100420  *ppStmt = 0;
100421  if( !sqlite3SafetyCheckOk(db) ){
100422    return SQLITE_MISUSE_BKPT;
100423  }
100424  sqlite3_mutex_enter(db->mutex);
100425  sqlite3BtreeEnterAll(db);
100426  rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
100427  if( rc==SQLITE_SCHEMA ){
100428    sqlite3_finalize(*ppStmt);
100429    rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
100430  }
100431  sqlite3BtreeLeaveAll(db);
100432  sqlite3_mutex_leave(db->mutex);
100433  assert( rc==SQLITE_OK || *ppStmt==0 );
100434  return rc;
100435}
100436
100437/*
100438** Rerun the compilation of a statement after a schema change.
100439**
100440** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
100441** if the statement cannot be recompiled because another connection has
100442** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
100443** occurs, return SQLITE_SCHEMA.
100444*/
100445SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
100446  int rc;
100447  sqlite3_stmt *pNew;
100448  const char *zSql;
100449  sqlite3 *db;
100450
100451  assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
100452  zSql = sqlite3_sql((sqlite3_stmt *)p);
100453  assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
100454  db = sqlite3VdbeDb(p);
100455  assert( sqlite3_mutex_held(db->mutex) );
100456  rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
100457  if( rc ){
100458    if( rc==SQLITE_NOMEM ){
100459      db->mallocFailed = 1;
100460    }
100461    assert( pNew==0 );
100462    return rc;
100463  }else{
100464    assert( pNew!=0 );
100465  }
100466  sqlite3VdbeSwap((Vdbe*)pNew, p);
100467  sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
100468  sqlite3VdbeResetStepResult((Vdbe*)pNew);
100469  sqlite3VdbeFinalize((Vdbe*)pNew);
100470  return SQLITE_OK;
100471}
100472
100473
100474/*
100475** Two versions of the official API.  Legacy and new use.  In the legacy
100476** version, the original SQL text is not saved in the prepared statement
100477** and so if a schema change occurs, SQLITE_SCHEMA is returned by
100478** sqlite3_step().  In the new version, the original SQL text is retained
100479** and the statement is automatically recompiled if an schema change
100480** occurs.
100481*/
100482SQLITE_API int sqlite3_prepare(
100483  sqlite3 *db,              /* Database handle. */
100484  const char *zSql,         /* UTF-8 encoded SQL statement. */
100485  int nBytes,               /* Length of zSql in bytes. */
100486  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
100487  const char **pzTail       /* OUT: End of parsed string */
100488){
100489  int rc;
100490  rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
100491  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
100492  return rc;
100493}
100494SQLITE_API int sqlite3_prepare_v2(
100495  sqlite3 *db,              /* Database handle. */
100496  const char *zSql,         /* UTF-8 encoded SQL statement. */
100497  int nBytes,               /* Length of zSql in bytes. */
100498  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
100499  const char **pzTail       /* OUT: End of parsed string */
100500){
100501  int rc;
100502  rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
100503  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
100504  return rc;
100505}
100506
100507
100508#ifndef SQLITE_OMIT_UTF16
100509/*
100510** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
100511*/
100512static int sqlite3Prepare16(
100513  sqlite3 *db,              /* Database handle. */
100514  const void *zSql,         /* UTF-16 encoded SQL statement. */
100515  int nBytes,               /* Length of zSql in bytes. */
100516  int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
100517  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
100518  const void **pzTail       /* OUT: End of parsed string */
100519){
100520  /* This function currently works by first transforming the UTF-16
100521  ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
100522  ** tricky bit is figuring out the pointer to return in *pzTail.
100523  */
100524  char *zSql8;
100525  const char *zTail8 = 0;
100526  int rc = SQLITE_OK;
100527
100528  assert( ppStmt );
100529  *ppStmt = 0;
100530  if( !sqlite3SafetyCheckOk(db) ){
100531    return SQLITE_MISUSE_BKPT;
100532  }
100533  if( nBytes>=0 ){
100534    int sz;
100535    const char *z = (const char*)zSql;
100536    for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
100537    nBytes = sz;
100538  }
100539  sqlite3_mutex_enter(db->mutex);
100540  zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
100541  if( zSql8 ){
100542    rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
100543  }
100544
100545  if( zTail8 && pzTail ){
100546    /* If sqlite3_prepare returns a tail pointer, we calculate the
100547    ** equivalent pointer into the UTF-16 string by counting the unicode
100548    ** characters between zSql8 and zTail8, and then returning a pointer
100549    ** the same number of characters into the UTF-16 string.
100550    */
100551    int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
100552    *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
100553  }
100554  sqlite3DbFree(db, zSql8);
100555  rc = sqlite3ApiExit(db, rc);
100556  sqlite3_mutex_leave(db->mutex);
100557  return rc;
100558}
100559
100560/*
100561** Two versions of the official API.  Legacy and new use.  In the legacy
100562** version, the original SQL text is not saved in the prepared statement
100563** and so if a schema change occurs, SQLITE_SCHEMA is returned by
100564** sqlite3_step().  In the new version, the original SQL text is retained
100565** and the statement is automatically recompiled if an schema change
100566** occurs.
100567*/
100568SQLITE_API int sqlite3_prepare16(
100569  sqlite3 *db,              /* Database handle. */
100570  const void *zSql,         /* UTF-16 encoded SQL statement. */
100571  int nBytes,               /* Length of zSql in bytes. */
100572  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
100573  const void **pzTail       /* OUT: End of parsed string */
100574){
100575  int rc;
100576  rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
100577  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
100578  return rc;
100579}
100580SQLITE_API int sqlite3_prepare16_v2(
100581  sqlite3 *db,              /* Database handle. */
100582  const void *zSql,         /* UTF-16 encoded SQL statement. */
100583  int nBytes,               /* Length of zSql in bytes. */
100584  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
100585  const void **pzTail       /* OUT: End of parsed string */
100586){
100587  int rc;
100588  rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
100589  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
100590  return rc;
100591}
100592
100593#endif /* SQLITE_OMIT_UTF16 */
100594
100595/************** End of prepare.c *********************************************/
100596/************** Begin file select.c ******************************************/
100597/*
100598** 2001 September 15
100599**
100600** The author disclaims copyright to this source code.  In place of
100601** a legal notice, here is a blessing:
100602**
100603**    May you do good and not evil.
100604**    May you find forgiveness for yourself and forgive others.
100605**    May you share freely, never taking more than you give.
100606**
100607*************************************************************************
100608** This file contains C code routines that are called by the parser
100609** to handle SELECT statements in SQLite.
100610*/
100611
100612/*
100613** An instance of the following object is used to record information about
100614** how to process the DISTINCT keyword, to simplify passing that information
100615** into the selectInnerLoop() routine.
100616*/
100617typedef struct DistinctCtx DistinctCtx;
100618struct DistinctCtx {
100619  u8 isTnct;      /* True if the DISTINCT keyword is present */
100620  u8 eTnctType;   /* One of the WHERE_DISTINCT_* operators */
100621  int tabTnct;    /* Ephemeral table used for DISTINCT processing */
100622  int addrTnct;   /* Address of OP_OpenEphemeral opcode for tabTnct */
100623};
100624
100625/*
100626** An instance of the following object is used to record information about
100627** the ORDER BY (or GROUP BY) clause of query is being coded.
100628*/
100629typedef struct SortCtx SortCtx;
100630struct SortCtx {
100631  ExprList *pOrderBy;   /* The ORDER BY (or GROUP BY clause) */
100632  int nOBSat;           /* Number of ORDER BY terms satisfied by indices */
100633  int iECursor;         /* Cursor number for the sorter */
100634  int regReturn;        /* Register holding block-output return address */
100635  int labelBkOut;       /* Start label for the block-output subroutine */
100636  int addrSortIndex;    /* Address of the OP_SorterOpen or OP_OpenEphemeral */
100637  u8 sortFlags;         /* Zero or more SORTFLAG_* bits */
100638};
100639#define SORTFLAG_UseSorter  0x01   /* Use SorterOpen instead of OpenEphemeral */
100640
100641/*
100642** Delete all the content of a Select structure but do not deallocate
100643** the select structure itself.
100644*/
100645static void clearSelect(sqlite3 *db, Select *p){
100646  sqlite3ExprListDelete(db, p->pEList);
100647  sqlite3SrcListDelete(db, p->pSrc);
100648  sqlite3ExprDelete(db, p->pWhere);
100649  sqlite3ExprListDelete(db, p->pGroupBy);
100650  sqlite3ExprDelete(db, p->pHaving);
100651  sqlite3ExprListDelete(db, p->pOrderBy);
100652  sqlite3SelectDelete(db, p->pPrior);
100653  sqlite3ExprDelete(db, p->pLimit);
100654  sqlite3ExprDelete(db, p->pOffset);
100655  sqlite3WithDelete(db, p->pWith);
100656}
100657
100658/*
100659** Initialize a SelectDest structure.
100660*/
100661SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
100662  pDest->eDest = (u8)eDest;
100663  pDest->iSDParm = iParm;
100664  pDest->affSdst = 0;
100665  pDest->iSdst = 0;
100666  pDest->nSdst = 0;
100667}
100668
100669
100670/*
100671** Allocate a new Select structure and return a pointer to that
100672** structure.
100673*/
100674SQLITE_PRIVATE Select *sqlite3SelectNew(
100675  Parse *pParse,        /* Parsing context */
100676  ExprList *pEList,     /* which columns to include in the result */
100677  SrcList *pSrc,        /* the FROM clause -- which tables to scan */
100678  Expr *pWhere,         /* the WHERE clause */
100679  ExprList *pGroupBy,   /* the GROUP BY clause */
100680  Expr *pHaving,        /* the HAVING clause */
100681  ExprList *pOrderBy,   /* the ORDER BY clause */
100682  u16 selFlags,         /* Flag parameters, such as SF_Distinct */
100683  Expr *pLimit,         /* LIMIT value.  NULL means not used */
100684  Expr *pOffset         /* OFFSET value.  NULL means no offset */
100685){
100686  Select *pNew;
100687  Select standin;
100688  sqlite3 *db = pParse->db;
100689  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
100690  assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
100691  if( pNew==0 ){
100692    assert( db->mallocFailed );
100693    pNew = &standin;
100694    memset(pNew, 0, sizeof(*pNew));
100695  }
100696  if( pEList==0 ){
100697    pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
100698  }
100699  pNew->pEList = pEList;
100700  if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
100701  pNew->pSrc = pSrc;
100702  pNew->pWhere = pWhere;
100703  pNew->pGroupBy = pGroupBy;
100704  pNew->pHaving = pHaving;
100705  pNew->pOrderBy = pOrderBy;
100706  pNew->selFlags = selFlags;
100707  pNew->op = TK_SELECT;
100708  pNew->pLimit = pLimit;
100709  pNew->pOffset = pOffset;
100710  assert( pOffset==0 || pLimit!=0 );
100711  pNew->addrOpenEphm[0] = -1;
100712  pNew->addrOpenEphm[1] = -1;
100713  if( db->mallocFailed ) {
100714    clearSelect(db, pNew);
100715    if( pNew!=&standin ) sqlite3DbFree(db, pNew);
100716    pNew = 0;
100717  }else{
100718    assert( pNew->pSrc!=0 || pParse->nErr>0 );
100719  }
100720  assert( pNew!=&standin );
100721  return pNew;
100722}
100723
100724/*
100725** Delete the given Select structure and all of its substructures.
100726*/
100727SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
100728  if( p ){
100729    clearSelect(db, p);
100730    sqlite3DbFree(db, p);
100731  }
100732}
100733
100734/*
100735** Return a pointer to the right-most SELECT statement in a compound.
100736*/
100737static Select *findRightmost(Select *p){
100738  while( p->pNext ) p = p->pNext;
100739  return p;
100740}
100741
100742/*
100743** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
100744** type of join.  Return an integer constant that expresses that type
100745** in terms of the following bit values:
100746**
100747**     JT_INNER
100748**     JT_CROSS
100749**     JT_OUTER
100750**     JT_NATURAL
100751**     JT_LEFT
100752**     JT_RIGHT
100753**
100754** A full outer join is the combination of JT_LEFT and JT_RIGHT.
100755**
100756** If an illegal or unsupported join type is seen, then still return
100757** a join type, but put an error in the pParse structure.
100758*/
100759SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
100760  int jointype = 0;
100761  Token *apAll[3];
100762  Token *p;
100763                             /*   0123456789 123456789 123456789 123 */
100764  static const char zKeyText[] = "naturaleftouterightfullinnercross";
100765  static const struct {
100766    u8 i;        /* Beginning of keyword text in zKeyText[] */
100767    u8 nChar;    /* Length of the keyword in characters */
100768    u8 code;     /* Join type mask */
100769  } aKeyword[] = {
100770    /* natural */ { 0,  7, JT_NATURAL                },
100771    /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
100772    /* outer   */ { 10, 5, JT_OUTER                  },
100773    /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
100774    /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
100775    /* inner   */ { 23, 5, JT_INNER                  },
100776    /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
100777  };
100778  int i, j;
100779  apAll[0] = pA;
100780  apAll[1] = pB;
100781  apAll[2] = pC;
100782  for(i=0; i<3 && apAll[i]; i++){
100783    p = apAll[i];
100784    for(j=0; j<ArraySize(aKeyword); j++){
100785      if( p->n==aKeyword[j].nChar
100786          && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
100787        jointype |= aKeyword[j].code;
100788        break;
100789      }
100790    }
100791    testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
100792    if( j>=ArraySize(aKeyword) ){
100793      jointype |= JT_ERROR;
100794      break;
100795    }
100796  }
100797  if(
100798     (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
100799     (jointype & JT_ERROR)!=0
100800  ){
100801    const char *zSp = " ";
100802    assert( pB!=0 );
100803    if( pC==0 ){ zSp++; }
100804    sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
100805       "%T %T%s%T", pA, pB, zSp, pC);
100806    jointype = JT_INNER;
100807  }else if( (jointype & JT_OUTER)!=0
100808         && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
100809    sqlite3ErrorMsg(pParse,
100810      "RIGHT and FULL OUTER JOINs are not currently supported");
100811    jointype = JT_INNER;
100812  }
100813  return jointype;
100814}
100815
100816/*
100817** Return the index of a column in a table.  Return -1 if the column
100818** is not contained in the table.
100819*/
100820static int columnIndex(Table *pTab, const char *zCol){
100821  int i;
100822  for(i=0; i<pTab->nCol; i++){
100823    if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
100824  }
100825  return -1;
100826}
100827
100828/*
100829** Search the first N tables in pSrc, from left to right, looking for a
100830** table that has a column named zCol.
100831**
100832** When found, set *piTab and *piCol to the table index and column index
100833** of the matching column and return TRUE.
100834**
100835** If not found, return FALSE.
100836*/
100837static int tableAndColumnIndex(
100838  SrcList *pSrc,       /* Array of tables to search */
100839  int N,               /* Number of tables in pSrc->a[] to search */
100840  const char *zCol,    /* Name of the column we are looking for */
100841  int *piTab,          /* Write index of pSrc->a[] here */
100842  int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
100843){
100844  int i;               /* For looping over tables in pSrc */
100845  int iCol;            /* Index of column matching zCol */
100846
100847  assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
100848  for(i=0; i<N; i++){
100849    iCol = columnIndex(pSrc->a[i].pTab, zCol);
100850    if( iCol>=0 ){
100851      if( piTab ){
100852        *piTab = i;
100853        *piCol = iCol;
100854      }
100855      return 1;
100856    }
100857  }
100858  return 0;
100859}
100860
100861/*
100862** This function is used to add terms implied by JOIN syntax to the
100863** WHERE clause expression of a SELECT statement. The new term, which
100864** is ANDed with the existing WHERE clause, is of the form:
100865**
100866**    (tab1.col1 = tab2.col2)
100867**
100868** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
100869** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
100870** column iColRight of tab2.
100871*/
100872static void addWhereTerm(
100873  Parse *pParse,                  /* Parsing context */
100874  SrcList *pSrc,                  /* List of tables in FROM clause */
100875  int iLeft,                      /* Index of first table to join in pSrc */
100876  int iColLeft,                   /* Index of column in first table */
100877  int iRight,                     /* Index of second table in pSrc */
100878  int iColRight,                  /* Index of column in second table */
100879  int isOuterJoin,                /* True if this is an OUTER join */
100880  Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
100881){
100882  sqlite3 *db = pParse->db;
100883  Expr *pE1;
100884  Expr *pE2;
100885  Expr *pEq;
100886
100887  assert( iLeft<iRight );
100888  assert( pSrc->nSrc>iRight );
100889  assert( pSrc->a[iLeft].pTab );
100890  assert( pSrc->a[iRight].pTab );
100891
100892  pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
100893  pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
100894
100895  pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
100896  if( pEq && isOuterJoin ){
100897    ExprSetProperty(pEq, EP_FromJoin);
100898    assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
100899    ExprSetVVAProperty(pEq, EP_NoReduce);
100900    pEq->iRightJoinTable = (i16)pE2->iTable;
100901  }
100902  *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
100903}
100904
100905/*
100906** Set the EP_FromJoin property on all terms of the given expression.
100907** And set the Expr.iRightJoinTable to iTable for every term in the
100908** expression.
100909**
100910** The EP_FromJoin property is used on terms of an expression to tell
100911** the LEFT OUTER JOIN processing logic that this term is part of the
100912** join restriction specified in the ON or USING clause and not a part
100913** of the more general WHERE clause.  These terms are moved over to the
100914** WHERE clause during join processing but we need to remember that they
100915** originated in the ON or USING clause.
100916**
100917** The Expr.iRightJoinTable tells the WHERE clause processing that the
100918** expression depends on table iRightJoinTable even if that table is not
100919** explicitly mentioned in the expression.  That information is needed
100920** for cases like this:
100921**
100922**    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
100923**
100924** The where clause needs to defer the handling of the t1.x=5
100925** term until after the t2 loop of the join.  In that way, a
100926** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
100927** defer the handling of t1.x=5, it will be processed immediately
100928** after the t1 loop and rows with t1.x!=5 will never appear in
100929** the output, which is incorrect.
100930*/
100931static void setJoinExpr(Expr *p, int iTable){
100932  while( p ){
100933    ExprSetProperty(p, EP_FromJoin);
100934    assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
100935    ExprSetVVAProperty(p, EP_NoReduce);
100936    p->iRightJoinTable = (i16)iTable;
100937    setJoinExpr(p->pLeft, iTable);
100938    p = p->pRight;
100939  }
100940}
100941
100942/*
100943** This routine processes the join information for a SELECT statement.
100944** ON and USING clauses are converted into extra terms of the WHERE clause.
100945** NATURAL joins also create extra WHERE clause terms.
100946**
100947** The terms of a FROM clause are contained in the Select.pSrc structure.
100948** The left most table is the first entry in Select.pSrc.  The right-most
100949** table is the last entry.  The join operator is held in the entry to
100950** the left.  Thus entry 0 contains the join operator for the join between
100951** entries 0 and 1.  Any ON or USING clauses associated with the join are
100952** also attached to the left entry.
100953**
100954** This routine returns the number of errors encountered.
100955*/
100956static int sqliteProcessJoin(Parse *pParse, Select *p){
100957  SrcList *pSrc;                  /* All tables in the FROM clause */
100958  int i, j;                       /* Loop counters */
100959  struct SrcList_item *pLeft;     /* Left table being joined */
100960  struct SrcList_item *pRight;    /* Right table being joined */
100961
100962  pSrc = p->pSrc;
100963  pLeft = &pSrc->a[0];
100964  pRight = &pLeft[1];
100965  for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
100966    Table *pLeftTab = pLeft->pTab;
100967    Table *pRightTab = pRight->pTab;
100968    int isOuter;
100969
100970    if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
100971    isOuter = (pRight->jointype & JT_OUTER)!=0;
100972
100973    /* When the NATURAL keyword is present, add WHERE clause terms for
100974    ** every column that the two tables have in common.
100975    */
100976    if( pRight->jointype & JT_NATURAL ){
100977      if( pRight->pOn || pRight->pUsing ){
100978        sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
100979           "an ON or USING clause", 0);
100980        return 1;
100981      }
100982      for(j=0; j<pRightTab->nCol; j++){
100983        char *zName;   /* Name of column in the right table */
100984        int iLeft;     /* Matching left table */
100985        int iLeftCol;  /* Matching column in the left table */
100986
100987        zName = pRightTab->aCol[j].zName;
100988        if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
100989          addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
100990                       isOuter, &p->pWhere);
100991        }
100992      }
100993    }
100994
100995    /* Disallow both ON and USING clauses in the same join
100996    */
100997    if( pRight->pOn && pRight->pUsing ){
100998      sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
100999        "clauses in the same join");
101000      return 1;
101001    }
101002
101003    /* Add the ON clause to the end of the WHERE clause, connected by
101004    ** an AND operator.
101005    */
101006    if( pRight->pOn ){
101007      if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
101008      p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
101009      pRight->pOn = 0;
101010    }
101011
101012    /* Create extra terms on the WHERE clause for each column named
101013    ** in the USING clause.  Example: If the two tables to be joined are
101014    ** A and B and the USING clause names X, Y, and Z, then add this
101015    ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
101016    ** Report an error if any column mentioned in the USING clause is
101017    ** not contained in both tables to be joined.
101018    */
101019    if( pRight->pUsing ){
101020      IdList *pList = pRight->pUsing;
101021      for(j=0; j<pList->nId; j++){
101022        char *zName;     /* Name of the term in the USING clause */
101023        int iLeft;       /* Table on the left with matching column name */
101024        int iLeftCol;    /* Column number of matching column on the left */
101025        int iRightCol;   /* Column number of matching column on the right */
101026
101027        zName = pList->a[j].zName;
101028        iRightCol = columnIndex(pRightTab, zName);
101029        if( iRightCol<0
101030         || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
101031        ){
101032          sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
101033            "not present in both tables", zName);
101034          return 1;
101035        }
101036        addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
101037                     isOuter, &p->pWhere);
101038      }
101039    }
101040  }
101041  return 0;
101042}
101043
101044/* Forward reference */
101045static KeyInfo *keyInfoFromExprList(
101046  Parse *pParse,       /* Parsing context */
101047  ExprList *pList,     /* Form the KeyInfo object from this ExprList */
101048  int iStart,          /* Begin with this column of pList */
101049  int nExtra           /* Add this many extra columns to the end */
101050);
101051
101052/*
101053** Insert code into "v" that will push the record in register regData
101054** into the sorter.
101055*/
101056static void pushOntoSorter(
101057  Parse *pParse,         /* Parser context */
101058  SortCtx *pSort,        /* Information about the ORDER BY clause */
101059  Select *pSelect,       /* The whole SELECT statement */
101060  int regData            /* Register holding data to be sorted */
101061){
101062  Vdbe *v = pParse->pVdbe;
101063  int nExpr = pSort->pOrderBy->nExpr;
101064  int regRecord = ++pParse->nMem;
101065  int regBase = pParse->nMem+1;
101066  int nOBSat = pSort->nOBSat;
101067  int op;
101068
101069  pParse->nMem += nExpr+2;        /* nExpr+2 registers allocated at regBase */
101070  sqlite3ExprCacheClear(pParse);
101071  sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, 0);
101072  sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
101073  sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
101074  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nExpr+2-nOBSat,regRecord);
101075  if( nOBSat>0 ){
101076    int regPrevKey;   /* The first nOBSat columns of the previous row */
101077    int addrFirst;    /* Address of the OP_IfNot opcode */
101078    int addrJmp;      /* Address of the OP_Jump opcode */
101079    VdbeOp *pOp;      /* Opcode that opens the sorter */
101080    int nKey;         /* Number of sorting key columns, including OP_Sequence */
101081    KeyInfo *pKI;     /* Original KeyInfo on the sorter table */
101082
101083    regPrevKey = pParse->nMem+1;
101084    pParse->nMem += pSort->nOBSat;
101085    nKey = nExpr - pSort->nOBSat + 1;
101086    addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr); VdbeCoverage(v);
101087    sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
101088    pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
101089    if( pParse->db->mallocFailed ) return;
101090    pOp->p2 = nKey + 1;
101091    pKI = pOp->p4.pKeyInfo;
101092    memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */
101093    sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
101094    pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat, 1);
101095    addrJmp = sqlite3VdbeCurrentAddr(v);
101096    sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
101097    pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
101098    pSort->regReturn = ++pParse->nMem;
101099    sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
101100    sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
101101    sqlite3VdbeJumpHere(v, addrFirst);
101102    sqlite3VdbeAddOp3(v, OP_Move, regBase, regPrevKey, pSort->nOBSat);
101103    sqlite3VdbeJumpHere(v, addrJmp);
101104  }
101105  if( pSort->sortFlags & SORTFLAG_UseSorter ){
101106    op = OP_SorterInsert;
101107  }else{
101108    op = OP_IdxInsert;
101109  }
101110  sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord);
101111  if( pSelect->iLimit ){
101112    int addr1, addr2;
101113    int iLimit;
101114    if( pSelect->iOffset ){
101115      iLimit = pSelect->iOffset+1;
101116    }else{
101117      iLimit = pSelect->iLimit;
101118    }
101119    addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit); VdbeCoverage(v);
101120    sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
101121    addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
101122    sqlite3VdbeJumpHere(v, addr1);
101123    sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
101124    sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
101125    sqlite3VdbeJumpHere(v, addr2);
101126  }
101127}
101128
101129/*
101130** Add code to implement the OFFSET
101131*/
101132static void codeOffset(
101133  Vdbe *v,          /* Generate code into this VM */
101134  int iOffset,      /* Register holding the offset counter */
101135  int iContinue     /* Jump here to skip the current record */
101136){
101137  if( iOffset>0 ){
101138    int addr;
101139    sqlite3VdbeAddOp2(v, OP_AddImm, iOffset, -1);
101140    addr = sqlite3VdbeAddOp1(v, OP_IfNeg, iOffset); VdbeCoverage(v);
101141    sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
101142    VdbeComment((v, "skip OFFSET records"));
101143    sqlite3VdbeJumpHere(v, addr);
101144  }
101145}
101146
101147/*
101148** Add code that will check to make sure the N registers starting at iMem
101149** form a distinct entry.  iTab is a sorting index that holds previously
101150** seen combinations of the N values.  A new entry is made in iTab
101151** if the current N values are new.
101152**
101153** A jump to addrRepeat is made and the N+1 values are popped from the
101154** stack if the top N elements are not distinct.
101155*/
101156static void codeDistinct(
101157  Parse *pParse,     /* Parsing and code generating context */
101158  int iTab,          /* A sorting index used to test for distinctness */
101159  int addrRepeat,    /* Jump to here if not distinct */
101160  int N,             /* Number of elements */
101161  int iMem           /* First element */
101162){
101163  Vdbe *v;
101164  int r1;
101165
101166  v = pParse->pVdbe;
101167  r1 = sqlite3GetTempReg(pParse);
101168  sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
101169  sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
101170  sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
101171  sqlite3ReleaseTempReg(pParse, r1);
101172}
101173
101174#ifndef SQLITE_OMIT_SUBQUERY
101175/*
101176** Generate an error message when a SELECT is used within a subexpression
101177** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
101178** column.  We do this in a subroutine because the error used to occur
101179** in multiple places.  (The error only occurs in one place now, but we
101180** retain the subroutine to minimize code disruption.)
101181*/
101182static int checkForMultiColumnSelectError(
101183  Parse *pParse,       /* Parse context. */
101184  SelectDest *pDest,   /* Destination of SELECT results */
101185  int nExpr            /* Number of result columns returned by SELECT */
101186){
101187  int eDest = pDest->eDest;
101188  if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
101189    sqlite3ErrorMsg(pParse, "only a single result allowed for "
101190       "a SELECT that is part of an expression");
101191    return 1;
101192  }else{
101193    return 0;
101194  }
101195}
101196#endif
101197
101198/*
101199** This routine generates the code for the inside of the inner loop
101200** of a SELECT.
101201**
101202** If srcTab is negative, then the pEList expressions
101203** are evaluated in order to get the data for this row.  If srcTab is
101204** zero or more, then data is pulled from srcTab and pEList is used only
101205** to get number columns and the datatype for each column.
101206*/
101207static void selectInnerLoop(
101208  Parse *pParse,          /* The parser context */
101209  Select *p,              /* The complete select statement being coded */
101210  ExprList *pEList,       /* List of values being extracted */
101211  int srcTab,             /* Pull data from this table */
101212  SortCtx *pSort,         /* If not NULL, info on how to process ORDER BY */
101213  DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
101214  SelectDest *pDest,      /* How to dispose of the results */
101215  int iContinue,          /* Jump here to continue with next row */
101216  int iBreak              /* Jump here to break out of the inner loop */
101217){
101218  Vdbe *v = pParse->pVdbe;
101219  int i;
101220  int hasDistinct;        /* True if the DISTINCT keyword is present */
101221  int regResult;              /* Start of memory holding result set */
101222  int eDest = pDest->eDest;   /* How to dispose of results */
101223  int iParm = pDest->iSDParm; /* First argument to disposal method */
101224  int nResultCol;             /* Number of result columns */
101225
101226  assert( v );
101227  assert( pEList!=0 );
101228  hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
101229  if( pSort && pSort->pOrderBy==0 ) pSort = 0;
101230  if( pSort==0 && !hasDistinct ){
101231    assert( iContinue!=0 );
101232    codeOffset(v, p->iOffset, iContinue);
101233  }
101234
101235  /* Pull the requested columns.
101236  */
101237  nResultCol = pEList->nExpr;
101238
101239  if( pDest->iSdst==0 ){
101240    pDest->iSdst = pParse->nMem+1;
101241    pParse->nMem += nResultCol;
101242  }else if( pDest->iSdst+nResultCol > pParse->nMem ){
101243    /* This is an error condition that can result, for example, when a SELECT
101244    ** on the right-hand side of an INSERT contains more result columns than
101245    ** there are columns in the table on the left.  The error will be caught
101246    ** and reported later.  But we need to make sure enough memory is allocated
101247    ** to avoid other spurious errors in the meantime. */
101248    pParse->nMem += nResultCol;
101249  }
101250  pDest->nSdst = nResultCol;
101251  regResult = pDest->iSdst;
101252  if( srcTab>=0 ){
101253    for(i=0; i<nResultCol; i++){
101254      sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
101255      VdbeComment((v, "%s", pEList->a[i].zName));
101256    }
101257  }else if( eDest!=SRT_Exists ){
101258    /* If the destination is an EXISTS(...) expression, the actual
101259    ** values returned by the SELECT are not required.
101260    */
101261    sqlite3ExprCodeExprList(pParse, pEList, regResult,
101262                  (eDest==SRT_Output||eDest==SRT_Coroutine)?SQLITE_ECEL_DUP:0);
101263  }
101264
101265  /* If the DISTINCT keyword was present on the SELECT statement
101266  ** and this row has been seen before, then do not make this row
101267  ** part of the result.
101268  */
101269  if( hasDistinct ){
101270    switch( pDistinct->eTnctType ){
101271      case WHERE_DISTINCT_ORDERED: {
101272        VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */
101273        int iJump;              /* Jump destination */
101274        int regPrev;            /* Previous row content */
101275
101276        /* Allocate space for the previous row */
101277        regPrev = pParse->nMem+1;
101278        pParse->nMem += nResultCol;
101279
101280        /* Change the OP_OpenEphemeral coded earlier to an OP_Null
101281        ** sets the MEM_Cleared bit on the first register of the
101282        ** previous value.  This will cause the OP_Ne below to always
101283        ** fail on the first iteration of the loop even if the first
101284        ** row is all NULLs.
101285        */
101286        sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
101287        pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
101288        pOp->opcode = OP_Null;
101289        pOp->p1 = 1;
101290        pOp->p2 = regPrev;
101291
101292        iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
101293        for(i=0; i<nResultCol; i++){
101294          CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
101295          if( i<nResultCol-1 ){
101296            sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
101297            VdbeCoverage(v);
101298          }else{
101299            sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
101300            VdbeCoverage(v);
101301           }
101302          sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
101303          sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
101304        }
101305        assert( sqlite3VdbeCurrentAddr(v)==iJump );
101306        sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
101307        break;
101308      }
101309
101310      case WHERE_DISTINCT_UNIQUE: {
101311        sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
101312        break;
101313      }
101314
101315      default: {
101316        assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
101317        codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol, regResult);
101318        break;
101319      }
101320    }
101321    if( pSort==0 ){
101322      codeOffset(v, p->iOffset, iContinue);
101323    }
101324  }
101325
101326  switch( eDest ){
101327    /* In this mode, write each query result to the key of the temporary
101328    ** table iParm.
101329    */
101330#ifndef SQLITE_OMIT_COMPOUND_SELECT
101331    case SRT_Union: {
101332      int r1;
101333      r1 = sqlite3GetTempReg(pParse);
101334      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
101335      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
101336      sqlite3ReleaseTempReg(pParse, r1);
101337      break;
101338    }
101339
101340    /* Construct a record from the query result, but instead of
101341    ** saving that record, use it as a key to delete elements from
101342    ** the temporary table iParm.
101343    */
101344    case SRT_Except: {
101345      sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
101346      break;
101347    }
101348#endif /* SQLITE_OMIT_COMPOUND_SELECT */
101349
101350    /* Store the result as data using a unique key.
101351    */
101352    case SRT_Fifo:
101353    case SRT_DistFifo:
101354    case SRT_Table:
101355    case SRT_EphemTab: {
101356      int r1 = sqlite3GetTempReg(pParse);
101357      testcase( eDest==SRT_Table );
101358      testcase( eDest==SRT_EphemTab );
101359      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
101360#ifndef SQLITE_OMIT_CTE
101361      if( eDest==SRT_DistFifo ){
101362        /* If the destination is DistFifo, then cursor (iParm+1) is open
101363        ** on an ephemeral index. If the current row is already present
101364        ** in the index, do not write it to the output. If not, add the
101365        ** current row to the index and proceed with writing it to the
101366        ** output table as well.  */
101367        int addr = sqlite3VdbeCurrentAddr(v) + 4;
101368        sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0); VdbeCoverage(v);
101369        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
101370        assert( pSort==0 );
101371      }
101372#endif
101373      if( pSort ){
101374        pushOntoSorter(pParse, pSort, p, r1);
101375      }else{
101376        int r2 = sqlite3GetTempReg(pParse);
101377        sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
101378        sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
101379        sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
101380        sqlite3ReleaseTempReg(pParse, r2);
101381      }
101382      sqlite3ReleaseTempReg(pParse, r1);
101383      break;
101384    }
101385
101386#ifndef SQLITE_OMIT_SUBQUERY
101387    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
101388    ** then there should be a single item on the stack.  Write this
101389    ** item into the set table with bogus data.
101390    */
101391    case SRT_Set: {
101392      assert( nResultCol==1 );
101393      pDest->affSdst =
101394                  sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
101395      if( pSort ){
101396        /* At first glance you would think we could optimize out the
101397        ** ORDER BY in this case since the order of entries in the set
101398        ** does not matter.  But there might be a LIMIT clause, in which
101399        ** case the order does matter */
101400        pushOntoSorter(pParse, pSort, p, regResult);
101401      }else{
101402        int r1 = sqlite3GetTempReg(pParse);
101403        sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
101404        sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
101405        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
101406        sqlite3ReleaseTempReg(pParse, r1);
101407      }
101408      break;
101409    }
101410
101411    /* If any row exist in the result set, record that fact and abort.
101412    */
101413    case SRT_Exists: {
101414      sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
101415      /* The LIMIT clause will terminate the loop for us */
101416      break;
101417    }
101418
101419    /* If this is a scalar select that is part of an expression, then
101420    ** store the results in the appropriate memory cell and break out
101421    ** of the scan loop.
101422    */
101423    case SRT_Mem: {
101424      assert( nResultCol==1 );
101425      if( pSort ){
101426        pushOntoSorter(pParse, pSort, p, regResult);
101427      }else{
101428        sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
101429        /* The LIMIT clause will jump out of the loop for us */
101430      }
101431      break;
101432    }
101433#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
101434
101435    case SRT_Coroutine:       /* Send data to a co-routine */
101436    case SRT_Output: {        /* Return the results */
101437      testcase( eDest==SRT_Coroutine );
101438      testcase( eDest==SRT_Output );
101439      if( pSort ){
101440        int r1 = sqlite3GetTempReg(pParse);
101441        sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
101442        pushOntoSorter(pParse, pSort, p, r1);
101443        sqlite3ReleaseTempReg(pParse, r1);
101444      }else if( eDest==SRT_Coroutine ){
101445        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
101446      }else{
101447        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
101448        sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
101449      }
101450      break;
101451    }
101452
101453#ifndef SQLITE_OMIT_CTE
101454    /* Write the results into a priority queue that is order according to
101455    ** pDest->pOrderBy (in pSO).  pDest->iSDParm (in iParm) is the cursor for an
101456    ** index with pSO->nExpr+2 columns.  Build a key using pSO for the first
101457    ** pSO->nExpr columns, then make sure all keys are unique by adding a
101458    ** final OP_Sequence column.  The last column is the record as a blob.
101459    */
101460    case SRT_DistQueue:
101461    case SRT_Queue: {
101462      int nKey;
101463      int r1, r2, r3;
101464      int addrTest = 0;
101465      ExprList *pSO;
101466      pSO = pDest->pOrderBy;
101467      assert( pSO );
101468      nKey = pSO->nExpr;
101469      r1 = sqlite3GetTempReg(pParse);
101470      r2 = sqlite3GetTempRange(pParse, nKey+2);
101471      r3 = r2+nKey+1;
101472      if( eDest==SRT_DistQueue ){
101473        /* If the destination is DistQueue, then cursor (iParm+1) is open
101474        ** on a second ephemeral index that holds all values every previously
101475        ** added to the queue. */
101476        addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
101477                                        regResult, nResultCol);
101478        VdbeCoverage(v);
101479      }
101480      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
101481      if( eDest==SRT_DistQueue ){
101482        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
101483        sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
101484      }
101485      for(i=0; i<nKey; i++){
101486        sqlite3VdbeAddOp2(v, OP_SCopy,
101487                          regResult + pSO->a[i].u.x.iOrderByCol - 1,
101488                          r2+i);
101489      }
101490      sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
101491      sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
101492      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
101493      if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
101494      sqlite3ReleaseTempReg(pParse, r1);
101495      sqlite3ReleaseTempRange(pParse, r2, nKey+2);
101496      break;
101497    }
101498#endif /* SQLITE_OMIT_CTE */
101499
101500
101501
101502#if !defined(SQLITE_OMIT_TRIGGER)
101503    /* Discard the results.  This is used for SELECT statements inside
101504    ** the body of a TRIGGER.  The purpose of such selects is to call
101505    ** user-defined functions that have side effects.  We do not care
101506    ** about the actual results of the select.
101507    */
101508    default: {
101509      assert( eDest==SRT_Discard );
101510      break;
101511    }
101512#endif
101513  }
101514
101515  /* Jump to the end of the loop if the LIMIT is reached.  Except, if
101516  ** there is a sorter, in which case the sorter has already limited
101517  ** the output for us.
101518  */
101519  if( pSort==0 && p->iLimit ){
101520    sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); VdbeCoverage(v);
101521  }
101522}
101523
101524/*
101525** Allocate a KeyInfo object sufficient for an index of N key columns and
101526** X extra columns.
101527*/
101528SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
101529  KeyInfo *p = sqlite3DbMallocZero(0,
101530                   sizeof(KeyInfo) + (N+X)*(sizeof(CollSeq*)+1));
101531  if( p ){
101532    p->aSortOrder = (u8*)&p->aColl[N+X];
101533    p->nField = (u16)N;
101534    p->nXField = (u16)X;
101535    p->enc = ENC(db);
101536    p->db = db;
101537    p->nRef = 1;
101538  }else{
101539    db->mallocFailed = 1;
101540  }
101541  return p;
101542}
101543
101544/*
101545** Deallocate a KeyInfo object
101546*/
101547SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
101548  if( p ){
101549    assert( p->nRef>0 );
101550    p->nRef--;
101551    if( p->nRef==0 ) sqlite3DbFree(0, p);
101552  }
101553}
101554
101555/*
101556** Make a new pointer to a KeyInfo object
101557*/
101558SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
101559  if( p ){
101560    assert( p->nRef>0 );
101561    p->nRef++;
101562  }
101563  return p;
101564}
101565
101566#ifdef SQLITE_DEBUG
101567/*
101568** Return TRUE if a KeyInfo object can be change.  The KeyInfo object
101569** can only be changed if this is just a single reference to the object.
101570**
101571** This routine is used only inside of assert() statements.
101572*/
101573SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
101574#endif /* SQLITE_DEBUG */
101575
101576/*
101577** Given an expression list, generate a KeyInfo structure that records
101578** the collating sequence for each expression in that expression list.
101579**
101580** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
101581** KeyInfo structure is appropriate for initializing a virtual index to
101582** implement that clause.  If the ExprList is the result set of a SELECT
101583** then the KeyInfo structure is appropriate for initializing a virtual
101584** index to implement a DISTINCT test.
101585**
101586** Space to hold the KeyInfo structure is obtain from malloc.  The calling
101587** function is responsible for seeing that this structure is eventually
101588** freed.
101589*/
101590static KeyInfo *keyInfoFromExprList(
101591  Parse *pParse,       /* Parsing context */
101592  ExprList *pList,     /* Form the KeyInfo object from this ExprList */
101593  int iStart,          /* Begin with this column of pList */
101594  int nExtra           /* Add this many extra columns to the end */
101595){
101596  int nExpr;
101597  KeyInfo *pInfo;
101598  struct ExprList_item *pItem;
101599  sqlite3 *db = pParse->db;
101600  int i;
101601
101602  nExpr = pList->nExpr;
101603  pInfo = sqlite3KeyInfoAlloc(db, nExpr+nExtra-iStart, 1);
101604  if( pInfo ){
101605    assert( sqlite3KeyInfoIsWriteable(pInfo) );
101606    for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
101607      CollSeq *pColl;
101608      pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
101609      if( !pColl ) pColl = db->pDfltColl;
101610      pInfo->aColl[i-iStart] = pColl;
101611      pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
101612    }
101613  }
101614  return pInfo;
101615}
101616
101617#ifndef SQLITE_OMIT_COMPOUND_SELECT
101618/*
101619** Name of the connection operator, used for error messages.
101620*/
101621static const char *selectOpName(int id){
101622  char *z;
101623  switch( id ){
101624    case TK_ALL:       z = "UNION ALL";   break;
101625    case TK_INTERSECT: z = "INTERSECT";   break;
101626    case TK_EXCEPT:    z = "EXCEPT";      break;
101627    default:           z = "UNION";       break;
101628  }
101629  return z;
101630}
101631#endif /* SQLITE_OMIT_COMPOUND_SELECT */
101632
101633#ifndef SQLITE_OMIT_EXPLAIN
101634/*
101635** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
101636** is a no-op. Otherwise, it adds a single row of output to the EQP result,
101637** where the caption is of the form:
101638**
101639**   "USE TEMP B-TREE FOR xxx"
101640**
101641** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
101642** is determined by the zUsage argument.
101643*/
101644static void explainTempTable(Parse *pParse, const char *zUsage){
101645  if( pParse->explain==2 ){
101646    Vdbe *v = pParse->pVdbe;
101647    char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
101648    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
101649  }
101650}
101651
101652/*
101653** Assign expression b to lvalue a. A second, no-op, version of this macro
101654** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
101655** in sqlite3Select() to assign values to structure member variables that
101656** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
101657** code with #ifndef directives.
101658*/
101659# define explainSetInteger(a, b) a = b
101660
101661#else
101662/* No-op versions of the explainXXX() functions and macros. */
101663# define explainTempTable(y,z)
101664# define explainSetInteger(y,z)
101665#endif
101666
101667#if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
101668/*
101669** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
101670** is a no-op. Otherwise, it adds a single row of output to the EQP result,
101671** where the caption is of one of the two forms:
101672**
101673**   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
101674**   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
101675**
101676** where iSub1 and iSub2 are the integers passed as the corresponding
101677** function parameters, and op is the text representation of the parameter
101678** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
101679** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
101680** false, or the second form if it is true.
101681*/
101682static void explainComposite(
101683  Parse *pParse,                  /* Parse context */
101684  int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
101685  int iSub1,                      /* Subquery id 1 */
101686  int iSub2,                      /* Subquery id 2 */
101687  int bUseTmp                     /* True if a temp table was used */
101688){
101689  assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
101690  if( pParse->explain==2 ){
101691    Vdbe *v = pParse->pVdbe;
101692    char *zMsg = sqlite3MPrintf(
101693        pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
101694        bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
101695    );
101696    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
101697  }
101698}
101699#else
101700/* No-op versions of the explainXXX() functions and macros. */
101701# define explainComposite(v,w,x,y,z)
101702#endif
101703
101704/*
101705** If the inner loop was generated using a non-null pOrderBy argument,
101706** then the results were placed in a sorter.  After the loop is terminated
101707** we need to run the sorter and output the results.  The following
101708** routine generates the code needed to do that.
101709*/
101710static void generateSortTail(
101711  Parse *pParse,    /* Parsing context */
101712  Select *p,        /* The SELECT statement */
101713  SortCtx *pSort,   /* Information on the ORDER BY clause */
101714  int nColumn,      /* Number of columns of data */
101715  SelectDest *pDest /* Write the sorted results here */
101716){
101717  Vdbe *v = pParse->pVdbe;                     /* The prepared statement */
101718  int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
101719  int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
101720  int addr;
101721  int addrOnce = 0;
101722  int iTab;
101723  int pseudoTab = 0;
101724  ExprList *pOrderBy = pSort->pOrderBy;
101725  int eDest = pDest->eDest;
101726  int iParm = pDest->iSDParm;
101727  int regRow;
101728  int regRowid;
101729  int nKey;
101730
101731  if( pSort->labelBkOut ){
101732    sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
101733    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrBreak);
101734    sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
101735    addrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
101736  }
101737  iTab = pSort->iECursor;
101738  regRow = sqlite3GetTempReg(pParse);
101739  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
101740    pseudoTab = pParse->nTab++;
101741    sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
101742    regRowid = 0;
101743  }else{
101744    regRowid = sqlite3GetTempReg(pParse);
101745  }
101746  nKey = pOrderBy->nExpr - pSort->nOBSat;
101747  if( pSort->sortFlags & SORTFLAG_UseSorter ){
101748    int regSortOut = ++pParse->nMem;
101749    int ptab2 = pParse->nTab++;
101750    sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, nKey+2);
101751    if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
101752    addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
101753    VdbeCoverage(v);
101754    codeOffset(v, p->iOffset, addrContinue);
101755    sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
101756    sqlite3VdbeAddOp3(v, OP_Column, ptab2, nKey+1, regRow);
101757    sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
101758  }else{
101759    if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
101760    addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
101761    codeOffset(v, p->iOffset, addrContinue);
101762    sqlite3VdbeAddOp3(v, OP_Column, iTab, nKey+1, regRow);
101763  }
101764  switch( eDest ){
101765    case SRT_Table:
101766    case SRT_EphemTab: {
101767      testcase( eDest==SRT_Table );
101768      testcase( eDest==SRT_EphemTab );
101769      sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
101770      sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
101771      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
101772      break;
101773    }
101774#ifndef SQLITE_OMIT_SUBQUERY
101775    case SRT_Set: {
101776      assert( nColumn==1 );
101777      sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
101778                        &pDest->affSdst, 1);
101779      sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
101780      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
101781      break;
101782    }
101783    case SRT_Mem: {
101784      assert( nColumn==1 );
101785      sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
101786      /* The LIMIT clause will terminate the loop for us */
101787      break;
101788    }
101789#endif
101790    default: {
101791      int i;
101792      assert( eDest==SRT_Output || eDest==SRT_Coroutine );
101793      testcase( eDest==SRT_Output );
101794      testcase( eDest==SRT_Coroutine );
101795      for(i=0; i<nColumn; i++){
101796        assert( regRow!=pDest->iSdst+i );
101797        sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iSdst+i);
101798        if( i==0 ){
101799          sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
101800        }
101801      }
101802      if( eDest==SRT_Output ){
101803        sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
101804        sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
101805      }else{
101806        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
101807      }
101808      break;
101809    }
101810  }
101811  sqlite3ReleaseTempReg(pParse, regRow);
101812  sqlite3ReleaseTempReg(pParse, regRowid);
101813
101814  /* The bottom of the loop
101815  */
101816  sqlite3VdbeResolveLabel(v, addrContinue);
101817  if( pSort->sortFlags & SORTFLAG_UseSorter ){
101818    sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
101819  }else{
101820    sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
101821  }
101822  if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
101823  sqlite3VdbeResolveLabel(v, addrBreak);
101824}
101825
101826/*
101827** Return a pointer to a string containing the 'declaration type' of the
101828** expression pExpr. The string may be treated as static by the caller.
101829**
101830** Also try to estimate the size of the returned value and return that
101831** result in *pEstWidth.
101832**
101833** The declaration type is the exact datatype definition extracted from the
101834** original CREATE TABLE statement if the expression is a column. The
101835** declaration type for a ROWID field is INTEGER. Exactly when an expression
101836** is considered a column can be complex in the presence of subqueries. The
101837** result-set expression in all of the following SELECT statements is
101838** considered a column by this function.
101839**
101840**   SELECT col FROM tbl;
101841**   SELECT (SELECT col FROM tbl;
101842**   SELECT (SELECT col FROM tbl);
101843**   SELECT abc FROM (SELECT col AS abc FROM tbl);
101844**
101845** The declaration type for any expression other than a column is NULL.
101846**
101847** This routine has either 3 or 6 parameters depending on whether or not
101848** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
101849*/
101850#ifdef SQLITE_ENABLE_COLUMN_METADATA
101851# define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
101852static const char *columnTypeImpl(
101853  NameContext *pNC,
101854  Expr *pExpr,
101855  const char **pzOrigDb,
101856  const char **pzOrigTab,
101857  const char **pzOrigCol,
101858  u8 *pEstWidth
101859){
101860  char const *zOrigDb = 0;
101861  char const *zOrigTab = 0;
101862  char const *zOrigCol = 0;
101863#else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
101864# define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
101865static const char *columnTypeImpl(
101866  NameContext *pNC,
101867  Expr *pExpr,
101868  u8 *pEstWidth
101869){
101870#endif /* !defined(SQLITE_ENABLE_COLUMN_METADATA) */
101871  char const *zType = 0;
101872  int j;
101873  u8 estWidth = 1;
101874
101875  if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
101876  switch( pExpr->op ){
101877    case TK_AGG_COLUMN:
101878    case TK_COLUMN: {
101879      /* The expression is a column. Locate the table the column is being
101880      ** extracted from in NameContext.pSrcList. This table may be real
101881      ** database table or a subquery.
101882      */
101883      Table *pTab = 0;            /* Table structure column is extracted from */
101884      Select *pS = 0;             /* Select the column is extracted from */
101885      int iCol = pExpr->iColumn;  /* Index of column in pTab */
101886      testcase( pExpr->op==TK_AGG_COLUMN );
101887      testcase( pExpr->op==TK_COLUMN );
101888      while( pNC && !pTab ){
101889        SrcList *pTabList = pNC->pSrcList;
101890        for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
101891        if( j<pTabList->nSrc ){
101892          pTab = pTabList->a[j].pTab;
101893          pS = pTabList->a[j].pSelect;
101894        }else{
101895          pNC = pNC->pNext;
101896        }
101897      }
101898
101899      if( pTab==0 ){
101900        /* At one time, code such as "SELECT new.x" within a trigger would
101901        ** cause this condition to run.  Since then, we have restructured how
101902        ** trigger code is generated and so this condition is no longer
101903        ** possible. However, it can still be true for statements like
101904        ** the following:
101905        **
101906        **   CREATE TABLE t1(col INTEGER);
101907        **   SELECT (SELECT t1.col) FROM FROM t1;
101908        **
101909        ** when columnType() is called on the expression "t1.col" in the
101910        ** sub-select. In this case, set the column type to NULL, even
101911        ** though it should really be "INTEGER".
101912        **
101913        ** This is not a problem, as the column type of "t1.col" is never
101914        ** used. When columnType() is called on the expression
101915        ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
101916        ** branch below.  */
101917        break;
101918      }
101919
101920      assert( pTab && pExpr->pTab==pTab );
101921      if( pS ){
101922        /* The "table" is actually a sub-select or a view in the FROM clause
101923        ** of the SELECT statement. Return the declaration type and origin
101924        ** data for the result-set column of the sub-select.
101925        */
101926        if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
101927          /* If iCol is less than zero, then the expression requests the
101928          ** rowid of the sub-select or view. This expression is legal (see
101929          ** test case misc2.2.2) - it always evaluates to NULL.
101930          */
101931          NameContext sNC;
101932          Expr *p = pS->pEList->a[iCol].pExpr;
101933          sNC.pSrcList = pS->pSrc;
101934          sNC.pNext = pNC;
101935          sNC.pParse = pNC->pParse;
101936          zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
101937        }
101938      }else if( pTab->pSchema ){
101939        /* A real table */
101940        assert( !pS );
101941        if( iCol<0 ) iCol = pTab->iPKey;
101942        assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
101943#ifdef SQLITE_ENABLE_COLUMN_METADATA
101944        if( iCol<0 ){
101945          zType = "INTEGER";
101946          zOrigCol = "rowid";
101947        }else{
101948          zType = pTab->aCol[iCol].zType;
101949          zOrigCol = pTab->aCol[iCol].zName;
101950          estWidth = pTab->aCol[iCol].szEst;
101951        }
101952        zOrigTab = pTab->zName;
101953        if( pNC->pParse ){
101954          int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
101955          zOrigDb = pNC->pParse->db->aDb[iDb].zName;
101956        }
101957#else
101958        if( iCol<0 ){
101959          zType = "INTEGER";
101960        }else{
101961          zType = pTab->aCol[iCol].zType;
101962          estWidth = pTab->aCol[iCol].szEst;
101963        }
101964#endif
101965      }
101966      break;
101967    }
101968#ifndef SQLITE_OMIT_SUBQUERY
101969    case TK_SELECT: {
101970      /* The expression is a sub-select. Return the declaration type and
101971      ** origin info for the single column in the result set of the SELECT
101972      ** statement.
101973      */
101974      NameContext sNC;
101975      Select *pS = pExpr->x.pSelect;
101976      Expr *p = pS->pEList->a[0].pExpr;
101977      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
101978      sNC.pSrcList = pS->pSrc;
101979      sNC.pNext = pNC;
101980      sNC.pParse = pNC->pParse;
101981      zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
101982      break;
101983    }
101984#endif
101985  }
101986
101987#ifdef SQLITE_ENABLE_COLUMN_METADATA
101988  if( pzOrigDb ){
101989    assert( pzOrigTab && pzOrigCol );
101990    *pzOrigDb = zOrigDb;
101991    *pzOrigTab = zOrigTab;
101992    *pzOrigCol = zOrigCol;
101993  }
101994#endif
101995  if( pEstWidth ) *pEstWidth = estWidth;
101996  return zType;
101997}
101998
101999/*
102000** Generate code that will tell the VDBE the declaration types of columns
102001** in the result set.
102002*/
102003static void generateColumnTypes(
102004  Parse *pParse,      /* Parser context */
102005  SrcList *pTabList,  /* List of tables */
102006  ExprList *pEList    /* Expressions defining the result set */
102007){
102008#ifndef SQLITE_OMIT_DECLTYPE
102009  Vdbe *v = pParse->pVdbe;
102010  int i;
102011  NameContext sNC;
102012  sNC.pSrcList = pTabList;
102013  sNC.pParse = pParse;
102014  for(i=0; i<pEList->nExpr; i++){
102015    Expr *p = pEList->a[i].pExpr;
102016    const char *zType;
102017#ifdef SQLITE_ENABLE_COLUMN_METADATA
102018    const char *zOrigDb = 0;
102019    const char *zOrigTab = 0;
102020    const char *zOrigCol = 0;
102021    zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
102022
102023    /* The vdbe must make its own copy of the column-type and other
102024    ** column specific strings, in case the schema is reset before this
102025    ** virtual machine is deleted.
102026    */
102027    sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
102028    sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
102029    sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
102030#else
102031    zType = columnType(&sNC, p, 0, 0, 0, 0);
102032#endif
102033    sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
102034  }
102035#endif /* !defined(SQLITE_OMIT_DECLTYPE) */
102036}
102037
102038/*
102039** Generate code that will tell the VDBE the names of columns
102040** in the result set.  This information is used to provide the
102041** azCol[] values in the callback.
102042*/
102043static void generateColumnNames(
102044  Parse *pParse,      /* Parser context */
102045  SrcList *pTabList,  /* List of tables */
102046  ExprList *pEList    /* Expressions defining the result set */
102047){
102048  Vdbe *v = pParse->pVdbe;
102049  int i, j;
102050  sqlite3 *db = pParse->db;
102051  int fullNames, shortNames;
102052
102053#ifndef SQLITE_OMIT_EXPLAIN
102054  /* If this is an EXPLAIN, skip this step */
102055  if( pParse->explain ){
102056    return;
102057  }
102058#endif
102059
102060  if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
102061  pParse->colNamesSet = 1;
102062  fullNames = (db->flags & SQLITE_FullColNames)!=0;
102063  shortNames = (db->flags & SQLITE_ShortColNames)!=0;
102064  sqlite3VdbeSetNumCols(v, pEList->nExpr);
102065  for(i=0; i<pEList->nExpr; i++){
102066    Expr *p;
102067    p = pEList->a[i].pExpr;
102068    if( NEVER(p==0) ) continue;
102069    if( pEList->a[i].zName ){
102070      char *zName = pEList->a[i].zName;
102071      sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
102072    }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
102073      Table *pTab;
102074      char *zCol;
102075      int iCol = p->iColumn;
102076      for(j=0; ALWAYS(j<pTabList->nSrc); j++){
102077        if( pTabList->a[j].iCursor==p->iTable ) break;
102078      }
102079      assert( j<pTabList->nSrc );
102080      pTab = pTabList->a[j].pTab;
102081      if( iCol<0 ) iCol = pTab->iPKey;
102082      assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
102083      if( iCol<0 ){
102084        zCol = "rowid";
102085      }else{
102086        zCol = pTab->aCol[iCol].zName;
102087      }
102088      if( !shortNames && !fullNames ){
102089        sqlite3VdbeSetColName(v, i, COLNAME_NAME,
102090            sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
102091      }else if( fullNames ){
102092        char *zName = 0;
102093        zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
102094        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
102095      }else{
102096        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
102097      }
102098    }else{
102099      const char *z = pEList->a[i].zSpan;
102100      z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
102101      sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
102102    }
102103  }
102104  generateColumnTypes(pParse, pTabList, pEList);
102105}
102106
102107/*
102108** Given a an expression list (which is really the list of expressions
102109** that form the result set of a SELECT statement) compute appropriate
102110** column names for a table that would hold the expression list.
102111**
102112** All column names will be unique.
102113**
102114** Only the column names are computed.  Column.zType, Column.zColl,
102115** and other fields of Column are zeroed.
102116**
102117** Return SQLITE_OK on success.  If a memory allocation error occurs,
102118** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
102119*/
102120static int selectColumnsFromExprList(
102121  Parse *pParse,          /* Parsing context */
102122  ExprList *pEList,       /* Expr list from which to derive column names */
102123  i16 *pnCol,             /* Write the number of columns here */
102124  Column **paCol          /* Write the new column list here */
102125){
102126  sqlite3 *db = pParse->db;   /* Database connection */
102127  int i, j;                   /* Loop counters */
102128  int cnt;                    /* Index added to make the name unique */
102129  Column *aCol, *pCol;        /* For looping over result columns */
102130  int nCol;                   /* Number of columns in the result set */
102131  Expr *p;                    /* Expression for a single result column */
102132  char *zName;                /* Column name */
102133  int nName;                  /* Size of name in zName[] */
102134
102135  if( pEList ){
102136    nCol = pEList->nExpr;
102137    aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
102138    testcase( aCol==0 );
102139  }else{
102140    nCol = 0;
102141    aCol = 0;
102142  }
102143  *pnCol = nCol;
102144  *paCol = aCol;
102145
102146  for(i=0, pCol=aCol; i<nCol; i++, pCol++){
102147    /* Get an appropriate name for the column
102148    */
102149    p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
102150    if( (zName = pEList->a[i].zName)!=0 ){
102151      /* If the column contains an "AS <name>" phrase, use <name> as the name */
102152      zName = sqlite3DbStrDup(db, zName);
102153    }else{
102154      Expr *pColExpr = p;  /* The expression that is the result column name */
102155      Table *pTab;         /* Table associated with this expression */
102156      while( pColExpr->op==TK_DOT ){
102157        pColExpr = pColExpr->pRight;
102158        assert( pColExpr!=0 );
102159      }
102160      if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
102161        /* For columns use the column name name */
102162        int iCol = pColExpr->iColumn;
102163        pTab = pColExpr->pTab;
102164        if( iCol<0 ) iCol = pTab->iPKey;
102165        zName = sqlite3MPrintf(db, "%s",
102166                 iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
102167      }else if( pColExpr->op==TK_ID ){
102168        assert( !ExprHasProperty(pColExpr, EP_IntValue) );
102169        zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
102170      }else{
102171        /* Use the original text of the column expression as its name */
102172        zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
102173      }
102174    }
102175    if( db->mallocFailed ){
102176      sqlite3DbFree(db, zName);
102177      break;
102178    }
102179
102180    /* Make sure the column name is unique.  If the name is not unique,
102181    ** append a integer to the name so that it becomes unique.
102182    */
102183    nName = sqlite3Strlen30(zName);
102184    for(j=cnt=0; j<i; j++){
102185      if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
102186        char *zNewName;
102187        int k;
102188        for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){}
102189        if( k>=0 && zName[k]==':' ) nName = k;
102190        zName[nName] = 0;
102191        zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
102192        sqlite3DbFree(db, zName);
102193        zName = zNewName;
102194        j = -1;
102195        if( zName==0 ) break;
102196      }
102197    }
102198    pCol->zName = zName;
102199  }
102200  if( db->mallocFailed ){
102201    for(j=0; j<i; j++){
102202      sqlite3DbFree(db, aCol[j].zName);
102203    }
102204    sqlite3DbFree(db, aCol);
102205    *paCol = 0;
102206    *pnCol = 0;
102207    return SQLITE_NOMEM;
102208  }
102209  return SQLITE_OK;
102210}
102211
102212/*
102213** Add type and collation information to a column list based on
102214** a SELECT statement.
102215**
102216** The column list presumably came from selectColumnNamesFromExprList().
102217** The column list has only names, not types or collations.  This
102218** routine goes through and adds the types and collations.
102219**
102220** This routine requires that all identifiers in the SELECT
102221** statement be resolved.
102222*/
102223static void selectAddColumnTypeAndCollation(
102224  Parse *pParse,        /* Parsing contexts */
102225  Table *pTab,          /* Add column type information to this table */
102226  Select *pSelect       /* SELECT used to determine types and collations */
102227){
102228  sqlite3 *db = pParse->db;
102229  NameContext sNC;
102230  Column *pCol;
102231  CollSeq *pColl;
102232  int i;
102233  Expr *p;
102234  struct ExprList_item *a;
102235  u64 szAll = 0;
102236
102237  assert( pSelect!=0 );
102238  assert( (pSelect->selFlags & SF_Resolved)!=0 );
102239  assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
102240  if( db->mallocFailed ) return;
102241  memset(&sNC, 0, sizeof(sNC));
102242  sNC.pSrcList = pSelect->pSrc;
102243  a = pSelect->pEList->a;
102244  for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
102245    p = a[i].pExpr;
102246    pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p,0,0,0, &pCol->szEst));
102247    szAll += pCol->szEst;
102248    pCol->affinity = sqlite3ExprAffinity(p);
102249    if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
102250    pColl = sqlite3ExprCollSeq(pParse, p);
102251    if( pColl ){
102252      pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
102253    }
102254  }
102255  pTab->szTabRow = sqlite3LogEst(szAll*4);
102256}
102257
102258/*
102259** Given a SELECT statement, generate a Table structure that describes
102260** the result set of that SELECT.
102261*/
102262SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
102263  Table *pTab;
102264  sqlite3 *db = pParse->db;
102265  int savedFlags;
102266
102267  savedFlags = db->flags;
102268  db->flags &= ~SQLITE_FullColNames;
102269  db->flags |= SQLITE_ShortColNames;
102270  sqlite3SelectPrep(pParse, pSelect, 0);
102271  if( pParse->nErr ) return 0;
102272  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
102273  db->flags = savedFlags;
102274  pTab = sqlite3DbMallocZero(db, sizeof(Table) );
102275  if( pTab==0 ){
102276    return 0;
102277  }
102278  /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
102279  ** is disabled */
102280  assert( db->lookaside.bEnabled==0 );
102281  pTab->nRef = 1;
102282  pTab->zName = 0;
102283  pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
102284  selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
102285  selectAddColumnTypeAndCollation(pParse, pTab, pSelect);
102286  pTab->iPKey = -1;
102287  if( db->mallocFailed ){
102288    sqlite3DeleteTable(db, pTab);
102289    return 0;
102290  }
102291  return pTab;
102292}
102293
102294/*
102295** Get a VDBE for the given parser context.  Create a new one if necessary.
102296** If an error occurs, return NULL and leave a message in pParse.
102297*/
102298SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
102299  Vdbe *v = pParse->pVdbe;
102300  if( v==0 ){
102301    v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
102302    if( v ) sqlite3VdbeAddOp0(v, OP_Init);
102303    if( pParse->pToplevel==0
102304     && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
102305    ){
102306      pParse->okConstFactor = 1;
102307    }
102308
102309  }
102310  return v;
102311}
102312
102313
102314/*
102315** Compute the iLimit and iOffset fields of the SELECT based on the
102316** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
102317** that appear in the original SQL statement after the LIMIT and OFFSET
102318** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
102319** are the integer memory register numbers for counters used to compute
102320** the limit and offset.  If there is no limit and/or offset, then
102321** iLimit and iOffset are negative.
102322**
102323** This routine changes the values of iLimit and iOffset only if
102324** a limit or offset is defined by pLimit and pOffset.  iLimit and
102325** iOffset should have been preset to appropriate default values (zero)
102326** prior to calling this routine.
102327**
102328** The iOffset register (if it exists) is initialized to the value
102329** of the OFFSET.  The iLimit register is initialized to LIMIT.  Register
102330** iOffset+1 is initialized to LIMIT+OFFSET.
102331**
102332** Only if pLimit!=0 or pOffset!=0 do the limit registers get
102333** redefined.  The UNION ALL operator uses this property to force
102334** the reuse of the same limit and offset registers across multiple
102335** SELECT statements.
102336*/
102337static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
102338  Vdbe *v = 0;
102339  int iLimit = 0;
102340  int iOffset;
102341  int addr1, n;
102342  if( p->iLimit ) return;
102343
102344  /*
102345  ** "LIMIT -1" always shows all rows.  There is some
102346  ** controversy about what the correct behavior should be.
102347  ** The current implementation interprets "LIMIT 0" to mean
102348  ** no rows.
102349  */
102350  sqlite3ExprCacheClear(pParse);
102351  assert( p->pOffset==0 || p->pLimit!=0 );
102352  if( p->pLimit ){
102353    p->iLimit = iLimit = ++pParse->nMem;
102354    v = sqlite3GetVdbe(pParse);
102355    assert( v!=0 );
102356    if( sqlite3ExprIsInteger(p->pLimit, &n) ){
102357      sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
102358      VdbeComment((v, "LIMIT counter"));
102359      if( n==0 ){
102360        sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
102361      }else if( n>=0 && p->nSelectRow>(u64)n ){
102362        p->nSelectRow = n;
102363      }
102364    }else{
102365      sqlite3ExprCode(pParse, p->pLimit, iLimit);
102366      sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
102367      VdbeComment((v, "LIMIT counter"));
102368      sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak); VdbeCoverage(v);
102369    }
102370    if( p->pOffset ){
102371      p->iOffset = iOffset = ++pParse->nMem;
102372      pParse->nMem++;   /* Allocate an extra register for limit+offset */
102373      sqlite3ExprCode(pParse, p->pOffset, iOffset);
102374      sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
102375      VdbeComment((v, "OFFSET counter"));
102376      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset); VdbeCoverage(v);
102377      sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
102378      sqlite3VdbeJumpHere(v, addr1);
102379      sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
102380      VdbeComment((v, "LIMIT+OFFSET"));
102381      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit); VdbeCoverage(v);
102382      sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
102383      sqlite3VdbeJumpHere(v, addr1);
102384    }
102385  }
102386}
102387
102388#ifndef SQLITE_OMIT_COMPOUND_SELECT
102389/*
102390** Return the appropriate collating sequence for the iCol-th column of
102391** the result set for the compound-select statement "p".  Return NULL if
102392** the column has no default collating sequence.
102393**
102394** The collating sequence for the compound select is taken from the
102395** left-most term of the select that has a collating sequence.
102396*/
102397static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
102398  CollSeq *pRet;
102399  if( p->pPrior ){
102400    pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
102401  }else{
102402    pRet = 0;
102403  }
102404  assert( iCol>=0 );
102405  if( pRet==0 && iCol<p->pEList->nExpr ){
102406    pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
102407  }
102408  return pRet;
102409}
102410
102411/*
102412** The select statement passed as the second parameter is a compound SELECT
102413** with an ORDER BY clause. This function allocates and returns a KeyInfo
102414** structure suitable for implementing the ORDER BY.
102415**
102416** Space to hold the KeyInfo structure is obtained from malloc. The calling
102417** function is responsible for ensuring that this structure is eventually
102418** freed.
102419*/
102420static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
102421  ExprList *pOrderBy = p->pOrderBy;
102422  int nOrderBy = p->pOrderBy->nExpr;
102423  sqlite3 *db = pParse->db;
102424  KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
102425  if( pRet ){
102426    int i;
102427    for(i=0; i<nOrderBy; i++){
102428      struct ExprList_item *pItem = &pOrderBy->a[i];
102429      Expr *pTerm = pItem->pExpr;
102430      CollSeq *pColl;
102431
102432      if( pTerm->flags & EP_Collate ){
102433        pColl = sqlite3ExprCollSeq(pParse, pTerm);
102434      }else{
102435        pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
102436        if( pColl==0 ) pColl = db->pDfltColl;
102437        pOrderBy->a[i].pExpr =
102438          sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
102439      }
102440      assert( sqlite3KeyInfoIsWriteable(pRet) );
102441      pRet->aColl[i] = pColl;
102442      pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
102443    }
102444  }
102445
102446  return pRet;
102447}
102448
102449#ifndef SQLITE_OMIT_CTE
102450/*
102451** This routine generates VDBE code to compute the content of a WITH RECURSIVE
102452** query of the form:
102453**
102454**   <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
102455**                         \___________/             \_______________/
102456**                           p->pPrior                      p
102457**
102458**
102459** There is exactly one reference to the recursive-table in the FROM clause
102460** of recursive-query, marked with the SrcList->a[].isRecursive flag.
102461**
102462** The setup-query runs once to generate an initial set of rows that go
102463** into a Queue table.  Rows are extracted from the Queue table one by
102464** one.  Each row extracted from Queue is output to pDest.  Then the single
102465** extracted row (now in the iCurrent table) becomes the content of the
102466** recursive-table for a recursive-query run.  The output of the recursive-query
102467** is added back into the Queue table.  Then another row is extracted from Queue
102468** and the iteration continues until the Queue table is empty.
102469**
102470** If the compound query operator is UNION then no duplicate rows are ever
102471** inserted into the Queue table.  The iDistinct table keeps a copy of all rows
102472** that have ever been inserted into Queue and causes duplicates to be
102473** discarded.  If the operator is UNION ALL, then duplicates are allowed.
102474**
102475** If the query has an ORDER BY, then entries in the Queue table are kept in
102476** ORDER BY order and the first entry is extracted for each cycle.  Without
102477** an ORDER BY, the Queue table is just a FIFO.
102478**
102479** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
102480** have been output to pDest.  A LIMIT of zero means to output no rows and a
102481** negative LIMIT means to output all rows.  If there is also an OFFSET clause
102482** with a positive value, then the first OFFSET outputs are discarded rather
102483** than being sent to pDest.  The LIMIT count does not begin until after OFFSET
102484** rows have been skipped.
102485*/
102486static void generateWithRecursiveQuery(
102487  Parse *pParse,        /* Parsing context */
102488  Select *p,            /* The recursive SELECT to be coded */
102489  SelectDest *pDest     /* What to do with query results */
102490){
102491  SrcList *pSrc = p->pSrc;      /* The FROM clause of the recursive query */
102492  int nCol = p->pEList->nExpr;  /* Number of columns in the recursive table */
102493  Vdbe *v = pParse->pVdbe;      /* The prepared statement under construction */
102494  Select *pSetup = p->pPrior;   /* The setup query */
102495  int addrTop;                  /* Top of the loop */
102496  int addrCont, addrBreak;      /* CONTINUE and BREAK addresses */
102497  int iCurrent = 0;             /* The Current table */
102498  int regCurrent;               /* Register holding Current table */
102499  int iQueue;                   /* The Queue table */
102500  int iDistinct = 0;            /* To ensure unique results if UNION */
102501  int eDest = SRT_Fifo;         /* How to write to Queue */
102502  SelectDest destQueue;         /* SelectDest targetting the Queue table */
102503  int i;                        /* Loop counter */
102504  int rc;                       /* Result code */
102505  ExprList *pOrderBy;           /* The ORDER BY clause */
102506  Expr *pLimit, *pOffset;       /* Saved LIMIT and OFFSET */
102507  int regLimit, regOffset;      /* Registers used by LIMIT and OFFSET */
102508
102509  /* Obtain authorization to do a recursive query */
102510  if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
102511
102512  /* Process the LIMIT and OFFSET clauses, if they exist */
102513  addrBreak = sqlite3VdbeMakeLabel(v);
102514  computeLimitRegisters(pParse, p, addrBreak);
102515  pLimit = p->pLimit;
102516  pOffset = p->pOffset;
102517  regLimit = p->iLimit;
102518  regOffset = p->iOffset;
102519  p->pLimit = p->pOffset = 0;
102520  p->iLimit = p->iOffset = 0;
102521  pOrderBy = p->pOrderBy;
102522
102523  /* Locate the cursor number of the Current table */
102524  for(i=0; ALWAYS(i<pSrc->nSrc); i++){
102525    if( pSrc->a[i].isRecursive ){
102526      iCurrent = pSrc->a[i].iCursor;
102527      break;
102528    }
102529  }
102530
102531  /* Allocate cursors numbers for Queue and Distinct.  The cursor number for
102532  ** the Distinct table must be exactly one greater than Queue in order
102533  ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
102534  iQueue = pParse->nTab++;
102535  if( p->op==TK_UNION ){
102536    eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
102537    iDistinct = pParse->nTab++;
102538  }else{
102539    eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
102540  }
102541  sqlite3SelectDestInit(&destQueue, eDest, iQueue);
102542
102543  /* Allocate cursors for Current, Queue, and Distinct. */
102544  regCurrent = ++pParse->nMem;
102545  sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
102546  if( pOrderBy ){
102547    KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
102548    sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
102549                      (char*)pKeyInfo, P4_KEYINFO);
102550    destQueue.pOrderBy = pOrderBy;
102551  }else{
102552    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
102553  }
102554  VdbeComment((v, "Queue table"));
102555  if( iDistinct ){
102556    p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
102557    p->selFlags |= SF_UsesEphemeral;
102558  }
102559
102560  /* Detach the ORDER BY clause from the compound SELECT */
102561  p->pOrderBy = 0;
102562
102563  /* Store the results of the setup-query in Queue. */
102564  pSetup->pNext = 0;
102565  rc = sqlite3Select(pParse, pSetup, &destQueue);
102566  pSetup->pNext = p;
102567  if( rc ) goto end_of_recursive_query;
102568
102569  /* Find the next row in the Queue and output that row */
102570  addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
102571
102572  /* Transfer the next row in Queue over to Current */
102573  sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
102574  if( pOrderBy ){
102575    sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
102576  }else{
102577    sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
102578  }
102579  sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
102580
102581  /* Output the single row in Current */
102582  addrCont = sqlite3VdbeMakeLabel(v);
102583  codeOffset(v, regOffset, addrCont);
102584  selectInnerLoop(pParse, p, p->pEList, iCurrent,
102585      0, 0, pDest, addrCont, addrBreak);
102586  if( regLimit ){
102587    sqlite3VdbeAddOp3(v, OP_IfZero, regLimit, addrBreak, -1);
102588    VdbeCoverage(v);
102589  }
102590  sqlite3VdbeResolveLabel(v, addrCont);
102591
102592  /* Execute the recursive SELECT taking the single row in Current as
102593  ** the value for the recursive-table. Store the results in the Queue.
102594  */
102595  p->pPrior = 0;
102596  sqlite3Select(pParse, p, &destQueue);
102597  assert( p->pPrior==0 );
102598  p->pPrior = pSetup;
102599
102600  /* Keep running the loop until the Queue is empty */
102601  sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
102602  sqlite3VdbeResolveLabel(v, addrBreak);
102603
102604end_of_recursive_query:
102605  sqlite3ExprListDelete(pParse->db, p->pOrderBy);
102606  p->pOrderBy = pOrderBy;
102607  p->pLimit = pLimit;
102608  p->pOffset = pOffset;
102609  return;
102610}
102611#endif /* SQLITE_OMIT_CTE */
102612
102613/* Forward references */
102614static int multiSelectOrderBy(
102615  Parse *pParse,        /* Parsing context */
102616  Select *p,            /* The right-most of SELECTs to be coded */
102617  SelectDest *pDest     /* What to do with query results */
102618);
102619
102620
102621/*
102622** This routine is called to process a compound query form from
102623** two or more separate queries using UNION, UNION ALL, EXCEPT, or
102624** INTERSECT
102625**
102626** "p" points to the right-most of the two queries.  the query on the
102627** left is p->pPrior.  The left query could also be a compound query
102628** in which case this routine will be called recursively.
102629**
102630** The results of the total query are to be written into a destination
102631** of type eDest with parameter iParm.
102632**
102633** Example 1:  Consider a three-way compound SQL statement.
102634**
102635**     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
102636**
102637** This statement is parsed up as follows:
102638**
102639**     SELECT c FROM t3
102640**      |
102641**      `----->  SELECT b FROM t2
102642**                |
102643**                `------>  SELECT a FROM t1
102644**
102645** The arrows in the diagram above represent the Select.pPrior pointer.
102646** So if this routine is called with p equal to the t3 query, then
102647** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
102648**
102649** Notice that because of the way SQLite parses compound SELECTs, the
102650** individual selects always group from left to right.
102651*/
102652static int multiSelect(
102653  Parse *pParse,        /* Parsing context */
102654  Select *p,            /* The right-most of SELECTs to be coded */
102655  SelectDest *pDest     /* What to do with query results */
102656){
102657  int rc = SQLITE_OK;   /* Success code from a subroutine */
102658  Select *pPrior;       /* Another SELECT immediately to our left */
102659  Vdbe *v;              /* Generate code to this VDBE */
102660  SelectDest dest;      /* Alternative data destination */
102661  Select *pDelete = 0;  /* Chain of simple selects to delete */
102662  sqlite3 *db;          /* Database connection */
102663#ifndef SQLITE_OMIT_EXPLAIN
102664  int iSub1 = 0;        /* EQP id of left-hand query */
102665  int iSub2 = 0;        /* EQP id of right-hand query */
102666#endif
102667
102668  /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
102669  ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
102670  */
102671  assert( p && p->pPrior );  /* Calling function guarantees this much */
102672  assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
102673  db = pParse->db;
102674  pPrior = p->pPrior;
102675  dest = *pDest;
102676  if( pPrior->pOrderBy ){
102677    sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
102678      selectOpName(p->op));
102679    rc = 1;
102680    goto multi_select_end;
102681  }
102682  if( pPrior->pLimit ){
102683    sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
102684      selectOpName(p->op));
102685    rc = 1;
102686    goto multi_select_end;
102687  }
102688
102689  v = sqlite3GetVdbe(pParse);
102690  assert( v!=0 );  /* The VDBE already created by calling function */
102691
102692  /* Create the destination temporary table if necessary
102693  */
102694  if( dest.eDest==SRT_EphemTab ){
102695    assert( p->pEList );
102696    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
102697    sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
102698    dest.eDest = SRT_Table;
102699  }
102700
102701  /* Make sure all SELECTs in the statement have the same number of elements
102702  ** in their result sets.
102703  */
102704  assert( p->pEList && pPrior->pEList );
102705  if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
102706    if( p->selFlags & SF_Values ){
102707      sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
102708    }else{
102709      sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
102710        " do not have the same number of result columns", selectOpName(p->op));
102711    }
102712    rc = 1;
102713    goto multi_select_end;
102714  }
102715
102716#ifndef SQLITE_OMIT_CTE
102717  if( p->selFlags & SF_Recursive ){
102718    generateWithRecursiveQuery(pParse, p, &dest);
102719  }else
102720#endif
102721
102722  /* Compound SELECTs that have an ORDER BY clause are handled separately.
102723  */
102724  if( p->pOrderBy ){
102725    return multiSelectOrderBy(pParse, p, pDest);
102726  }else
102727
102728  /* Generate code for the left and right SELECT statements.
102729  */
102730  switch( p->op ){
102731    case TK_ALL: {
102732      int addr = 0;
102733      int nLimit;
102734      assert( !pPrior->pLimit );
102735      pPrior->iLimit = p->iLimit;
102736      pPrior->iOffset = p->iOffset;
102737      pPrior->pLimit = p->pLimit;
102738      pPrior->pOffset = p->pOffset;
102739      explainSetInteger(iSub1, pParse->iNextSelectId);
102740      rc = sqlite3Select(pParse, pPrior, &dest);
102741      p->pLimit = 0;
102742      p->pOffset = 0;
102743      if( rc ){
102744        goto multi_select_end;
102745      }
102746      p->pPrior = 0;
102747      p->iLimit = pPrior->iLimit;
102748      p->iOffset = pPrior->iOffset;
102749      if( p->iLimit ){
102750        addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit); VdbeCoverage(v);
102751        VdbeComment((v, "Jump ahead if LIMIT reached"));
102752      }
102753      explainSetInteger(iSub2, pParse->iNextSelectId);
102754      rc = sqlite3Select(pParse, p, &dest);
102755      testcase( rc!=SQLITE_OK );
102756      pDelete = p->pPrior;
102757      p->pPrior = pPrior;
102758      p->nSelectRow += pPrior->nSelectRow;
102759      if( pPrior->pLimit
102760       && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
102761       && nLimit>0 && p->nSelectRow > (u64)nLimit
102762      ){
102763        p->nSelectRow = nLimit;
102764      }
102765      if( addr ){
102766        sqlite3VdbeJumpHere(v, addr);
102767      }
102768      break;
102769    }
102770    case TK_EXCEPT:
102771    case TK_UNION: {
102772      int unionTab;    /* Cursor number of the temporary table holding result */
102773      u8 op = 0;       /* One of the SRT_ operations to apply to self */
102774      int priorOp;     /* The SRT_ operation to apply to prior selects */
102775      Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
102776      int addr;
102777      SelectDest uniondest;
102778
102779      testcase( p->op==TK_EXCEPT );
102780      testcase( p->op==TK_UNION );
102781      priorOp = SRT_Union;
102782      if( dest.eDest==priorOp ){
102783        /* We can reuse a temporary table generated by a SELECT to our
102784        ** right.
102785        */
102786        assert( p->pLimit==0 );      /* Not allowed on leftward elements */
102787        assert( p->pOffset==0 );     /* Not allowed on leftward elements */
102788        unionTab = dest.iSDParm;
102789      }else{
102790        /* We will need to create our own temporary table to hold the
102791        ** intermediate results.
102792        */
102793        unionTab = pParse->nTab++;
102794        assert( p->pOrderBy==0 );
102795        addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
102796        assert( p->addrOpenEphm[0] == -1 );
102797        p->addrOpenEphm[0] = addr;
102798        findRightmost(p)->selFlags |= SF_UsesEphemeral;
102799        assert( p->pEList );
102800      }
102801
102802      /* Code the SELECT statements to our left
102803      */
102804      assert( !pPrior->pOrderBy );
102805      sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
102806      explainSetInteger(iSub1, pParse->iNextSelectId);
102807      rc = sqlite3Select(pParse, pPrior, &uniondest);
102808      if( rc ){
102809        goto multi_select_end;
102810      }
102811
102812      /* Code the current SELECT statement
102813      */
102814      if( p->op==TK_EXCEPT ){
102815        op = SRT_Except;
102816      }else{
102817        assert( p->op==TK_UNION );
102818        op = SRT_Union;
102819      }
102820      p->pPrior = 0;
102821      pLimit = p->pLimit;
102822      p->pLimit = 0;
102823      pOffset = p->pOffset;
102824      p->pOffset = 0;
102825      uniondest.eDest = op;
102826      explainSetInteger(iSub2, pParse->iNextSelectId);
102827      rc = sqlite3Select(pParse, p, &uniondest);
102828      testcase( rc!=SQLITE_OK );
102829      /* Query flattening in sqlite3Select() might refill p->pOrderBy.
102830      ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
102831      sqlite3ExprListDelete(db, p->pOrderBy);
102832      pDelete = p->pPrior;
102833      p->pPrior = pPrior;
102834      p->pOrderBy = 0;
102835      if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
102836      sqlite3ExprDelete(db, p->pLimit);
102837      p->pLimit = pLimit;
102838      p->pOffset = pOffset;
102839      p->iLimit = 0;
102840      p->iOffset = 0;
102841
102842      /* Convert the data in the temporary table into whatever form
102843      ** it is that we currently need.
102844      */
102845      assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
102846      if( dest.eDest!=priorOp ){
102847        int iCont, iBreak, iStart;
102848        assert( p->pEList );
102849        if( dest.eDest==SRT_Output ){
102850          Select *pFirst = p;
102851          while( pFirst->pPrior ) pFirst = pFirst->pPrior;
102852          generateColumnNames(pParse, 0, pFirst->pEList);
102853        }
102854        iBreak = sqlite3VdbeMakeLabel(v);
102855        iCont = sqlite3VdbeMakeLabel(v);
102856        computeLimitRegisters(pParse, p, iBreak);
102857        sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
102858        iStart = sqlite3VdbeCurrentAddr(v);
102859        selectInnerLoop(pParse, p, p->pEList, unionTab,
102860                        0, 0, &dest, iCont, iBreak);
102861        sqlite3VdbeResolveLabel(v, iCont);
102862        sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
102863        sqlite3VdbeResolveLabel(v, iBreak);
102864        sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
102865      }
102866      break;
102867    }
102868    default: assert( p->op==TK_INTERSECT ); {
102869      int tab1, tab2;
102870      int iCont, iBreak, iStart;
102871      Expr *pLimit, *pOffset;
102872      int addr;
102873      SelectDest intersectdest;
102874      int r1;
102875
102876      /* INTERSECT is different from the others since it requires
102877      ** two temporary tables.  Hence it has its own case.  Begin
102878      ** by allocating the tables we will need.
102879      */
102880      tab1 = pParse->nTab++;
102881      tab2 = pParse->nTab++;
102882      assert( p->pOrderBy==0 );
102883
102884      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
102885      assert( p->addrOpenEphm[0] == -1 );
102886      p->addrOpenEphm[0] = addr;
102887      findRightmost(p)->selFlags |= SF_UsesEphemeral;
102888      assert( p->pEList );
102889
102890      /* Code the SELECTs to our left into temporary table "tab1".
102891      */
102892      sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
102893      explainSetInteger(iSub1, pParse->iNextSelectId);
102894      rc = sqlite3Select(pParse, pPrior, &intersectdest);
102895      if( rc ){
102896        goto multi_select_end;
102897      }
102898
102899      /* Code the current SELECT into temporary table "tab2"
102900      */
102901      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
102902      assert( p->addrOpenEphm[1] == -1 );
102903      p->addrOpenEphm[1] = addr;
102904      p->pPrior = 0;
102905      pLimit = p->pLimit;
102906      p->pLimit = 0;
102907      pOffset = p->pOffset;
102908      p->pOffset = 0;
102909      intersectdest.iSDParm = tab2;
102910      explainSetInteger(iSub2, pParse->iNextSelectId);
102911      rc = sqlite3Select(pParse, p, &intersectdest);
102912      testcase( rc!=SQLITE_OK );
102913      pDelete = p->pPrior;
102914      p->pPrior = pPrior;
102915      if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
102916      sqlite3ExprDelete(db, p->pLimit);
102917      p->pLimit = pLimit;
102918      p->pOffset = pOffset;
102919
102920      /* Generate code to take the intersection of the two temporary
102921      ** tables.
102922      */
102923      assert( p->pEList );
102924      if( dest.eDest==SRT_Output ){
102925        Select *pFirst = p;
102926        while( pFirst->pPrior ) pFirst = pFirst->pPrior;
102927        generateColumnNames(pParse, 0, pFirst->pEList);
102928      }
102929      iBreak = sqlite3VdbeMakeLabel(v);
102930      iCont = sqlite3VdbeMakeLabel(v);
102931      computeLimitRegisters(pParse, p, iBreak);
102932      sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
102933      r1 = sqlite3GetTempReg(pParse);
102934      iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
102935      sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
102936      sqlite3ReleaseTempReg(pParse, r1);
102937      selectInnerLoop(pParse, p, p->pEList, tab1,
102938                      0, 0, &dest, iCont, iBreak);
102939      sqlite3VdbeResolveLabel(v, iCont);
102940      sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
102941      sqlite3VdbeResolveLabel(v, iBreak);
102942      sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
102943      sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
102944      break;
102945    }
102946  }
102947
102948  explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
102949
102950  /* Compute collating sequences used by
102951  ** temporary tables needed to implement the compound select.
102952  ** Attach the KeyInfo structure to all temporary tables.
102953  **
102954  ** This section is run by the right-most SELECT statement only.
102955  ** SELECT statements to the left always skip this part.  The right-most
102956  ** SELECT might also skip this part if it has no ORDER BY clause and
102957  ** no temp tables are required.
102958  */
102959  if( p->selFlags & SF_UsesEphemeral ){
102960    int i;                        /* Loop counter */
102961    KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
102962    Select *pLoop;                /* For looping through SELECT statements */
102963    CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
102964    int nCol;                     /* Number of columns in result set */
102965
102966    assert( p->pNext==0 );
102967    nCol = p->pEList->nExpr;
102968    pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
102969    if( !pKeyInfo ){
102970      rc = SQLITE_NOMEM;
102971      goto multi_select_end;
102972    }
102973    for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
102974      *apColl = multiSelectCollSeq(pParse, p, i);
102975      if( 0==*apColl ){
102976        *apColl = db->pDfltColl;
102977      }
102978    }
102979
102980    for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
102981      for(i=0; i<2; i++){
102982        int addr = pLoop->addrOpenEphm[i];
102983        if( addr<0 ){
102984          /* If [0] is unused then [1] is also unused.  So we can
102985          ** always safely abort as soon as the first unused slot is found */
102986          assert( pLoop->addrOpenEphm[1]<0 );
102987          break;
102988        }
102989        sqlite3VdbeChangeP2(v, addr, nCol);
102990        sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
102991                            P4_KEYINFO);
102992        pLoop->addrOpenEphm[i] = -1;
102993      }
102994    }
102995    sqlite3KeyInfoUnref(pKeyInfo);
102996  }
102997
102998multi_select_end:
102999  pDest->iSdst = dest.iSdst;
103000  pDest->nSdst = dest.nSdst;
103001  sqlite3SelectDelete(db, pDelete);
103002  return rc;
103003}
103004#endif /* SQLITE_OMIT_COMPOUND_SELECT */
103005
103006/*
103007** Code an output subroutine for a coroutine implementation of a
103008** SELECT statment.
103009**
103010** The data to be output is contained in pIn->iSdst.  There are
103011** pIn->nSdst columns to be output.  pDest is where the output should
103012** be sent.
103013**
103014** regReturn is the number of the register holding the subroutine
103015** return address.
103016**
103017** If regPrev>0 then it is the first register in a vector that
103018** records the previous output.  mem[regPrev] is a flag that is false
103019** if there has been no previous output.  If regPrev>0 then code is
103020** generated to suppress duplicates.  pKeyInfo is used for comparing
103021** keys.
103022**
103023** If the LIMIT found in p->iLimit is reached, jump immediately to
103024** iBreak.
103025*/
103026static int generateOutputSubroutine(
103027  Parse *pParse,          /* Parsing context */
103028  Select *p,              /* The SELECT statement */
103029  SelectDest *pIn,        /* Coroutine supplying data */
103030  SelectDest *pDest,      /* Where to send the data */
103031  int regReturn,          /* The return address register */
103032  int regPrev,            /* Previous result register.  No uniqueness if 0 */
103033  KeyInfo *pKeyInfo,      /* For comparing with previous entry */
103034  int iBreak              /* Jump here if we hit the LIMIT */
103035){
103036  Vdbe *v = pParse->pVdbe;
103037  int iContinue;
103038  int addr;
103039
103040  addr = sqlite3VdbeCurrentAddr(v);
103041  iContinue = sqlite3VdbeMakeLabel(v);
103042
103043  /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
103044  */
103045  if( regPrev ){
103046    int j1, j2;
103047    j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
103048    j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
103049                              (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
103050    sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2); VdbeCoverage(v);
103051    sqlite3VdbeJumpHere(v, j1);
103052    sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
103053    sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
103054  }
103055  if( pParse->db->mallocFailed ) return 0;
103056
103057  /* Suppress the first OFFSET entries if there is an OFFSET clause
103058  */
103059  codeOffset(v, p->iOffset, iContinue);
103060
103061  switch( pDest->eDest ){
103062    /* Store the result as data using a unique key.
103063    */
103064    case SRT_Table:
103065    case SRT_EphemTab: {
103066      int r1 = sqlite3GetTempReg(pParse);
103067      int r2 = sqlite3GetTempReg(pParse);
103068      testcase( pDest->eDest==SRT_Table );
103069      testcase( pDest->eDest==SRT_EphemTab );
103070      sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
103071      sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
103072      sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
103073      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
103074      sqlite3ReleaseTempReg(pParse, r2);
103075      sqlite3ReleaseTempReg(pParse, r1);
103076      break;
103077    }
103078
103079#ifndef SQLITE_OMIT_SUBQUERY
103080    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
103081    ** then there should be a single item on the stack.  Write this
103082    ** item into the set table with bogus data.
103083    */
103084    case SRT_Set: {
103085      int r1;
103086      assert( pIn->nSdst==1 );
103087      pDest->affSdst =
103088         sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
103089      r1 = sqlite3GetTempReg(pParse);
103090      sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
103091      sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
103092      sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
103093      sqlite3ReleaseTempReg(pParse, r1);
103094      break;
103095    }
103096
103097#if 0  /* Never occurs on an ORDER BY query */
103098    /* If any row exist in the result set, record that fact and abort.
103099    */
103100    case SRT_Exists: {
103101      sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
103102      /* The LIMIT clause will terminate the loop for us */
103103      break;
103104    }
103105#endif
103106
103107    /* If this is a scalar select that is part of an expression, then
103108    ** store the results in the appropriate memory cell and break out
103109    ** of the scan loop.
103110    */
103111    case SRT_Mem: {
103112      assert( pIn->nSdst==1 );
103113      sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
103114      /* The LIMIT clause will jump out of the loop for us */
103115      break;
103116    }
103117#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
103118
103119    /* The results are stored in a sequence of registers
103120    ** starting at pDest->iSdst.  Then the co-routine yields.
103121    */
103122    case SRT_Coroutine: {
103123      if( pDest->iSdst==0 ){
103124        pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
103125        pDest->nSdst = pIn->nSdst;
103126      }
103127      sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst);
103128      sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
103129      break;
103130    }
103131
103132    /* If none of the above, then the result destination must be
103133    ** SRT_Output.  This routine is never called with any other
103134    ** destination other than the ones handled above or SRT_Output.
103135    **
103136    ** For SRT_Output, results are stored in a sequence of registers.
103137    ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
103138    ** return the next row of result.
103139    */
103140    default: {
103141      assert( pDest->eDest==SRT_Output );
103142      sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
103143      sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
103144      break;
103145    }
103146  }
103147
103148  /* Jump to the end of the loop if the LIMIT is reached.
103149  */
103150  if( p->iLimit ){
103151    sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); VdbeCoverage(v);
103152  }
103153
103154  /* Generate the subroutine return
103155  */
103156  sqlite3VdbeResolveLabel(v, iContinue);
103157  sqlite3VdbeAddOp1(v, OP_Return, regReturn);
103158
103159  return addr;
103160}
103161
103162/*
103163** Alternative compound select code generator for cases when there
103164** is an ORDER BY clause.
103165**
103166** We assume a query of the following form:
103167**
103168**      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
103169**
103170** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
103171** is to code both <selectA> and <selectB> with the ORDER BY clause as
103172** co-routines.  Then run the co-routines in parallel and merge the results
103173** into the output.  In addition to the two coroutines (called selectA and
103174** selectB) there are 7 subroutines:
103175**
103176**    outA:    Move the output of the selectA coroutine into the output
103177**             of the compound query.
103178**
103179**    outB:    Move the output of the selectB coroutine into the output
103180**             of the compound query.  (Only generated for UNION and
103181**             UNION ALL.  EXCEPT and INSERTSECT never output a row that
103182**             appears only in B.)
103183**
103184**    AltB:    Called when there is data from both coroutines and A<B.
103185**
103186**    AeqB:    Called when there is data from both coroutines and A==B.
103187**
103188**    AgtB:    Called when there is data from both coroutines and A>B.
103189**
103190**    EofA:    Called when data is exhausted from selectA.
103191**
103192**    EofB:    Called when data is exhausted from selectB.
103193**
103194** The implementation of the latter five subroutines depend on which
103195** <operator> is used:
103196**
103197**
103198**             UNION ALL         UNION            EXCEPT          INTERSECT
103199**          -------------  -----------------  --------------  -----------------
103200**   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
103201**
103202**   AeqB:   outA, nextA         nextA             nextA         outA, nextA
103203**
103204**   AgtB:   outB, nextB      outB, nextB          nextB            nextB
103205**
103206**   EofA:   outB, nextB      outB, nextB          halt             halt
103207**
103208**   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
103209**
103210** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
103211** causes an immediate jump to EofA and an EOF on B following nextB causes
103212** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
103213** following nextX causes a jump to the end of the select processing.
103214**
103215** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
103216** within the output subroutine.  The regPrev register set holds the previously
103217** output value.  A comparison is made against this value and the output
103218** is skipped if the next results would be the same as the previous.
103219**
103220** The implementation plan is to implement the two coroutines and seven
103221** subroutines first, then put the control logic at the bottom.  Like this:
103222**
103223**          goto Init
103224**     coA: coroutine for left query (A)
103225**     coB: coroutine for right query (B)
103226**    outA: output one row of A
103227**    outB: output one row of B (UNION and UNION ALL only)
103228**    EofA: ...
103229**    EofB: ...
103230**    AltB: ...
103231**    AeqB: ...
103232**    AgtB: ...
103233**    Init: initialize coroutine registers
103234**          yield coA
103235**          if eof(A) goto EofA
103236**          yield coB
103237**          if eof(B) goto EofB
103238**    Cmpr: Compare A, B
103239**          Jump AltB, AeqB, AgtB
103240**     End: ...
103241**
103242** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
103243** actually called using Gosub and they do not Return.  EofA and EofB loop
103244** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
103245** and AgtB jump to either L2 or to one of EofA or EofB.
103246*/
103247#ifndef SQLITE_OMIT_COMPOUND_SELECT
103248static int multiSelectOrderBy(
103249  Parse *pParse,        /* Parsing context */
103250  Select *p,            /* The right-most of SELECTs to be coded */
103251  SelectDest *pDest     /* What to do with query results */
103252){
103253  int i, j;             /* Loop counters */
103254  Select *pPrior;       /* Another SELECT immediately to our left */
103255  Vdbe *v;              /* Generate code to this VDBE */
103256  SelectDest destA;     /* Destination for coroutine A */
103257  SelectDest destB;     /* Destination for coroutine B */
103258  int regAddrA;         /* Address register for select-A coroutine */
103259  int regAddrB;         /* Address register for select-B coroutine */
103260  int addrSelectA;      /* Address of the select-A coroutine */
103261  int addrSelectB;      /* Address of the select-B coroutine */
103262  int regOutA;          /* Address register for the output-A subroutine */
103263  int regOutB;          /* Address register for the output-B subroutine */
103264  int addrOutA;         /* Address of the output-A subroutine */
103265  int addrOutB = 0;     /* Address of the output-B subroutine */
103266  int addrEofA;         /* Address of the select-A-exhausted subroutine */
103267  int addrEofA_noB;     /* Alternate addrEofA if B is uninitialized */
103268  int addrEofB;         /* Address of the select-B-exhausted subroutine */
103269  int addrAltB;         /* Address of the A<B subroutine */
103270  int addrAeqB;         /* Address of the A==B subroutine */
103271  int addrAgtB;         /* Address of the A>B subroutine */
103272  int regLimitA;        /* Limit register for select-A */
103273  int regLimitB;        /* Limit register for select-A */
103274  int regPrev;          /* A range of registers to hold previous output */
103275  int savedLimit;       /* Saved value of p->iLimit */
103276  int savedOffset;      /* Saved value of p->iOffset */
103277  int labelCmpr;        /* Label for the start of the merge algorithm */
103278  int labelEnd;         /* Label for the end of the overall SELECT stmt */
103279  int j1;               /* Jump instructions that get retargetted */
103280  int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
103281  KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
103282  KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
103283  sqlite3 *db;          /* Database connection */
103284  ExprList *pOrderBy;   /* The ORDER BY clause */
103285  int nOrderBy;         /* Number of terms in the ORDER BY clause */
103286  int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
103287#ifndef SQLITE_OMIT_EXPLAIN
103288  int iSub1;            /* EQP id of left-hand query */
103289  int iSub2;            /* EQP id of right-hand query */
103290#endif
103291
103292  assert( p->pOrderBy!=0 );
103293  assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
103294  db = pParse->db;
103295  v = pParse->pVdbe;
103296  assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
103297  labelEnd = sqlite3VdbeMakeLabel(v);
103298  labelCmpr = sqlite3VdbeMakeLabel(v);
103299
103300
103301  /* Patch up the ORDER BY clause
103302  */
103303  op = p->op;
103304  pPrior = p->pPrior;
103305  assert( pPrior->pOrderBy==0 );
103306  pOrderBy = p->pOrderBy;
103307  assert( pOrderBy );
103308  nOrderBy = pOrderBy->nExpr;
103309
103310  /* For operators other than UNION ALL we have to make sure that
103311  ** the ORDER BY clause covers every term of the result set.  Add
103312  ** terms to the ORDER BY clause as necessary.
103313  */
103314  if( op!=TK_ALL ){
103315    for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
103316      struct ExprList_item *pItem;
103317      for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
103318        assert( pItem->u.x.iOrderByCol>0 );
103319        if( pItem->u.x.iOrderByCol==i ) break;
103320      }
103321      if( j==nOrderBy ){
103322        Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
103323        if( pNew==0 ) return SQLITE_NOMEM;
103324        pNew->flags |= EP_IntValue;
103325        pNew->u.iValue = i;
103326        pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
103327        if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
103328      }
103329    }
103330  }
103331
103332  /* Compute the comparison permutation and keyinfo that is used with
103333  ** the permutation used to determine if the next
103334  ** row of results comes from selectA or selectB.  Also add explicit
103335  ** collations to the ORDER BY clause terms so that when the subqueries
103336  ** to the right and the left are evaluated, they use the correct
103337  ** collation.
103338  */
103339  aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
103340  if( aPermute ){
103341    struct ExprList_item *pItem;
103342    for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
103343      assert( pItem->u.x.iOrderByCol>0
103344          && pItem->u.x.iOrderByCol<=p->pEList->nExpr );
103345      aPermute[i] = pItem->u.x.iOrderByCol - 1;
103346    }
103347    pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
103348  }else{
103349    pKeyMerge = 0;
103350  }
103351
103352  /* Reattach the ORDER BY clause to the query.
103353  */
103354  p->pOrderBy = pOrderBy;
103355  pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
103356
103357  /* Allocate a range of temporary registers and the KeyInfo needed
103358  ** for the logic that removes duplicate result rows when the
103359  ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
103360  */
103361  if( op==TK_ALL ){
103362    regPrev = 0;
103363  }else{
103364    int nExpr = p->pEList->nExpr;
103365    assert( nOrderBy>=nExpr || db->mallocFailed );
103366    regPrev = pParse->nMem+1;
103367    pParse->nMem += nExpr+1;
103368    sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
103369    pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
103370    if( pKeyDup ){
103371      assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
103372      for(i=0; i<nExpr; i++){
103373        pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
103374        pKeyDup->aSortOrder[i] = 0;
103375      }
103376    }
103377  }
103378
103379  /* Separate the left and the right query from one another
103380  */
103381  p->pPrior = 0;
103382  pPrior->pNext = 0;
103383  sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
103384  if( pPrior->pPrior==0 ){
103385    sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
103386  }
103387
103388  /* Compute the limit registers */
103389  computeLimitRegisters(pParse, p, labelEnd);
103390  if( p->iLimit && op==TK_ALL ){
103391    regLimitA = ++pParse->nMem;
103392    regLimitB = ++pParse->nMem;
103393    sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
103394                                  regLimitA);
103395    sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
103396  }else{
103397    regLimitA = regLimitB = 0;
103398  }
103399  sqlite3ExprDelete(db, p->pLimit);
103400  p->pLimit = 0;
103401  sqlite3ExprDelete(db, p->pOffset);
103402  p->pOffset = 0;
103403
103404  regAddrA = ++pParse->nMem;
103405  regAddrB = ++pParse->nMem;
103406  regOutA = ++pParse->nMem;
103407  regOutB = ++pParse->nMem;
103408  sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
103409  sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
103410
103411  /* Generate a coroutine to evaluate the SELECT statement to the
103412  ** left of the compound operator - the "A" select.
103413  */
103414  addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
103415  j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
103416  VdbeComment((v, "left SELECT"));
103417  pPrior->iLimit = regLimitA;
103418  explainSetInteger(iSub1, pParse->iNextSelectId);
103419  sqlite3Select(pParse, pPrior, &destA);
103420  sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrA);
103421  sqlite3VdbeJumpHere(v, j1);
103422
103423  /* Generate a coroutine to evaluate the SELECT statement on
103424  ** the right - the "B" select
103425  */
103426  addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
103427  j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
103428  VdbeComment((v, "right SELECT"));
103429  savedLimit = p->iLimit;
103430  savedOffset = p->iOffset;
103431  p->iLimit = regLimitB;
103432  p->iOffset = 0;
103433  explainSetInteger(iSub2, pParse->iNextSelectId);
103434  sqlite3Select(pParse, p, &destB);
103435  p->iLimit = savedLimit;
103436  p->iOffset = savedOffset;
103437  sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrB);
103438
103439  /* Generate a subroutine that outputs the current row of the A
103440  ** select as the next output row of the compound select.
103441  */
103442  VdbeNoopComment((v, "Output routine for A"));
103443  addrOutA = generateOutputSubroutine(pParse,
103444                 p, &destA, pDest, regOutA,
103445                 regPrev, pKeyDup, labelEnd);
103446
103447  /* Generate a subroutine that outputs the current row of the B
103448  ** select as the next output row of the compound select.
103449  */
103450  if( op==TK_ALL || op==TK_UNION ){
103451    VdbeNoopComment((v, "Output routine for B"));
103452    addrOutB = generateOutputSubroutine(pParse,
103453                 p, &destB, pDest, regOutB,
103454                 regPrev, pKeyDup, labelEnd);
103455  }
103456  sqlite3KeyInfoUnref(pKeyDup);
103457
103458  /* Generate a subroutine to run when the results from select A
103459  ** are exhausted and only data in select B remains.
103460  */
103461  if( op==TK_EXCEPT || op==TK_INTERSECT ){
103462    addrEofA_noB = addrEofA = labelEnd;
103463  }else{
103464    VdbeNoopComment((v, "eof-A subroutine"));
103465    addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
103466    addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
103467                                     VdbeCoverage(v);
103468    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
103469    p->nSelectRow += pPrior->nSelectRow;
103470  }
103471
103472  /* Generate a subroutine to run when the results from select B
103473  ** are exhausted and only data in select A remains.
103474  */
103475  if( op==TK_INTERSECT ){
103476    addrEofB = addrEofA;
103477    if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
103478  }else{
103479    VdbeNoopComment((v, "eof-B subroutine"));
103480    addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
103481    sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
103482    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
103483  }
103484
103485  /* Generate code to handle the case of A<B
103486  */
103487  VdbeNoopComment((v, "A-lt-B subroutine"));
103488  addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
103489  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
103490  sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
103491
103492  /* Generate code to handle the case of A==B
103493  */
103494  if( op==TK_ALL ){
103495    addrAeqB = addrAltB;
103496  }else if( op==TK_INTERSECT ){
103497    addrAeqB = addrAltB;
103498    addrAltB++;
103499  }else{
103500    VdbeNoopComment((v, "A-eq-B subroutine"));
103501    addrAeqB =
103502    sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
103503    sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
103504  }
103505
103506  /* Generate code to handle the case of A>B
103507  */
103508  VdbeNoopComment((v, "A-gt-B subroutine"));
103509  addrAgtB = sqlite3VdbeCurrentAddr(v);
103510  if( op==TK_ALL || op==TK_UNION ){
103511    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
103512  }
103513  sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
103514  sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
103515
103516  /* This code runs once to initialize everything.
103517  */
103518  sqlite3VdbeJumpHere(v, j1);
103519  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
103520  sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
103521
103522  /* Implement the main merge loop
103523  */
103524  sqlite3VdbeResolveLabel(v, labelCmpr);
103525  sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
103526  sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
103527                         (char*)pKeyMerge, P4_KEYINFO);
103528  sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
103529  sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
103530
103531  /* Jump to the this point in order to terminate the query.
103532  */
103533  sqlite3VdbeResolveLabel(v, labelEnd);
103534
103535  /* Set the number of output columns
103536  */
103537  if( pDest->eDest==SRT_Output ){
103538    Select *pFirst = pPrior;
103539    while( pFirst->pPrior ) pFirst = pFirst->pPrior;
103540    generateColumnNames(pParse, 0, pFirst->pEList);
103541  }
103542
103543  /* Reassembly the compound query so that it will be freed correctly
103544  ** by the calling function */
103545  if( p->pPrior ){
103546    sqlite3SelectDelete(db, p->pPrior);
103547  }
103548  p->pPrior = pPrior;
103549  pPrior->pNext = p;
103550
103551  /*** TBD:  Insert subroutine calls to close cursors on incomplete
103552  **** subqueries ****/
103553  explainComposite(pParse, p->op, iSub1, iSub2, 0);
103554  return SQLITE_OK;
103555}
103556#endif
103557
103558#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
103559/* Forward Declarations */
103560static void substExprList(sqlite3*, ExprList*, int, ExprList*);
103561static void substSelect(sqlite3*, Select *, int, ExprList *);
103562
103563/*
103564** Scan through the expression pExpr.  Replace every reference to
103565** a column in table number iTable with a copy of the iColumn-th
103566** entry in pEList.  (But leave references to the ROWID column
103567** unchanged.)
103568**
103569** This routine is part of the flattening procedure.  A subquery
103570** whose result set is defined by pEList appears as entry in the
103571** FROM clause of a SELECT such that the VDBE cursor assigned to that
103572** FORM clause entry is iTable.  This routine make the necessary
103573** changes to pExpr so that it refers directly to the source table
103574** of the subquery rather the result set of the subquery.
103575*/
103576static Expr *substExpr(
103577  sqlite3 *db,        /* Report malloc errors to this connection */
103578  Expr *pExpr,        /* Expr in which substitution occurs */
103579  int iTable,         /* Table to be substituted */
103580  ExprList *pEList    /* Substitute expressions */
103581){
103582  if( pExpr==0 ) return 0;
103583  if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
103584    if( pExpr->iColumn<0 ){
103585      pExpr->op = TK_NULL;
103586    }else{
103587      Expr *pNew;
103588      assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
103589      assert( pExpr->pLeft==0 && pExpr->pRight==0 );
103590      pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
103591      sqlite3ExprDelete(db, pExpr);
103592      pExpr = pNew;
103593    }
103594  }else{
103595    pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
103596    pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
103597    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
103598      substSelect(db, pExpr->x.pSelect, iTable, pEList);
103599    }else{
103600      substExprList(db, pExpr->x.pList, iTable, pEList);
103601    }
103602  }
103603  return pExpr;
103604}
103605static void substExprList(
103606  sqlite3 *db,         /* Report malloc errors here */
103607  ExprList *pList,     /* List to scan and in which to make substitutes */
103608  int iTable,          /* Table to be substituted */
103609  ExprList *pEList     /* Substitute values */
103610){
103611  int i;
103612  if( pList==0 ) return;
103613  for(i=0; i<pList->nExpr; i++){
103614    pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
103615  }
103616}
103617static void substSelect(
103618  sqlite3 *db,         /* Report malloc errors here */
103619  Select *p,           /* SELECT statement in which to make substitutions */
103620  int iTable,          /* Table to be replaced */
103621  ExprList *pEList     /* Substitute values */
103622){
103623  SrcList *pSrc;
103624  struct SrcList_item *pItem;
103625  int i;
103626  if( !p ) return;
103627  substExprList(db, p->pEList, iTable, pEList);
103628  substExprList(db, p->pGroupBy, iTable, pEList);
103629  substExprList(db, p->pOrderBy, iTable, pEList);
103630  p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
103631  p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
103632  substSelect(db, p->pPrior, iTable, pEList);
103633  pSrc = p->pSrc;
103634  assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
103635  if( ALWAYS(pSrc) ){
103636    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
103637      substSelect(db, pItem->pSelect, iTable, pEList);
103638    }
103639  }
103640}
103641#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
103642
103643#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
103644/*
103645** This routine attempts to flatten subqueries as a performance optimization.
103646** This routine returns 1 if it makes changes and 0 if no flattening occurs.
103647**
103648** To understand the concept of flattening, consider the following
103649** query:
103650**
103651**     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
103652**
103653** The default way of implementing this query is to execute the
103654** subquery first and store the results in a temporary table, then
103655** run the outer query on that temporary table.  This requires two
103656** passes over the data.  Furthermore, because the temporary table
103657** has no indices, the WHERE clause on the outer query cannot be
103658** optimized.
103659**
103660** This routine attempts to rewrite queries such as the above into
103661** a single flat select, like this:
103662**
103663**     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
103664**
103665** The code generated for this simpification gives the same result
103666** but only has to scan the data once.  And because indices might
103667** exist on the table t1, a complete scan of the data might be
103668** avoided.
103669**
103670** Flattening is only attempted if all of the following are true:
103671**
103672**   (1)  The subquery and the outer query do not both use aggregates.
103673**
103674**   (2)  The subquery is not an aggregate or the outer query is not a join.
103675**
103676**   (3)  The subquery is not the right operand of a left outer join
103677**        (Originally ticket #306.  Strengthened by ticket #3300)
103678**
103679**   (4)  The subquery is not DISTINCT.
103680**
103681**  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
103682**        sub-queries that were excluded from this optimization. Restriction
103683**        (4) has since been expanded to exclude all DISTINCT subqueries.
103684**
103685**   (6)  The subquery does not use aggregates or the outer query is not
103686**        DISTINCT.
103687**
103688**   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
103689**        A FROM clause, consider adding a FROM close with the special
103690**        table sqlite_once that consists of a single row containing a
103691**        single NULL.
103692**
103693**   (8)  The subquery does not use LIMIT or the outer query is not a join.
103694**
103695**   (9)  The subquery does not use LIMIT or the outer query does not use
103696**        aggregates.
103697**
103698**  (10)  The subquery does not use aggregates or the outer query does not
103699**        use LIMIT.
103700**
103701**  (11)  The subquery and the outer query do not both have ORDER BY clauses.
103702**
103703**  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
103704**        a separate restriction deriving from ticket #350.
103705**
103706**  (13)  The subquery and outer query do not both use LIMIT.
103707**
103708**  (14)  The subquery does not use OFFSET.
103709**
103710**  (15)  The outer query is not part of a compound select or the
103711**        subquery does not have a LIMIT clause.
103712**        (See ticket #2339 and ticket [02a8e81d44]).
103713**
103714**  (16)  The outer query is not an aggregate or the subquery does
103715**        not contain ORDER BY.  (Ticket #2942)  This used to not matter
103716**        until we introduced the group_concat() function.
103717**
103718**  (17)  The sub-query is not a compound select, or it is a UNION ALL
103719**        compound clause made up entirely of non-aggregate queries, and
103720**        the parent query:
103721**
103722**          * is not itself part of a compound select,
103723**          * is not an aggregate or DISTINCT query, and
103724**          * is not a join
103725**
103726**        The parent and sub-query may contain WHERE clauses. Subject to
103727**        rules (11), (13) and (14), they may also contain ORDER BY,
103728**        LIMIT and OFFSET clauses.  The subquery cannot use any compound
103729**        operator other than UNION ALL because all the other compound
103730**        operators have an implied DISTINCT which is disallowed by
103731**        restriction (4).
103732**
103733**        Also, each component of the sub-query must return the same number
103734**        of result columns. This is actually a requirement for any compound
103735**        SELECT statement, but all the code here does is make sure that no
103736**        such (illegal) sub-query is flattened. The caller will detect the
103737**        syntax error and return a detailed message.
103738**
103739**  (18)  If the sub-query is a compound select, then all terms of the
103740**        ORDER by clause of the parent must be simple references to
103741**        columns of the sub-query.
103742**
103743**  (19)  The subquery does not use LIMIT or the outer query does not
103744**        have a WHERE clause.
103745**
103746**  (20)  If the sub-query is a compound select, then it must not use
103747**        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
103748**        somewhat by saying that the terms of the ORDER BY clause must
103749**        appear as unmodified result columns in the outer query.  But we
103750**        have other optimizations in mind to deal with that case.
103751**
103752**  (21)  The subquery does not use LIMIT or the outer query is not
103753**        DISTINCT.  (See ticket [752e1646fc]).
103754**
103755**  (22)  The subquery is not a recursive CTE.
103756**
103757**  (23)  The parent is not a recursive CTE, or the sub-query is not a
103758**        compound query. This restriction is because transforming the
103759**        parent to a compound query confuses the code that handles
103760**        recursive queries in multiSelect().
103761**
103762**
103763** In this routine, the "p" parameter is a pointer to the outer query.
103764** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
103765** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
103766**
103767** If flattening is not attempted, this routine is a no-op and returns 0.
103768** If flattening is attempted this routine returns 1.
103769**
103770** All of the expression analysis must occur on both the outer query and
103771** the subquery before this routine runs.
103772*/
103773static int flattenSubquery(
103774  Parse *pParse,       /* Parsing context */
103775  Select *p,           /* The parent or outer SELECT statement */
103776  int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
103777  int isAgg,           /* True if outer SELECT uses aggregate functions */
103778  int subqueryIsAgg    /* True if the subquery uses aggregate functions */
103779){
103780  const char *zSavedAuthContext = pParse->zAuthContext;
103781  Select *pParent;
103782  Select *pSub;       /* The inner query or "subquery" */
103783  Select *pSub1;      /* Pointer to the rightmost select in sub-query */
103784  SrcList *pSrc;      /* The FROM clause of the outer query */
103785  SrcList *pSubSrc;   /* The FROM clause of the subquery */
103786  ExprList *pList;    /* The result set of the outer query */
103787  int iParent;        /* VDBE cursor number of the pSub result set temp table */
103788  int i;              /* Loop counter */
103789  Expr *pWhere;                    /* The WHERE clause */
103790  struct SrcList_item *pSubitem;   /* The subquery */
103791  sqlite3 *db = pParse->db;
103792
103793  /* Check to see if flattening is permitted.  Return 0 if not.
103794  */
103795  assert( p!=0 );
103796  assert( p->pPrior==0 );  /* Unable to flatten compound queries */
103797  if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
103798  pSrc = p->pSrc;
103799  assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
103800  pSubitem = &pSrc->a[iFrom];
103801  iParent = pSubitem->iCursor;
103802  pSub = pSubitem->pSelect;
103803  assert( pSub!=0 );
103804  if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
103805  if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
103806  pSubSrc = pSub->pSrc;
103807  assert( pSubSrc );
103808  /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
103809  ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
103810  ** because they could be computed at compile-time.  But when LIMIT and OFFSET
103811  ** became arbitrary expressions, we were forced to add restrictions (13)
103812  ** and (14). */
103813  if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
103814  if( pSub->pOffset ) return 0;                          /* Restriction (14) */
103815  if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
103816    return 0;                                            /* Restriction (15) */
103817  }
103818  if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
103819  if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
103820  if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
103821     return 0;         /* Restrictions (8)(9) */
103822  }
103823  if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
103824     return 0;         /* Restriction (6)  */
103825  }
103826  if( p->pOrderBy && pSub->pOrderBy ){
103827     return 0;                                           /* Restriction (11) */
103828  }
103829  if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
103830  if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
103831  if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
103832     return 0;         /* Restriction (21) */
103833  }
103834  if( pSub->selFlags & SF_Recursive ) return 0;          /* Restriction (22)  */
103835  if( (p->selFlags & SF_Recursive) && pSub->pPrior ) return 0;       /* (23)  */
103836
103837  /* OBSOLETE COMMENT 1:
103838  ** Restriction 3:  If the subquery is a join, make sure the subquery is
103839  ** not used as the right operand of an outer join.  Examples of why this
103840  ** is not allowed:
103841  **
103842  **         t1 LEFT OUTER JOIN (t2 JOIN t3)
103843  **
103844  ** If we flatten the above, we would get
103845  **
103846  **         (t1 LEFT OUTER JOIN t2) JOIN t3
103847  **
103848  ** which is not at all the same thing.
103849  **
103850  ** OBSOLETE COMMENT 2:
103851  ** Restriction 12:  If the subquery is the right operand of a left outer
103852  ** join, make sure the subquery has no WHERE clause.
103853  ** An examples of why this is not allowed:
103854  **
103855  **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
103856  **
103857  ** If we flatten the above, we would get
103858  **
103859  **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
103860  **
103861  ** But the t2.x>0 test will always fail on a NULL row of t2, which
103862  ** effectively converts the OUTER JOIN into an INNER JOIN.
103863  **
103864  ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
103865  ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
103866  ** is fraught with danger.  Best to avoid the whole thing.  If the
103867  ** subquery is the right term of a LEFT JOIN, then do not flatten.
103868  */
103869  if( (pSubitem->jointype & JT_OUTER)!=0 ){
103870    return 0;
103871  }
103872
103873  /* Restriction 17: If the sub-query is a compound SELECT, then it must
103874  ** use only the UNION ALL operator. And none of the simple select queries
103875  ** that make up the compound SELECT are allowed to be aggregate or distinct
103876  ** queries.
103877  */
103878  if( pSub->pPrior ){
103879    if( pSub->pOrderBy ){
103880      return 0;  /* Restriction 20 */
103881    }
103882    if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
103883      return 0;
103884    }
103885    for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
103886      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
103887      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
103888      assert( pSub->pSrc!=0 );
103889      if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
103890       || (pSub1->pPrior && pSub1->op!=TK_ALL)
103891       || pSub1->pSrc->nSrc<1
103892       || pSub->pEList->nExpr!=pSub1->pEList->nExpr
103893      ){
103894        return 0;
103895      }
103896      testcase( pSub1->pSrc->nSrc>1 );
103897    }
103898
103899    /* Restriction 18. */
103900    if( p->pOrderBy ){
103901      int ii;
103902      for(ii=0; ii<p->pOrderBy->nExpr; ii++){
103903        if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
103904      }
103905    }
103906  }
103907
103908  /***** If we reach this point, flattening is permitted. *****/
103909
103910  /* Authorize the subquery */
103911  pParse->zAuthContext = pSubitem->zName;
103912  TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
103913  testcase( i==SQLITE_DENY );
103914  pParse->zAuthContext = zSavedAuthContext;
103915
103916  /* If the sub-query is a compound SELECT statement, then (by restrictions
103917  ** 17 and 18 above) it must be a UNION ALL and the parent query must
103918  ** be of the form:
103919  **
103920  **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
103921  **
103922  ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
103923  ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
103924  ** OFFSET clauses and joins them to the left-hand-side of the original
103925  ** using UNION ALL operators. In this case N is the number of simple
103926  ** select statements in the compound sub-query.
103927  **
103928  ** Example:
103929  **
103930  **     SELECT a+1 FROM (
103931  **        SELECT x FROM tab
103932  **        UNION ALL
103933  **        SELECT y FROM tab
103934  **        UNION ALL
103935  **        SELECT abs(z*2) FROM tab2
103936  **     ) WHERE a!=5 ORDER BY 1
103937  **
103938  ** Transformed into:
103939  **
103940  **     SELECT x+1 FROM tab WHERE x+1!=5
103941  **     UNION ALL
103942  **     SELECT y+1 FROM tab WHERE y+1!=5
103943  **     UNION ALL
103944  **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
103945  **     ORDER BY 1
103946  **
103947  ** We call this the "compound-subquery flattening".
103948  */
103949  for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
103950    Select *pNew;
103951    ExprList *pOrderBy = p->pOrderBy;
103952    Expr *pLimit = p->pLimit;
103953    Expr *pOffset = p->pOffset;
103954    Select *pPrior = p->pPrior;
103955    p->pOrderBy = 0;
103956    p->pSrc = 0;
103957    p->pPrior = 0;
103958    p->pLimit = 0;
103959    p->pOffset = 0;
103960    pNew = sqlite3SelectDup(db, p, 0);
103961    p->pOffset = pOffset;
103962    p->pLimit = pLimit;
103963    p->pOrderBy = pOrderBy;
103964    p->pSrc = pSrc;
103965    p->op = TK_ALL;
103966    if( pNew==0 ){
103967      p->pPrior = pPrior;
103968    }else{
103969      pNew->pPrior = pPrior;
103970      if( pPrior ) pPrior->pNext = pNew;
103971      pNew->pNext = p;
103972      p->pPrior = pNew;
103973    }
103974    if( db->mallocFailed ) return 1;
103975  }
103976
103977  /* Begin flattening the iFrom-th entry of the FROM clause
103978  ** in the outer query.
103979  */
103980  pSub = pSub1 = pSubitem->pSelect;
103981
103982  /* Delete the transient table structure associated with the
103983  ** subquery
103984  */
103985  sqlite3DbFree(db, pSubitem->zDatabase);
103986  sqlite3DbFree(db, pSubitem->zName);
103987  sqlite3DbFree(db, pSubitem->zAlias);
103988  pSubitem->zDatabase = 0;
103989  pSubitem->zName = 0;
103990  pSubitem->zAlias = 0;
103991  pSubitem->pSelect = 0;
103992
103993  /* Defer deleting the Table object associated with the
103994  ** subquery until code generation is
103995  ** complete, since there may still exist Expr.pTab entries that
103996  ** refer to the subquery even after flattening.  Ticket #3346.
103997  **
103998  ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
103999  */
104000  if( ALWAYS(pSubitem->pTab!=0) ){
104001    Table *pTabToDel = pSubitem->pTab;
104002    if( pTabToDel->nRef==1 ){
104003      Parse *pToplevel = sqlite3ParseToplevel(pParse);
104004      pTabToDel->pNextZombie = pToplevel->pZombieTab;
104005      pToplevel->pZombieTab = pTabToDel;
104006    }else{
104007      pTabToDel->nRef--;
104008    }
104009    pSubitem->pTab = 0;
104010  }
104011
104012  /* The following loop runs once for each term in a compound-subquery
104013  ** flattening (as described above).  If we are doing a different kind
104014  ** of flattening - a flattening other than a compound-subquery flattening -
104015  ** then this loop only runs once.
104016  **
104017  ** This loop moves all of the FROM elements of the subquery into the
104018  ** the FROM clause of the outer query.  Before doing this, remember
104019  ** the cursor number for the original outer query FROM element in
104020  ** iParent.  The iParent cursor will never be used.  Subsequent code
104021  ** will scan expressions looking for iParent references and replace
104022  ** those references with expressions that resolve to the subquery FROM
104023  ** elements we are now copying in.
104024  */
104025  for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
104026    int nSubSrc;
104027    u8 jointype = 0;
104028    pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
104029    nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
104030    pSrc = pParent->pSrc;     /* FROM clause of the outer query */
104031
104032    if( pSrc ){
104033      assert( pParent==p );  /* First time through the loop */
104034      jointype = pSubitem->jointype;
104035    }else{
104036      assert( pParent!=p );  /* 2nd and subsequent times through the loop */
104037      pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
104038      if( pSrc==0 ){
104039        assert( db->mallocFailed );
104040        break;
104041      }
104042    }
104043
104044    /* The subquery uses a single slot of the FROM clause of the outer
104045    ** query.  If the subquery has more than one element in its FROM clause,
104046    ** then expand the outer query to make space for it to hold all elements
104047    ** of the subquery.
104048    **
104049    ** Example:
104050    **
104051    **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
104052    **
104053    ** The outer query has 3 slots in its FROM clause.  One slot of the
104054    ** outer query (the middle slot) is used by the subquery.  The next
104055    ** block of code will expand the out query to 4 slots.  The middle
104056    ** slot is expanded to two slots in order to make space for the
104057    ** two elements in the FROM clause of the subquery.
104058    */
104059    if( nSubSrc>1 ){
104060      pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
104061      if( db->mallocFailed ){
104062        break;
104063      }
104064    }
104065
104066    /* Transfer the FROM clause terms from the subquery into the
104067    ** outer query.
104068    */
104069    for(i=0; i<nSubSrc; i++){
104070      sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
104071      pSrc->a[i+iFrom] = pSubSrc->a[i];
104072      memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
104073    }
104074    pSrc->a[iFrom].jointype = jointype;
104075
104076    /* Now begin substituting subquery result set expressions for
104077    ** references to the iParent in the outer query.
104078    **
104079    ** Example:
104080    **
104081    **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
104082    **   \                     \_____________ subquery __________/          /
104083    **    \_____________________ outer query ______________________________/
104084    **
104085    ** We look at every expression in the outer query and every place we see
104086    ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
104087    */
104088    pList = pParent->pEList;
104089    for(i=0; i<pList->nExpr; i++){
104090      if( pList->a[i].zName==0 ){
104091        char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
104092        sqlite3Dequote(zName);
104093        pList->a[i].zName = zName;
104094      }
104095    }
104096    substExprList(db, pParent->pEList, iParent, pSub->pEList);
104097    if( isAgg ){
104098      substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
104099      pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
104100    }
104101    if( pSub->pOrderBy ){
104102      assert( pParent->pOrderBy==0 );
104103      pParent->pOrderBy = pSub->pOrderBy;
104104      pSub->pOrderBy = 0;
104105    }else if( pParent->pOrderBy ){
104106      substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
104107    }
104108    if( pSub->pWhere ){
104109      pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
104110    }else{
104111      pWhere = 0;
104112    }
104113    if( subqueryIsAgg ){
104114      assert( pParent->pHaving==0 );
104115      pParent->pHaving = pParent->pWhere;
104116      pParent->pWhere = pWhere;
104117      pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
104118      pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
104119                                  sqlite3ExprDup(db, pSub->pHaving, 0));
104120      assert( pParent->pGroupBy==0 );
104121      pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
104122    }else{
104123      pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
104124      pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
104125    }
104126
104127    /* The flattened query is distinct if either the inner or the
104128    ** outer query is distinct.
104129    */
104130    pParent->selFlags |= pSub->selFlags & SF_Distinct;
104131
104132    /*
104133    ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
104134    **
104135    ** One is tempted to try to add a and b to combine the limits.  But this
104136    ** does not work if either limit is negative.
104137    */
104138    if( pSub->pLimit ){
104139      pParent->pLimit = pSub->pLimit;
104140      pSub->pLimit = 0;
104141    }
104142  }
104143
104144  /* Finially, delete what is left of the subquery and return
104145  ** success.
104146  */
104147  sqlite3SelectDelete(db, pSub1);
104148
104149  return 1;
104150}
104151#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
104152
104153/*
104154** Based on the contents of the AggInfo structure indicated by the first
104155** argument, this function checks if the following are true:
104156**
104157**    * the query contains just a single aggregate function,
104158**    * the aggregate function is either min() or max(), and
104159**    * the argument to the aggregate function is a column value.
104160**
104161** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
104162** is returned as appropriate. Also, *ppMinMax is set to point to the
104163** list of arguments passed to the aggregate before returning.
104164**
104165** Or, if the conditions above are not met, *ppMinMax is set to 0 and
104166** WHERE_ORDERBY_NORMAL is returned.
104167*/
104168static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
104169  int eRet = WHERE_ORDERBY_NORMAL;          /* Return value */
104170
104171  *ppMinMax = 0;
104172  if( pAggInfo->nFunc==1 ){
104173    Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
104174    ExprList *pEList = pExpr->x.pList;      /* Arguments to agg function */
104175
104176    assert( pExpr->op==TK_AGG_FUNCTION );
104177    if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
104178      const char *zFunc = pExpr->u.zToken;
104179      if( sqlite3StrICmp(zFunc, "min")==0 ){
104180        eRet = WHERE_ORDERBY_MIN;
104181        *ppMinMax = pEList;
104182      }else if( sqlite3StrICmp(zFunc, "max")==0 ){
104183        eRet = WHERE_ORDERBY_MAX;
104184        *ppMinMax = pEList;
104185      }
104186    }
104187  }
104188
104189  assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
104190  return eRet;
104191}
104192
104193/*
104194** The select statement passed as the first argument is an aggregate query.
104195** The second argment is the associated aggregate-info object. This
104196** function tests if the SELECT is of the form:
104197**
104198**   SELECT count(*) FROM <tbl>
104199**
104200** where table is a database table, not a sub-select or view. If the query
104201** does match this pattern, then a pointer to the Table object representing
104202** <tbl> is returned. Otherwise, 0 is returned.
104203*/
104204static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
104205  Table *pTab;
104206  Expr *pExpr;
104207
104208  assert( !p->pGroupBy );
104209
104210  if( p->pWhere || p->pEList->nExpr!=1
104211   || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
104212  ){
104213    return 0;
104214  }
104215  pTab = p->pSrc->a[0].pTab;
104216  pExpr = p->pEList->a[0].pExpr;
104217  assert( pTab && !pTab->pSelect && pExpr );
104218
104219  if( IsVirtual(pTab) ) return 0;
104220  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
104221  if( NEVER(pAggInfo->nFunc==0) ) return 0;
104222  if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
104223  if( pExpr->flags&EP_Distinct ) return 0;
104224
104225  return pTab;
104226}
104227
104228/*
104229** If the source-list item passed as an argument was augmented with an
104230** INDEXED BY clause, then try to locate the specified index. If there
104231** was such a clause and the named index cannot be found, return
104232** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
104233** pFrom->pIndex and return SQLITE_OK.
104234*/
104235SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
104236  if( pFrom->pTab && pFrom->zIndex ){
104237    Table *pTab = pFrom->pTab;
104238    char *zIndex = pFrom->zIndex;
104239    Index *pIdx;
104240    for(pIdx=pTab->pIndex;
104241        pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
104242        pIdx=pIdx->pNext
104243    );
104244    if( !pIdx ){
104245      sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
104246      pParse->checkSchema = 1;
104247      return SQLITE_ERROR;
104248    }
104249    pFrom->pIndex = pIdx;
104250  }
104251  return SQLITE_OK;
104252}
104253/*
104254** Detect compound SELECT statements that use an ORDER BY clause with
104255** an alternative collating sequence.
104256**
104257**    SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
104258**
104259** These are rewritten as a subquery:
104260**
104261**    SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
104262**     ORDER BY ... COLLATE ...
104263**
104264** This transformation is necessary because the multiSelectOrderBy() routine
104265** above that generates the code for a compound SELECT with an ORDER BY clause
104266** uses a merge algorithm that requires the same collating sequence on the
104267** result columns as on the ORDER BY clause.  See ticket
104268** http://www.sqlite.org/src/info/6709574d2a
104269**
104270** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
104271** The UNION ALL operator works fine with multiSelectOrderBy() even when
104272** there are COLLATE terms in the ORDER BY.
104273*/
104274static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
104275  int i;
104276  Select *pNew;
104277  Select *pX;
104278  sqlite3 *db;
104279  struct ExprList_item *a;
104280  SrcList *pNewSrc;
104281  Parse *pParse;
104282  Token dummy;
104283
104284  if( p->pPrior==0 ) return WRC_Continue;
104285  if( p->pOrderBy==0 ) return WRC_Continue;
104286  for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
104287  if( pX==0 ) return WRC_Continue;
104288  a = p->pOrderBy->a;
104289  for(i=p->pOrderBy->nExpr-1; i>=0; i--){
104290    if( a[i].pExpr->flags & EP_Collate ) break;
104291  }
104292  if( i<0 ) return WRC_Continue;
104293
104294  /* If we reach this point, that means the transformation is required. */
104295
104296  pParse = pWalker->pParse;
104297  db = pParse->db;
104298  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
104299  if( pNew==0 ) return WRC_Abort;
104300  memset(&dummy, 0, sizeof(dummy));
104301  pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
104302  if( pNewSrc==0 ) return WRC_Abort;
104303  *pNew = *p;
104304  p->pSrc = pNewSrc;
104305  p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0));
104306  p->op = TK_SELECT;
104307  p->pWhere = 0;
104308  pNew->pGroupBy = 0;
104309  pNew->pHaving = 0;
104310  pNew->pOrderBy = 0;
104311  p->pPrior = 0;
104312  p->pNext = 0;
104313  p->selFlags &= ~SF_Compound;
104314  assert( pNew->pPrior!=0 );
104315  pNew->pPrior->pNext = pNew;
104316  pNew->pLimit = 0;
104317  pNew->pOffset = 0;
104318  return WRC_Continue;
104319}
104320
104321#ifndef SQLITE_OMIT_CTE
104322/*
104323** Argument pWith (which may be NULL) points to a linked list of nested
104324** WITH contexts, from inner to outermost. If the table identified by
104325** FROM clause element pItem is really a common-table-expression (CTE)
104326** then return a pointer to the CTE definition for that table. Otherwise
104327** return NULL.
104328**
104329** If a non-NULL value is returned, set *ppContext to point to the With
104330** object that the returned CTE belongs to.
104331*/
104332static struct Cte *searchWith(
104333  With *pWith,                    /* Current outermost WITH clause */
104334  struct SrcList_item *pItem,     /* FROM clause element to resolve */
104335  With **ppContext                /* OUT: WITH clause return value belongs to */
104336){
104337  const char *zName;
104338  if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
104339    With *p;
104340    for(p=pWith; p; p=p->pOuter){
104341      int i;
104342      for(i=0; i<p->nCte; i++){
104343        if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
104344          *ppContext = p;
104345          return &p->a[i];
104346        }
104347      }
104348    }
104349  }
104350  return 0;
104351}
104352
104353/* The code generator maintains a stack of active WITH clauses
104354** with the inner-most WITH clause being at the top of the stack.
104355**
104356** This routine pushes the WITH clause passed as the second argument
104357** onto the top of the stack. If argument bFree is true, then this
104358** WITH clause will never be popped from the stack. In this case it
104359** should be freed along with the Parse object. In other cases, when
104360** bFree==0, the With object will be freed along with the SELECT
104361** statement with which it is associated.
104362*/
104363SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
104364  assert( bFree==0 || pParse->pWith==0 );
104365  if( pWith ){
104366    pWith->pOuter = pParse->pWith;
104367    pParse->pWith = pWith;
104368    pParse->bFreeWith = bFree;
104369  }
104370}
104371
104372/*
104373** This function checks if argument pFrom refers to a CTE declared by
104374** a WITH clause on the stack currently maintained by the parser. And,
104375** if currently processing a CTE expression, if it is a recursive
104376** reference to the current CTE.
104377**
104378** If pFrom falls into either of the two categories above, pFrom->pTab
104379** and other fields are populated accordingly. The caller should check
104380** (pFrom->pTab!=0) to determine whether or not a successful match
104381** was found.
104382**
104383** Whether or not a match is found, SQLITE_OK is returned if no error
104384** occurs. If an error does occur, an error message is stored in the
104385** parser and some error code other than SQLITE_OK returned.
104386*/
104387static int withExpand(
104388  Walker *pWalker,
104389  struct SrcList_item *pFrom
104390){
104391  Parse *pParse = pWalker->pParse;
104392  sqlite3 *db = pParse->db;
104393  struct Cte *pCte;               /* Matched CTE (or NULL if no match) */
104394  With *pWith;                    /* WITH clause that pCte belongs to */
104395
104396  assert( pFrom->pTab==0 );
104397
104398  pCte = searchWith(pParse->pWith, pFrom, &pWith);
104399  if( pCte ){
104400    Table *pTab;
104401    ExprList *pEList;
104402    Select *pSel;
104403    Select *pLeft;                /* Left-most SELECT statement */
104404    int bMayRecursive;            /* True if compound joined by UNION [ALL] */
104405    With *pSavedWith;             /* Initial value of pParse->pWith */
104406
104407    /* If pCte->zErr is non-NULL at this point, then this is an illegal
104408    ** recursive reference to CTE pCte. Leave an error in pParse and return
104409    ** early. If pCte->zErr is NULL, then this is not a recursive reference.
104410    ** In this case, proceed.  */
104411    if( pCte->zErr ){
104412      sqlite3ErrorMsg(pParse, pCte->zErr, pCte->zName);
104413      return SQLITE_ERROR;
104414    }
104415
104416    assert( pFrom->pTab==0 );
104417    pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
104418    if( pTab==0 ) return WRC_Abort;
104419    pTab->nRef = 1;
104420    pTab->zName = sqlite3DbStrDup(db, pCte->zName);
104421    pTab->iPKey = -1;
104422    pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
104423    pTab->tabFlags |= TF_Ephemeral;
104424    pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
104425    if( db->mallocFailed ) return SQLITE_NOMEM;
104426    assert( pFrom->pSelect );
104427
104428    /* Check if this is a recursive CTE. */
104429    pSel = pFrom->pSelect;
104430    bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
104431    if( bMayRecursive ){
104432      int i;
104433      SrcList *pSrc = pFrom->pSelect->pSrc;
104434      for(i=0; i<pSrc->nSrc; i++){
104435        struct SrcList_item *pItem = &pSrc->a[i];
104436        if( pItem->zDatabase==0
104437         && pItem->zName!=0
104438         && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
104439          ){
104440          pItem->pTab = pTab;
104441          pItem->isRecursive = 1;
104442          pTab->nRef++;
104443          pSel->selFlags |= SF_Recursive;
104444        }
104445      }
104446    }
104447
104448    /* Only one recursive reference is permitted. */
104449    if( pTab->nRef>2 ){
104450      sqlite3ErrorMsg(
104451          pParse, "multiple references to recursive table: %s", pCte->zName
104452      );
104453      return SQLITE_ERROR;
104454    }
104455    assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 ));
104456
104457    pCte->zErr = "circular reference: %s";
104458    pSavedWith = pParse->pWith;
104459    pParse->pWith = pWith;
104460    sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel);
104461
104462    for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
104463    pEList = pLeft->pEList;
104464    if( pCte->pCols ){
104465      if( pEList->nExpr!=pCte->pCols->nExpr ){
104466        sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
104467            pCte->zName, pEList->nExpr, pCte->pCols->nExpr
104468        );
104469        pParse->pWith = pSavedWith;
104470        return SQLITE_ERROR;
104471      }
104472      pEList = pCte->pCols;
104473    }
104474
104475    selectColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
104476    if( bMayRecursive ){
104477      if( pSel->selFlags & SF_Recursive ){
104478        pCte->zErr = "multiple recursive references: %s";
104479      }else{
104480        pCte->zErr = "recursive reference in a subquery: %s";
104481      }
104482      sqlite3WalkSelect(pWalker, pSel);
104483    }
104484    pCte->zErr = 0;
104485    pParse->pWith = pSavedWith;
104486  }
104487
104488  return SQLITE_OK;
104489}
104490#endif
104491
104492#ifndef SQLITE_OMIT_CTE
104493/*
104494** If the SELECT passed as the second argument has an associated WITH
104495** clause, pop it from the stack stored as part of the Parse object.
104496**
104497** This function is used as the xSelectCallback2() callback by
104498** sqlite3SelectExpand() when walking a SELECT tree to resolve table
104499** names and other FROM clause elements.
104500*/
104501static void selectPopWith(Walker *pWalker, Select *p){
104502  Parse *pParse = pWalker->pParse;
104503  With *pWith = findRightmost(p)->pWith;
104504  if( pWith!=0 ){
104505    assert( pParse->pWith==pWith );
104506    pParse->pWith = pWith->pOuter;
104507  }
104508}
104509#else
104510#define selectPopWith 0
104511#endif
104512
104513/*
104514** This routine is a Walker callback for "expanding" a SELECT statement.
104515** "Expanding" means to do the following:
104516**
104517**    (1)  Make sure VDBE cursor numbers have been assigned to every
104518**         element of the FROM clause.
104519**
104520**    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
104521**         defines FROM clause.  When views appear in the FROM clause,
104522**         fill pTabList->a[].pSelect with a copy of the SELECT statement
104523**         that implements the view.  A copy is made of the view's SELECT
104524**         statement so that we can freely modify or delete that statement
104525**         without worrying about messing up the presistent representation
104526**         of the view.
104527**
104528**    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
104529**         on joins and the ON and USING clause of joins.
104530**
104531**    (4)  Scan the list of columns in the result set (pEList) looking
104532**         for instances of the "*" operator or the TABLE.* operator.
104533**         If found, expand each "*" to be every column in every table
104534**         and TABLE.* to be every column in TABLE.
104535**
104536*/
104537static int selectExpander(Walker *pWalker, Select *p){
104538  Parse *pParse = pWalker->pParse;
104539  int i, j, k;
104540  SrcList *pTabList;
104541  ExprList *pEList;
104542  struct SrcList_item *pFrom;
104543  sqlite3 *db = pParse->db;
104544  Expr *pE, *pRight, *pExpr;
104545  u16 selFlags = p->selFlags;
104546
104547  p->selFlags |= SF_Expanded;
104548  if( db->mallocFailed  ){
104549    return WRC_Abort;
104550  }
104551  if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
104552    return WRC_Prune;
104553  }
104554  pTabList = p->pSrc;
104555  pEList = p->pEList;
104556  sqlite3WithPush(pParse, findRightmost(p)->pWith, 0);
104557
104558  /* Make sure cursor numbers have been assigned to all entries in
104559  ** the FROM clause of the SELECT statement.
104560  */
104561  sqlite3SrcListAssignCursors(pParse, pTabList);
104562
104563  /* Look up every table named in the FROM clause of the select.  If
104564  ** an entry of the FROM clause is a subquery instead of a table or view,
104565  ** then create a transient table structure to describe the subquery.
104566  */
104567  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
104568    Table *pTab;
104569    assert( pFrom->isRecursive==0 || pFrom->pTab );
104570    if( pFrom->isRecursive ) continue;
104571    if( pFrom->pTab!=0 ){
104572      /* This statement has already been prepared.  There is no need
104573      ** to go further. */
104574      assert( i==0 );
104575#ifndef SQLITE_OMIT_CTE
104576      selectPopWith(pWalker, p);
104577#endif
104578      return WRC_Prune;
104579    }
104580#ifndef SQLITE_OMIT_CTE
104581    if( withExpand(pWalker, pFrom) ) return WRC_Abort;
104582    if( pFrom->pTab ) {} else
104583#endif
104584    if( pFrom->zName==0 ){
104585#ifndef SQLITE_OMIT_SUBQUERY
104586      Select *pSel = pFrom->pSelect;
104587      /* A sub-query in the FROM clause of a SELECT */
104588      assert( pSel!=0 );
104589      assert( pFrom->pTab==0 );
104590      sqlite3WalkSelect(pWalker, pSel);
104591      pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
104592      if( pTab==0 ) return WRC_Abort;
104593      pTab->nRef = 1;
104594      pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
104595      while( pSel->pPrior ){ pSel = pSel->pPrior; }
104596      selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
104597      pTab->iPKey = -1;
104598      pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
104599      pTab->tabFlags |= TF_Ephemeral;
104600#endif
104601    }else{
104602      /* An ordinary table or view name in the FROM clause */
104603      assert( pFrom->pTab==0 );
104604      pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
104605      if( pTab==0 ) return WRC_Abort;
104606      if( pTab->nRef==0xffff ){
104607        sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
104608           pTab->zName);
104609        pFrom->pTab = 0;
104610        return WRC_Abort;
104611      }
104612      pTab->nRef++;
104613#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
104614      if( pTab->pSelect || IsVirtual(pTab) ){
104615        /* We reach here if the named table is a really a view */
104616        if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
104617        assert( pFrom->pSelect==0 );
104618        pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
104619        sqlite3WalkSelect(pWalker, pFrom->pSelect);
104620      }
104621#endif
104622    }
104623
104624    /* Locate the index named by the INDEXED BY clause, if any. */
104625    if( sqlite3IndexedByLookup(pParse, pFrom) ){
104626      return WRC_Abort;
104627    }
104628  }
104629
104630  /* Process NATURAL keywords, and ON and USING clauses of joins.
104631  */
104632  if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
104633    return WRC_Abort;
104634  }
104635
104636  /* For every "*" that occurs in the column list, insert the names of
104637  ** all columns in all tables.  And for every TABLE.* insert the names
104638  ** of all columns in TABLE.  The parser inserted a special expression
104639  ** with the TK_ALL operator for each "*" that it found in the column list.
104640  ** The following code just has to locate the TK_ALL expressions and expand
104641  ** each one to the list of all columns in all tables.
104642  **
104643  ** The first loop just checks to see if there are any "*" operators
104644  ** that need expanding.
104645  */
104646  for(k=0; k<pEList->nExpr; k++){
104647    pE = pEList->a[k].pExpr;
104648    if( pE->op==TK_ALL ) break;
104649    assert( pE->op!=TK_DOT || pE->pRight!=0 );
104650    assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
104651    if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
104652  }
104653  if( k<pEList->nExpr ){
104654    /*
104655    ** If we get here it means the result set contains one or more "*"
104656    ** operators that need to be expanded.  Loop through each expression
104657    ** in the result set and expand them one by one.
104658    */
104659    struct ExprList_item *a = pEList->a;
104660    ExprList *pNew = 0;
104661    int flags = pParse->db->flags;
104662    int longNames = (flags & SQLITE_FullColNames)!=0
104663                      && (flags & SQLITE_ShortColNames)==0;
104664
104665    /* When processing FROM-clause subqueries, it is always the case
104666    ** that full_column_names=OFF and short_column_names=ON.  The
104667    ** sqlite3ResultSetOfSelect() routine makes it so. */
104668    assert( (p->selFlags & SF_NestedFrom)==0
104669          || ((flags & SQLITE_FullColNames)==0 &&
104670              (flags & SQLITE_ShortColNames)!=0) );
104671
104672    for(k=0; k<pEList->nExpr; k++){
104673      pE = a[k].pExpr;
104674      pRight = pE->pRight;
104675      assert( pE->op!=TK_DOT || pRight!=0 );
104676      if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){
104677        /* This particular expression does not need to be expanded.
104678        */
104679        pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
104680        if( pNew ){
104681          pNew->a[pNew->nExpr-1].zName = a[k].zName;
104682          pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
104683          a[k].zName = 0;
104684          a[k].zSpan = 0;
104685        }
104686        a[k].pExpr = 0;
104687      }else{
104688        /* This expression is a "*" or a "TABLE.*" and needs to be
104689        ** expanded. */
104690        int tableSeen = 0;      /* Set to 1 when TABLE matches */
104691        char *zTName = 0;       /* text of name of TABLE */
104692        if( pE->op==TK_DOT ){
104693          assert( pE->pLeft!=0 );
104694          assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
104695          zTName = pE->pLeft->u.zToken;
104696        }
104697        for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
104698          Table *pTab = pFrom->pTab;
104699          Select *pSub = pFrom->pSelect;
104700          char *zTabName = pFrom->zAlias;
104701          const char *zSchemaName = 0;
104702          int iDb;
104703          if( zTabName==0 ){
104704            zTabName = pTab->zName;
104705          }
104706          if( db->mallocFailed ) break;
104707          if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
104708            pSub = 0;
104709            if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
104710              continue;
104711            }
104712            iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
104713            zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
104714          }
104715          for(j=0; j<pTab->nCol; j++){
104716            char *zName = pTab->aCol[j].zName;
104717            char *zColname;  /* The computed column name */
104718            char *zToFree;   /* Malloced string that needs to be freed */
104719            Token sColname;  /* Computed column name as a token */
104720
104721            assert( zName );
104722            if( zTName && pSub
104723             && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
104724            ){
104725              continue;
104726            }
104727
104728            /* If a column is marked as 'hidden' (currently only possible
104729            ** for virtual tables), do not include it in the expanded
104730            ** result-set list.
104731            */
104732            if( IsHiddenColumn(&pTab->aCol[j]) ){
104733              assert(IsVirtual(pTab));
104734              continue;
104735            }
104736            tableSeen = 1;
104737
104738            if( i>0 && zTName==0 ){
104739              if( (pFrom->jointype & JT_NATURAL)!=0
104740                && tableAndColumnIndex(pTabList, i, zName, 0, 0)
104741              ){
104742                /* In a NATURAL join, omit the join columns from the
104743                ** table to the right of the join */
104744                continue;
104745              }
104746              if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
104747                /* In a join with a USING clause, omit columns in the
104748                ** using clause from the table on the right. */
104749                continue;
104750              }
104751            }
104752            pRight = sqlite3Expr(db, TK_ID, zName);
104753            zColname = zName;
104754            zToFree = 0;
104755            if( longNames || pTabList->nSrc>1 ){
104756              Expr *pLeft;
104757              pLeft = sqlite3Expr(db, TK_ID, zTabName);
104758              pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
104759              if( zSchemaName ){
104760                pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
104761                pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
104762              }
104763              if( longNames ){
104764                zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
104765                zToFree = zColname;
104766              }
104767            }else{
104768              pExpr = pRight;
104769            }
104770            pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
104771            sColname.z = zColname;
104772            sColname.n = sqlite3Strlen30(zColname);
104773            sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
104774            if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
104775              struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
104776              if( pSub ){
104777                pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
104778                testcase( pX->zSpan==0 );
104779              }else{
104780                pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
104781                                           zSchemaName, zTabName, zColname);
104782                testcase( pX->zSpan==0 );
104783              }
104784              pX->bSpanIsTab = 1;
104785            }
104786            sqlite3DbFree(db, zToFree);
104787          }
104788        }
104789        if( !tableSeen ){
104790          if( zTName ){
104791            sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
104792          }else{
104793            sqlite3ErrorMsg(pParse, "no tables specified");
104794          }
104795        }
104796      }
104797    }
104798    sqlite3ExprListDelete(db, pEList);
104799    p->pEList = pNew;
104800  }
104801#if SQLITE_MAX_COLUMN
104802  if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
104803    sqlite3ErrorMsg(pParse, "too many columns in result set");
104804  }
104805#endif
104806  return WRC_Continue;
104807}
104808
104809/*
104810** No-op routine for the parse-tree walker.
104811**
104812** When this routine is the Walker.xExprCallback then expression trees
104813** are walked without any actions being taken at each node.  Presumably,
104814** when this routine is used for Walker.xExprCallback then
104815** Walker.xSelectCallback is set to do something useful for every
104816** subquery in the parser tree.
104817*/
104818static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
104819  UNUSED_PARAMETER2(NotUsed, NotUsed2);
104820  return WRC_Continue;
104821}
104822
104823/*
104824** This routine "expands" a SELECT statement and all of its subqueries.
104825** For additional information on what it means to "expand" a SELECT
104826** statement, see the comment on the selectExpand worker callback above.
104827**
104828** Expanding a SELECT statement is the first step in processing a
104829** SELECT statement.  The SELECT statement must be expanded before
104830** name resolution is performed.
104831**
104832** If anything goes wrong, an error message is written into pParse.
104833** The calling function can detect the problem by looking at pParse->nErr
104834** and/or pParse->db->mallocFailed.
104835*/
104836static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
104837  Walker w;
104838  memset(&w, 0, sizeof(w));
104839  w.xExprCallback = exprWalkNoop;
104840  w.pParse = pParse;
104841  if( pParse->hasCompound ){
104842    w.xSelectCallback = convertCompoundSelectToSubquery;
104843    sqlite3WalkSelect(&w, pSelect);
104844  }
104845  w.xSelectCallback = selectExpander;
104846  w.xSelectCallback2 = selectPopWith;
104847  sqlite3WalkSelect(&w, pSelect);
104848}
104849
104850
104851#ifndef SQLITE_OMIT_SUBQUERY
104852/*
104853** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
104854** interface.
104855**
104856** For each FROM-clause subquery, add Column.zType and Column.zColl
104857** information to the Table structure that represents the result set
104858** of that subquery.
104859**
104860** The Table structure that represents the result set was constructed
104861** by selectExpander() but the type and collation information was omitted
104862** at that point because identifiers had not yet been resolved.  This
104863** routine is called after identifier resolution.
104864*/
104865static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
104866  Parse *pParse;
104867  int i;
104868  SrcList *pTabList;
104869  struct SrcList_item *pFrom;
104870
104871  assert( p->selFlags & SF_Resolved );
104872  if( (p->selFlags & SF_HasTypeInfo)==0 ){
104873    p->selFlags |= SF_HasTypeInfo;
104874    pParse = pWalker->pParse;
104875    pTabList = p->pSrc;
104876    for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
104877      Table *pTab = pFrom->pTab;
104878      if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
104879        /* A sub-query in the FROM clause of a SELECT */
104880        Select *pSel = pFrom->pSelect;
104881        if( pSel ){
104882          while( pSel->pPrior ) pSel = pSel->pPrior;
104883          selectAddColumnTypeAndCollation(pParse, pTab, pSel);
104884        }
104885      }
104886    }
104887  }
104888}
104889#endif
104890
104891
104892/*
104893** This routine adds datatype and collating sequence information to
104894** the Table structures of all FROM-clause subqueries in a
104895** SELECT statement.
104896**
104897** Use this routine after name resolution.
104898*/
104899static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
104900#ifndef SQLITE_OMIT_SUBQUERY
104901  Walker w;
104902  memset(&w, 0, sizeof(w));
104903  w.xSelectCallback2 = selectAddSubqueryTypeInfo;
104904  w.xExprCallback = exprWalkNoop;
104905  w.pParse = pParse;
104906  sqlite3WalkSelect(&w, pSelect);
104907#endif
104908}
104909
104910
104911/*
104912** This routine sets up a SELECT statement for processing.  The
104913** following is accomplished:
104914**
104915**     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
104916**     *  Ephemeral Table objects are created for all FROM-clause subqueries.
104917**     *  ON and USING clauses are shifted into WHERE statements
104918**     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
104919**     *  Identifiers in expression are matched to tables.
104920**
104921** This routine acts recursively on all subqueries within the SELECT.
104922*/
104923SQLITE_PRIVATE void sqlite3SelectPrep(
104924  Parse *pParse,         /* The parser context */
104925  Select *p,             /* The SELECT statement being coded. */
104926  NameContext *pOuterNC  /* Name context for container */
104927){
104928  sqlite3 *db;
104929  if( NEVER(p==0) ) return;
104930  db = pParse->db;
104931  if( db->mallocFailed ) return;
104932  if( p->selFlags & SF_HasTypeInfo ) return;
104933  sqlite3SelectExpand(pParse, p);
104934  if( pParse->nErr || db->mallocFailed ) return;
104935  sqlite3ResolveSelectNames(pParse, p, pOuterNC);
104936  if( pParse->nErr || db->mallocFailed ) return;
104937  sqlite3SelectAddTypeInfo(pParse, p);
104938}
104939
104940/*
104941** Reset the aggregate accumulator.
104942**
104943** The aggregate accumulator is a set of memory cells that hold
104944** intermediate results while calculating an aggregate.  This
104945** routine generates code that stores NULLs in all of those memory
104946** cells.
104947*/
104948static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
104949  Vdbe *v = pParse->pVdbe;
104950  int i;
104951  struct AggInfo_func *pFunc;
104952  int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
104953  if( nReg==0 ) return;
104954#ifdef SQLITE_DEBUG
104955  /* Verify that all AggInfo registers are within the range specified by
104956  ** AggInfo.mnReg..AggInfo.mxReg */
104957  assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
104958  for(i=0; i<pAggInfo->nColumn; i++){
104959    assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
104960         && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
104961  }
104962  for(i=0; i<pAggInfo->nFunc; i++){
104963    assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
104964         && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
104965  }
104966#endif
104967  sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
104968  for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
104969    if( pFunc->iDistinct>=0 ){
104970      Expr *pE = pFunc->pExpr;
104971      assert( !ExprHasProperty(pE, EP_xIsSelect) );
104972      if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
104973        sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
104974           "argument");
104975        pFunc->iDistinct = -1;
104976      }else{
104977        KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
104978        sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
104979                          (char*)pKeyInfo, P4_KEYINFO);
104980      }
104981    }
104982  }
104983}
104984
104985/*
104986** Invoke the OP_AggFinalize opcode for every aggregate function
104987** in the AggInfo structure.
104988*/
104989static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
104990  Vdbe *v = pParse->pVdbe;
104991  int i;
104992  struct AggInfo_func *pF;
104993  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
104994    ExprList *pList = pF->pExpr->x.pList;
104995    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
104996    sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
104997                      (void*)pF->pFunc, P4_FUNCDEF);
104998  }
104999}
105000
105001/*
105002** Update the accumulator memory cells for an aggregate based on
105003** the current cursor position.
105004*/
105005static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
105006  Vdbe *v = pParse->pVdbe;
105007  int i;
105008  int regHit = 0;
105009  int addrHitTest = 0;
105010  struct AggInfo_func *pF;
105011  struct AggInfo_col *pC;
105012
105013  pAggInfo->directMode = 1;
105014  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
105015    int nArg;
105016    int addrNext = 0;
105017    int regAgg;
105018    ExprList *pList = pF->pExpr->x.pList;
105019    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
105020    if( pList ){
105021      nArg = pList->nExpr;
105022      regAgg = sqlite3GetTempRange(pParse, nArg);
105023      sqlite3ExprCodeExprList(pParse, pList, regAgg, SQLITE_ECEL_DUP);
105024    }else{
105025      nArg = 0;
105026      regAgg = 0;
105027    }
105028    if( pF->iDistinct>=0 ){
105029      addrNext = sqlite3VdbeMakeLabel(v);
105030      assert( nArg==1 );
105031      codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
105032    }
105033    if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
105034      CollSeq *pColl = 0;
105035      struct ExprList_item *pItem;
105036      int j;
105037      assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
105038      for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
105039        pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
105040      }
105041      if( !pColl ){
105042        pColl = pParse->db->pDfltColl;
105043      }
105044      if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
105045      sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
105046    }
105047    sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
105048                      (void*)pF->pFunc, P4_FUNCDEF);
105049    sqlite3VdbeChangeP5(v, (u8)nArg);
105050    sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
105051    sqlite3ReleaseTempRange(pParse, regAgg, nArg);
105052    if( addrNext ){
105053      sqlite3VdbeResolveLabel(v, addrNext);
105054      sqlite3ExprCacheClear(pParse);
105055    }
105056  }
105057
105058  /* Before populating the accumulator registers, clear the column cache.
105059  ** Otherwise, if any of the required column values are already present
105060  ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
105061  ** to pC->iMem. But by the time the value is used, the original register
105062  ** may have been used, invalidating the underlying buffer holding the
105063  ** text or blob value. See ticket [883034dcb5].
105064  **
105065  ** Another solution would be to change the OP_SCopy used to copy cached
105066  ** values to an OP_Copy.
105067  */
105068  if( regHit ){
105069    addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
105070  }
105071  sqlite3ExprCacheClear(pParse);
105072  for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
105073    sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
105074  }
105075  pAggInfo->directMode = 0;
105076  sqlite3ExprCacheClear(pParse);
105077  if( addrHitTest ){
105078    sqlite3VdbeJumpHere(v, addrHitTest);
105079  }
105080}
105081
105082/*
105083** Add a single OP_Explain instruction to the VDBE to explain a simple
105084** count(*) query ("SELECT count(*) FROM pTab").
105085*/
105086#ifndef SQLITE_OMIT_EXPLAIN
105087static void explainSimpleCount(
105088  Parse *pParse,                  /* Parse context */
105089  Table *pTab,                    /* Table being queried */
105090  Index *pIdx                     /* Index used to optimize scan, or NULL */
105091){
105092  if( pParse->explain==2 ){
105093    int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
105094    char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
105095        pTab->zName,
105096        bCover ? " USING COVERING INDEX " : "",
105097        bCover ? pIdx->zName : ""
105098    );
105099    sqlite3VdbeAddOp4(
105100        pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
105101    );
105102  }
105103}
105104#else
105105# define explainSimpleCount(a,b,c)
105106#endif
105107
105108/*
105109** Generate code for the SELECT statement given in the p argument.
105110**
105111** The results are returned according to the SelectDest structure.
105112** See comments in sqliteInt.h for further information.
105113**
105114** This routine returns the number of errors.  If any errors are
105115** encountered, then an appropriate error message is left in
105116** pParse->zErrMsg.
105117**
105118** This routine does NOT free the Select structure passed in.  The
105119** calling function needs to do that.
105120*/
105121SQLITE_PRIVATE int sqlite3Select(
105122  Parse *pParse,         /* The parser context */
105123  Select *p,             /* The SELECT statement being coded. */
105124  SelectDest *pDest      /* What to do with the query results */
105125){
105126  int i, j;              /* Loop counters */
105127  WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
105128  Vdbe *v;               /* The virtual machine under construction */
105129  int isAgg;             /* True for select lists like "count(*)" */
105130  ExprList *pEList;      /* List of columns to extract. */
105131  SrcList *pTabList;     /* List of tables to select from */
105132  Expr *pWhere;          /* The WHERE clause.  May be NULL */
105133  ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
105134  Expr *pHaving;         /* The HAVING clause.  May be NULL */
105135  int rc = 1;            /* Value to return from this function */
105136  DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
105137  SortCtx sSort;         /* Info on how to code the ORDER BY clause */
105138  AggInfo sAggInfo;      /* Information used by aggregate queries */
105139  int iEnd;              /* Address of the end of the query */
105140  sqlite3 *db;           /* The database connection */
105141
105142#ifndef SQLITE_OMIT_EXPLAIN
105143  int iRestoreSelectId = pParse->iSelectId;
105144  pParse->iSelectId = pParse->iNextSelectId++;
105145#endif
105146
105147  db = pParse->db;
105148  if( p==0 || db->mallocFailed || pParse->nErr ){
105149    return 1;
105150  }
105151  if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
105152  memset(&sAggInfo, 0, sizeof(sAggInfo));
105153
105154  assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
105155  assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
105156  assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
105157  assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
105158  if( IgnorableOrderby(pDest) ){
105159    assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
105160           pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
105161           pDest->eDest==SRT_Queue  || pDest->eDest==SRT_DistFifo ||
105162           pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
105163    /* If ORDER BY makes no difference in the output then neither does
105164    ** DISTINCT so it can be removed too. */
105165    sqlite3ExprListDelete(db, p->pOrderBy);
105166    p->pOrderBy = 0;
105167    p->selFlags &= ~SF_Distinct;
105168  }
105169  sqlite3SelectPrep(pParse, p, 0);
105170  memset(&sSort, 0, sizeof(sSort));
105171  sSort.pOrderBy = p->pOrderBy;
105172  pTabList = p->pSrc;
105173  pEList = p->pEList;
105174  if( pParse->nErr || db->mallocFailed ){
105175    goto select_end;
105176  }
105177  isAgg = (p->selFlags & SF_Aggregate)!=0;
105178  assert( pEList!=0 );
105179
105180  /* Begin generating code.
105181  */
105182  v = sqlite3GetVdbe(pParse);
105183  if( v==0 ) goto select_end;
105184
105185  /* If writing to memory or generating a set
105186  ** only a single column may be output.
105187  */
105188#ifndef SQLITE_OMIT_SUBQUERY
105189  if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
105190    goto select_end;
105191  }
105192#endif
105193
105194  /* Generate code for all sub-queries in the FROM clause
105195  */
105196#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
105197  for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
105198    struct SrcList_item *pItem = &pTabList->a[i];
105199    SelectDest dest;
105200    Select *pSub = pItem->pSelect;
105201    int isAggSub;
105202
105203    if( pSub==0 ) continue;
105204
105205    /* Sometimes the code for a subquery will be generated more than
105206    ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
105207    ** for example.  In that case, do not regenerate the code to manifest
105208    ** a view or the co-routine to implement a view.  The first instance
105209    ** is sufficient, though the subroutine to manifest the view does need
105210    ** to be invoked again. */
105211    if( pItem->addrFillSub ){
105212      if( pItem->viaCoroutine==0 ){
105213        sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
105214      }
105215      continue;
105216    }
105217
105218    /* Increment Parse.nHeight by the height of the largest expression
105219    ** tree referred to by this, the parent select. The child select
105220    ** may contain expression trees of at most
105221    ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
105222    ** more conservative than necessary, but much easier than enforcing
105223    ** an exact limit.
105224    */
105225    pParse->nHeight += sqlite3SelectExprHeight(p);
105226
105227    isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
105228    if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
105229      /* This subquery can be absorbed into its parent. */
105230      if( isAggSub ){
105231        isAgg = 1;
105232        p->selFlags |= SF_Aggregate;
105233      }
105234      i = -1;
105235    }else if( pTabList->nSrc==1
105236           && OptimizationEnabled(db, SQLITE_SubqCoroutine)
105237    ){
105238      /* Implement a co-routine that will return a single row of the result
105239      ** set on each invocation.
105240      */
105241      int addrTop = sqlite3VdbeCurrentAddr(v)+1;
105242      pItem->regReturn = ++pParse->nMem;
105243      sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
105244      VdbeComment((v, "%s", pItem->pTab->zName));
105245      pItem->addrFillSub = addrTop;
105246      sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
105247      explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
105248      sqlite3Select(pParse, pSub, &dest);
105249      pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
105250      pItem->viaCoroutine = 1;
105251      pItem->regResult = dest.iSdst;
105252      sqlite3VdbeAddOp1(v, OP_EndCoroutine, pItem->regReturn);
105253      sqlite3VdbeJumpHere(v, addrTop-1);
105254      sqlite3ClearTempRegCache(pParse);
105255    }else{
105256      /* Generate a subroutine that will fill an ephemeral table with
105257      ** the content of this subquery.  pItem->addrFillSub will point
105258      ** to the address of the generated subroutine.  pItem->regReturn
105259      ** is a register allocated to hold the subroutine return address
105260      */
105261      int topAddr;
105262      int onceAddr = 0;
105263      int retAddr;
105264      assert( pItem->addrFillSub==0 );
105265      pItem->regReturn = ++pParse->nMem;
105266      topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
105267      pItem->addrFillSub = topAddr+1;
105268      if( pItem->isCorrelated==0 ){
105269        /* If the subquery is not correlated and if we are not inside of
105270        ** a trigger, then we only need to compute the value of the subquery
105271        ** once. */
105272        onceAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
105273        VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
105274      }else{
105275        VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
105276      }
105277      sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
105278      explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
105279      sqlite3Select(pParse, pSub, &dest);
105280      pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
105281      if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
105282      retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
105283      VdbeComment((v, "end %s", pItem->pTab->zName));
105284      sqlite3VdbeChangeP1(v, topAddr, retAddr);
105285      sqlite3ClearTempRegCache(pParse);
105286    }
105287    if( /*pParse->nErr ||*/ db->mallocFailed ){
105288      goto select_end;
105289    }
105290    pParse->nHeight -= sqlite3SelectExprHeight(p);
105291    pTabList = p->pSrc;
105292    if( !IgnorableOrderby(pDest) ){
105293      sSort.pOrderBy = p->pOrderBy;
105294    }
105295  }
105296  pEList = p->pEList;
105297#endif
105298  pWhere = p->pWhere;
105299  pGroupBy = p->pGroupBy;
105300  pHaving = p->pHaving;
105301  sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
105302
105303#ifndef SQLITE_OMIT_COMPOUND_SELECT
105304  /* If there is are a sequence of queries, do the earlier ones first.
105305  */
105306  if( p->pPrior ){
105307    rc = multiSelect(pParse, p, pDest);
105308    explainSetInteger(pParse->iSelectId, iRestoreSelectId);
105309    return rc;
105310  }
105311#endif
105312
105313  /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
105314  ** if the select-list is the same as the ORDER BY list, then this query
105315  ** can be rewritten as a GROUP BY. In other words, this:
105316  **
105317  **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
105318  **
105319  ** is transformed to:
105320  **
105321  **     SELECT xyz FROM ... GROUP BY xyz
105322  **
105323  ** The second form is preferred as a single index (or temp-table) may be
105324  ** used for both the ORDER BY and DISTINCT processing. As originally
105325  ** written the query must use a temp-table for at least one of the ORDER
105326  ** BY and DISTINCT, and an index or separate temp-table for the other.
105327  */
105328  if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
105329   && sqlite3ExprListCompare(sSort.pOrderBy, p->pEList, -1)==0
105330  ){
105331    p->selFlags &= ~SF_Distinct;
105332    p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
105333    pGroupBy = p->pGroupBy;
105334    sSort.pOrderBy = 0;
105335    /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
105336    ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
105337    ** original setting of the SF_Distinct flag, not the current setting */
105338    assert( sDistinct.isTnct );
105339  }
105340
105341  /* If there is an ORDER BY clause, then this sorting
105342  ** index might end up being unused if the data can be
105343  ** extracted in pre-sorted order.  If that is the case, then the
105344  ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
105345  ** we figure out that the sorting index is not needed.  The addrSortIndex
105346  ** variable is used to facilitate that change.
105347  */
105348  if( sSort.pOrderBy ){
105349    KeyInfo *pKeyInfo;
105350    pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, 0);
105351    sSort.iECursor = pParse->nTab++;
105352    sSort.addrSortIndex =
105353      sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
105354                           sSort.iECursor, sSort.pOrderBy->nExpr+2, 0,
105355                           (char*)pKeyInfo, P4_KEYINFO);
105356  }else{
105357    sSort.addrSortIndex = -1;
105358  }
105359
105360  /* If the output is destined for a temporary table, open that table.
105361  */
105362  if( pDest->eDest==SRT_EphemTab ){
105363    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
105364  }
105365
105366  /* Set the limiter.
105367  */
105368  iEnd = sqlite3VdbeMakeLabel(v);
105369  p->nSelectRow = LARGEST_INT64;
105370  computeLimitRegisters(pParse, p, iEnd);
105371  if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
105372    sqlite3VdbeGetOp(v, sSort.addrSortIndex)->opcode = OP_SorterOpen;
105373    sSort.sortFlags |= SORTFLAG_UseSorter;
105374  }
105375
105376  /* Open a virtual index to use for the distinct set.
105377  */
105378  if( p->selFlags & SF_Distinct ){
105379    sDistinct.tabTnct = pParse->nTab++;
105380    sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
105381                                sDistinct.tabTnct, 0, 0,
105382                                (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
105383                                P4_KEYINFO);
105384    sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
105385    sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
105386  }else{
105387    sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
105388  }
105389
105390  if( !isAgg && pGroupBy==0 ){
105391    /* No aggregate functions and no GROUP BY clause */
105392    u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
105393
105394    /* Begin the database scan. */
105395    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
105396                               p->pEList, wctrlFlags, 0);
105397    if( pWInfo==0 ) goto select_end;
105398    if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
105399      p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
105400    }
105401    if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
105402      sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
105403    }
105404    if( sSort.pOrderBy ){
105405      sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
105406      if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
105407        sSort.pOrderBy = 0;
105408      }
105409    }
105410
105411    /* If sorting index that was created by a prior OP_OpenEphemeral
105412    ** instruction ended up not being needed, then change the OP_OpenEphemeral
105413    ** into an OP_Noop.
105414    */
105415    if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
105416      sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
105417    }
105418
105419    /* Use the standard inner loop. */
105420    selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest,
105421                    sqlite3WhereContinueLabel(pWInfo),
105422                    sqlite3WhereBreakLabel(pWInfo));
105423
105424    /* End the database scan loop.
105425    */
105426    sqlite3WhereEnd(pWInfo);
105427  }else{
105428    /* This case when there exist aggregate functions or a GROUP BY clause
105429    ** or both */
105430    NameContext sNC;    /* Name context for processing aggregate information */
105431    int iAMem;          /* First Mem address for storing current GROUP BY */
105432    int iBMem;          /* First Mem address for previous GROUP BY */
105433    int iUseFlag;       /* Mem address holding flag indicating that at least
105434                        ** one row of the input to the aggregator has been
105435                        ** processed */
105436    int iAbortFlag;     /* Mem address which causes query abort if positive */
105437    int groupBySort;    /* Rows come from source in GROUP BY order */
105438    int addrEnd;        /* End of processing for this SELECT */
105439    int sortPTab = 0;   /* Pseudotable used to decode sorting results */
105440    int sortOut = 0;    /* Output register from the sorter */
105441    int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
105442
105443    /* Remove any and all aliases between the result set and the
105444    ** GROUP BY clause.
105445    */
105446    if( pGroupBy ){
105447      int k;                        /* Loop counter */
105448      struct ExprList_item *pItem;  /* For looping over expression in a list */
105449
105450      for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
105451        pItem->u.x.iAlias = 0;
105452      }
105453      for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
105454        pItem->u.x.iAlias = 0;
105455      }
105456      if( p->nSelectRow>100 ) p->nSelectRow = 100;
105457    }else{
105458      p->nSelectRow = 1;
105459    }
105460
105461
105462    /* If there is both a GROUP BY and an ORDER BY clause and they are
105463    ** identical, then it may be possible to disable the ORDER BY clause
105464    ** on the grounds that the GROUP BY will cause elements to come out
105465    ** in the correct order. It also may not - the GROUP BY may use a
105466    ** database index that causes rows to be grouped together as required
105467    ** but not actually sorted. Either way, record the fact that the
105468    ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
105469    ** variable.  */
105470    if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
105471      orderByGrp = 1;
105472    }
105473
105474    /* Create a label to jump to when we want to abort the query */
105475    addrEnd = sqlite3VdbeMakeLabel(v);
105476
105477    /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
105478    ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
105479    ** SELECT statement.
105480    */
105481    memset(&sNC, 0, sizeof(sNC));
105482    sNC.pParse = pParse;
105483    sNC.pSrcList = pTabList;
105484    sNC.pAggInfo = &sAggInfo;
105485    sAggInfo.mnReg = pParse->nMem+1;
105486    sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
105487    sAggInfo.pGroupBy = pGroupBy;
105488    sqlite3ExprAnalyzeAggList(&sNC, pEList);
105489    sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
105490    if( pHaving ){
105491      sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
105492    }
105493    sAggInfo.nAccumulator = sAggInfo.nColumn;
105494    for(i=0; i<sAggInfo.nFunc; i++){
105495      assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
105496      sNC.ncFlags |= NC_InAggFunc;
105497      sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
105498      sNC.ncFlags &= ~NC_InAggFunc;
105499    }
105500    sAggInfo.mxReg = pParse->nMem;
105501    if( db->mallocFailed ) goto select_end;
105502
105503    /* Processing for aggregates with GROUP BY is very different and
105504    ** much more complex than aggregates without a GROUP BY.
105505    */
105506    if( pGroupBy ){
105507      KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
105508      int j1;             /* A-vs-B comparision jump */
105509      int addrOutputRow;  /* Start of subroutine that outputs a result row */
105510      int regOutputRow;   /* Return address register for output subroutine */
105511      int addrSetAbort;   /* Set the abort flag and return */
105512      int addrTopOfLoop;  /* Top of the input loop */
105513      int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
105514      int addrReset;      /* Subroutine for resetting the accumulator */
105515      int regReset;       /* Return address register for reset subroutine */
105516
105517      /* If there is a GROUP BY clause we might need a sorting index to
105518      ** implement it.  Allocate that sorting index now.  If it turns out
105519      ** that we do not need it after all, the OP_SorterOpen instruction
105520      ** will be converted into a Noop.
105521      */
105522      sAggInfo.sortingIdx = pParse->nTab++;
105523      pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, 0);
105524      addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
105525          sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
105526          0, (char*)pKeyInfo, P4_KEYINFO);
105527
105528      /* Initialize memory locations used by GROUP BY aggregate processing
105529      */
105530      iUseFlag = ++pParse->nMem;
105531      iAbortFlag = ++pParse->nMem;
105532      regOutputRow = ++pParse->nMem;
105533      addrOutputRow = sqlite3VdbeMakeLabel(v);
105534      regReset = ++pParse->nMem;
105535      addrReset = sqlite3VdbeMakeLabel(v);
105536      iAMem = pParse->nMem + 1;
105537      pParse->nMem += pGroupBy->nExpr;
105538      iBMem = pParse->nMem + 1;
105539      pParse->nMem += pGroupBy->nExpr;
105540      sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
105541      VdbeComment((v, "clear abort flag"));
105542      sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
105543      VdbeComment((v, "indicate accumulator empty"));
105544      sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
105545
105546      /* Begin a loop that will extract all source rows in GROUP BY order.
105547      ** This might involve two separate loops with an OP_Sort in between, or
105548      ** it might be a single loop that uses an index to extract information
105549      ** in the right order to begin with.
105550      */
105551      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
105552      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
105553          WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
105554      );
105555      if( pWInfo==0 ) goto select_end;
105556      if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
105557        /* The optimizer is able to deliver rows in group by order so
105558        ** we do not have to sort.  The OP_OpenEphemeral table will be
105559        ** cancelled later because we still need to use the pKeyInfo
105560        */
105561        groupBySort = 0;
105562      }else{
105563        /* Rows are coming out in undetermined order.  We have to push
105564        ** each row into a sorting index, terminate the first loop,
105565        ** then loop over the sorting index in order to get the output
105566        ** in sorted order
105567        */
105568        int regBase;
105569        int regRecord;
105570        int nCol;
105571        int nGroupBy;
105572
105573        explainTempTable(pParse,
105574            (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
105575                    "DISTINCT" : "GROUP BY");
105576
105577        groupBySort = 1;
105578        nGroupBy = pGroupBy->nExpr;
105579        nCol = nGroupBy + 1;
105580        j = nGroupBy+1;
105581        for(i=0; i<sAggInfo.nColumn; i++){
105582          if( sAggInfo.aCol[i].iSorterColumn>=j ){
105583            nCol++;
105584            j++;
105585          }
105586        }
105587        regBase = sqlite3GetTempRange(pParse, nCol);
105588        sqlite3ExprCacheClear(pParse);
105589        sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
105590        sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
105591        j = nGroupBy+1;
105592        for(i=0; i<sAggInfo.nColumn; i++){
105593          struct AggInfo_col *pCol = &sAggInfo.aCol[i];
105594          if( pCol->iSorterColumn>=j ){
105595            int r1 = j + regBase;
105596            int r2;
105597
105598            r2 = sqlite3ExprCodeGetColumn(pParse,
105599                               pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
105600            if( r1!=r2 ){
105601              sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
105602            }
105603            j++;
105604          }
105605        }
105606        regRecord = sqlite3GetTempReg(pParse);
105607        sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
105608        sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
105609        sqlite3ReleaseTempReg(pParse, regRecord);
105610        sqlite3ReleaseTempRange(pParse, regBase, nCol);
105611        sqlite3WhereEnd(pWInfo);
105612        sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
105613        sortOut = sqlite3GetTempReg(pParse);
105614        sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
105615        sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
105616        VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
105617        sAggInfo.useSortingIdx = 1;
105618        sqlite3ExprCacheClear(pParse);
105619
105620      }
105621
105622      /* If the index or temporary table used by the GROUP BY sort
105623      ** will naturally deliver rows in the order required by the ORDER BY
105624      ** clause, cancel the ephemeral table open coded earlier.
105625      **
105626      ** This is an optimization - the correct answer should result regardless.
105627      ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
105628      ** disable this optimization for testing purposes.  */
105629      if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
105630       && (groupBySort || sqlite3WhereIsSorted(pWInfo))
105631      ){
105632        sSort.pOrderBy = 0;
105633        sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
105634      }
105635
105636      /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
105637      ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
105638      ** Then compare the current GROUP BY terms against the GROUP BY terms
105639      ** from the previous row currently stored in a0, a1, a2...
105640      */
105641      addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
105642      sqlite3ExprCacheClear(pParse);
105643      if( groupBySort ){
105644        sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
105645      }
105646      for(j=0; j<pGroupBy->nExpr; j++){
105647        if( groupBySort ){
105648          sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
105649          if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
105650        }else{
105651          sAggInfo.directMode = 1;
105652          sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
105653        }
105654      }
105655      sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
105656                          (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
105657      j1 = sqlite3VdbeCurrentAddr(v);
105658      sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1); VdbeCoverage(v);
105659
105660      /* Generate code that runs whenever the GROUP BY changes.
105661      ** Changes in the GROUP BY are detected by the previous code
105662      ** block.  If there were no changes, this block is skipped.
105663      **
105664      ** This code copies current group by terms in b0,b1,b2,...
105665      ** over to a0,a1,a2.  It then calls the output subroutine
105666      ** and resets the aggregate accumulator registers in preparation
105667      ** for the next GROUP BY batch.
105668      */
105669      sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
105670      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
105671      VdbeComment((v, "output one row"));
105672      sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
105673      VdbeComment((v, "check abort flag"));
105674      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
105675      VdbeComment((v, "reset accumulator"));
105676
105677      /* Update the aggregate accumulators based on the content of
105678      ** the current row
105679      */
105680      sqlite3VdbeJumpHere(v, j1);
105681      updateAccumulator(pParse, &sAggInfo);
105682      sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
105683      VdbeComment((v, "indicate data in accumulator"));
105684
105685      /* End of the loop
105686      */
105687      if( groupBySort ){
105688        sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
105689        VdbeCoverage(v);
105690      }else{
105691        sqlite3WhereEnd(pWInfo);
105692        sqlite3VdbeChangeToNoop(v, addrSortingIdx);
105693      }
105694
105695      /* Output the final row of result
105696      */
105697      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
105698      VdbeComment((v, "output final row"));
105699
105700      /* Jump over the subroutines
105701      */
105702      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
105703
105704      /* Generate a subroutine that outputs a single row of the result
105705      ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
105706      ** is less than or equal to zero, the subroutine is a no-op.  If
105707      ** the processing calls for the query to abort, this subroutine
105708      ** increments the iAbortFlag memory location before returning in
105709      ** order to signal the caller to abort.
105710      */
105711      addrSetAbort = sqlite3VdbeCurrentAddr(v);
105712      sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
105713      VdbeComment((v, "set abort flag"));
105714      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
105715      sqlite3VdbeResolveLabel(v, addrOutputRow);
105716      addrOutputRow = sqlite3VdbeCurrentAddr(v);
105717      sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); VdbeCoverage(v);
105718      VdbeComment((v, "Groupby result generator entry point"));
105719      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
105720      finalizeAggFunctions(pParse, &sAggInfo);
105721      sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
105722      selectInnerLoop(pParse, p, p->pEList, -1, &sSort,
105723                      &sDistinct, pDest,
105724                      addrOutputRow+1, addrSetAbort);
105725      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
105726      VdbeComment((v, "end groupby result generator"));
105727
105728      /* Generate a subroutine that will reset the group-by accumulator
105729      */
105730      sqlite3VdbeResolveLabel(v, addrReset);
105731      resetAccumulator(pParse, &sAggInfo);
105732      sqlite3VdbeAddOp1(v, OP_Return, regReset);
105733
105734    } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
105735    else {
105736      ExprList *pDel = 0;
105737#ifndef SQLITE_OMIT_BTREECOUNT
105738      Table *pTab;
105739      if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
105740        /* If isSimpleCount() returns a pointer to a Table structure, then
105741        ** the SQL statement is of the form:
105742        **
105743        **   SELECT count(*) FROM <tbl>
105744        **
105745        ** where the Table structure returned represents table <tbl>.
105746        **
105747        ** This statement is so common that it is optimized specially. The
105748        ** OP_Count instruction is executed either on the intkey table that
105749        ** contains the data for table <tbl> or on one of its indexes. It
105750        ** is better to execute the op on an index, as indexes are almost
105751        ** always spread across less pages than their corresponding tables.
105752        */
105753        const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
105754        const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
105755        Index *pIdx;                         /* Iterator variable */
105756        KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
105757        Index *pBest = 0;                    /* Best index found so far */
105758        int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
105759
105760        sqlite3CodeVerifySchema(pParse, iDb);
105761        sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
105762
105763        /* Search for the index that has the lowest scan cost.
105764        **
105765        ** (2011-04-15) Do not do a full scan of an unordered index.
105766        **
105767        ** (2013-10-03) Do not count the entries in a partial index.
105768        **
105769        ** In practice the KeyInfo structure will not be used. It is only
105770        ** passed to keep OP_OpenRead happy.
105771        */
105772        if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
105773        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
105774          if( pIdx->bUnordered==0
105775           && pIdx->szIdxRow<pTab->szTabRow
105776           && pIdx->pPartIdxWhere==0
105777           && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
105778          ){
105779            pBest = pIdx;
105780          }
105781        }
105782        if( pBest ){
105783          iRoot = pBest->tnum;
105784          pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
105785        }
105786
105787        /* Open a read-only cursor, execute the OP_Count, close the cursor. */
105788        sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
105789        if( pKeyInfo ){
105790          sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
105791        }
105792        sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
105793        sqlite3VdbeAddOp1(v, OP_Close, iCsr);
105794        explainSimpleCount(pParse, pTab, pBest);
105795      }else
105796#endif /* SQLITE_OMIT_BTREECOUNT */
105797      {
105798        /* Check if the query is of one of the following forms:
105799        **
105800        **   SELECT min(x) FROM ...
105801        **   SELECT max(x) FROM ...
105802        **
105803        ** If it is, then ask the code in where.c to attempt to sort results
105804        ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
105805        ** If where.c is able to produce results sorted in this order, then
105806        ** add vdbe code to break out of the processing loop after the
105807        ** first iteration (since the first iteration of the loop is
105808        ** guaranteed to operate on the row with the minimum or maximum
105809        ** value of x, the only row required).
105810        **
105811        ** A special flag must be passed to sqlite3WhereBegin() to slightly
105812        ** modify behavior as follows:
105813        **
105814        **   + If the query is a "SELECT min(x)", then the loop coded by
105815        **     where.c should not iterate over any values with a NULL value
105816        **     for x.
105817        **
105818        **   + The optimizer code in where.c (the thing that decides which
105819        **     index or indices to use) should place a different priority on
105820        **     satisfying the 'ORDER BY' clause than it does in other cases.
105821        **     Refer to code and comments in where.c for details.
105822        */
105823        ExprList *pMinMax = 0;
105824        u8 flag = WHERE_ORDERBY_NORMAL;
105825
105826        assert( p->pGroupBy==0 );
105827        assert( flag==0 );
105828        if( p->pHaving==0 ){
105829          flag = minMaxQuery(&sAggInfo, &pMinMax);
105830        }
105831        assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
105832
105833        if( flag ){
105834          pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
105835          pDel = pMinMax;
105836          if( pMinMax && !db->mallocFailed ){
105837            pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
105838            pMinMax->a[0].pExpr->op = TK_COLUMN;
105839          }
105840        }
105841
105842        /* This case runs if the aggregate has no GROUP BY clause.  The
105843        ** processing is much simpler since there is only a single row
105844        ** of output.
105845        */
105846        resetAccumulator(pParse, &sAggInfo);
105847        pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
105848        if( pWInfo==0 ){
105849          sqlite3ExprListDelete(db, pDel);
105850          goto select_end;
105851        }
105852        updateAccumulator(pParse, &sAggInfo);
105853        assert( pMinMax==0 || pMinMax->nExpr==1 );
105854        if( sqlite3WhereIsOrdered(pWInfo)>0 ){
105855          sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3WhereBreakLabel(pWInfo));
105856          VdbeComment((v, "%s() by index",
105857                (flag==WHERE_ORDERBY_MIN?"min":"max")));
105858        }
105859        sqlite3WhereEnd(pWInfo);
105860        finalizeAggFunctions(pParse, &sAggInfo);
105861      }
105862
105863      sSort.pOrderBy = 0;
105864      sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
105865      selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
105866                      pDest, addrEnd, addrEnd);
105867      sqlite3ExprListDelete(db, pDel);
105868    }
105869    sqlite3VdbeResolveLabel(v, addrEnd);
105870
105871  } /* endif aggregate query */
105872
105873  if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
105874    explainTempTable(pParse, "DISTINCT");
105875  }
105876
105877  /* If there is an ORDER BY clause, then we need to sort the results
105878  ** and send them to the callback one by one.
105879  */
105880  if( sSort.pOrderBy ){
105881    explainTempTable(pParse, sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
105882    generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
105883  }
105884
105885  /* Jump here to skip this query
105886  */
105887  sqlite3VdbeResolveLabel(v, iEnd);
105888
105889  /* The SELECT was successfully coded.   Set the return code to 0
105890  ** to indicate no errors.
105891  */
105892  rc = 0;
105893
105894  /* Control jumps to here if an error is encountered above, or upon
105895  ** successful coding of the SELECT.
105896  */
105897select_end:
105898  explainSetInteger(pParse->iSelectId, iRestoreSelectId);
105899
105900  /* Identify column names if results of the SELECT are to be output.
105901  */
105902  if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
105903    generateColumnNames(pParse, pTabList, pEList);
105904  }
105905
105906  sqlite3DbFree(db, sAggInfo.aCol);
105907  sqlite3DbFree(db, sAggInfo.aFunc);
105908  return rc;
105909}
105910
105911#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
105912/*
105913** Generate a human-readable description of a the Select object.
105914*/
105915static void explainOneSelect(Vdbe *pVdbe, Select *p){
105916  sqlite3ExplainPrintf(pVdbe, "SELECT ");
105917  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
105918    if( p->selFlags & SF_Distinct ){
105919      sqlite3ExplainPrintf(pVdbe, "DISTINCT ");
105920    }
105921    if( p->selFlags & SF_Aggregate ){
105922      sqlite3ExplainPrintf(pVdbe, "agg_flag ");
105923    }
105924    sqlite3ExplainNL(pVdbe);
105925    sqlite3ExplainPrintf(pVdbe, "   ");
105926  }
105927  sqlite3ExplainExprList(pVdbe, p->pEList);
105928  sqlite3ExplainNL(pVdbe);
105929  if( p->pSrc && p->pSrc->nSrc ){
105930    int i;
105931    sqlite3ExplainPrintf(pVdbe, "FROM ");
105932    sqlite3ExplainPush(pVdbe);
105933    for(i=0; i<p->pSrc->nSrc; i++){
105934      struct SrcList_item *pItem = &p->pSrc->a[i];
105935      sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor);
105936      if( pItem->pSelect ){
105937        sqlite3ExplainSelect(pVdbe, pItem->pSelect);
105938        if( pItem->pTab ){
105939          sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName);
105940        }
105941      }else if( pItem->zName ){
105942        sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName);
105943      }
105944      if( pItem->zAlias ){
105945        sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias);
105946      }
105947      if( pItem->jointype & JT_LEFT ){
105948        sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN");
105949      }
105950      sqlite3ExplainNL(pVdbe);
105951    }
105952    sqlite3ExplainPop(pVdbe);
105953  }
105954  if( p->pWhere ){
105955    sqlite3ExplainPrintf(pVdbe, "WHERE ");
105956    sqlite3ExplainExpr(pVdbe, p->pWhere);
105957    sqlite3ExplainNL(pVdbe);
105958  }
105959  if( p->pGroupBy ){
105960    sqlite3ExplainPrintf(pVdbe, "GROUPBY ");
105961    sqlite3ExplainExprList(pVdbe, p->pGroupBy);
105962    sqlite3ExplainNL(pVdbe);
105963  }
105964  if( p->pHaving ){
105965    sqlite3ExplainPrintf(pVdbe, "HAVING ");
105966    sqlite3ExplainExpr(pVdbe, p->pHaving);
105967    sqlite3ExplainNL(pVdbe);
105968  }
105969  if( p->pOrderBy ){
105970    sqlite3ExplainPrintf(pVdbe, "ORDERBY ");
105971    sqlite3ExplainExprList(pVdbe, p->pOrderBy);
105972    sqlite3ExplainNL(pVdbe);
105973  }
105974  if( p->pLimit ){
105975    sqlite3ExplainPrintf(pVdbe, "LIMIT ");
105976    sqlite3ExplainExpr(pVdbe, p->pLimit);
105977    sqlite3ExplainNL(pVdbe);
105978  }
105979  if( p->pOffset ){
105980    sqlite3ExplainPrintf(pVdbe, "OFFSET ");
105981    sqlite3ExplainExpr(pVdbe, p->pOffset);
105982    sqlite3ExplainNL(pVdbe);
105983  }
105984}
105985SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){
105986  if( p==0 ){
105987    sqlite3ExplainPrintf(pVdbe, "(null-select)");
105988    return;
105989  }
105990  sqlite3ExplainPush(pVdbe);
105991  while( p ){
105992    explainOneSelect(pVdbe, p);
105993    p = p->pNext;
105994    if( p==0 ) break;
105995    sqlite3ExplainNL(pVdbe);
105996    sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op));
105997  }
105998  sqlite3ExplainPrintf(pVdbe, "END");
105999  sqlite3ExplainPop(pVdbe);
106000}
106001
106002/* End of the structure debug printing code
106003*****************************************************************************/
106004#endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
106005
106006/************** End of select.c **********************************************/
106007/************** Begin file table.c *******************************************/
106008/*
106009** 2001 September 15
106010**
106011** The author disclaims copyright to this source code.  In place of
106012** a legal notice, here is a blessing:
106013**
106014**    May you do good and not evil.
106015**    May you find forgiveness for yourself and forgive others.
106016**    May you share freely, never taking more than you give.
106017**
106018*************************************************************************
106019** This file contains the sqlite3_get_table() and sqlite3_free_table()
106020** interface routines.  These are just wrappers around the main
106021** interface routine of sqlite3_exec().
106022**
106023** These routines are in a separate files so that they will not be linked
106024** if they are not used.
106025*/
106026/* #include <stdlib.h> */
106027/* #include <string.h> */
106028
106029#ifndef SQLITE_OMIT_GET_TABLE
106030
106031/*
106032** This structure is used to pass data from sqlite3_get_table() through
106033** to the callback function is uses to build the result.
106034*/
106035typedef struct TabResult {
106036  char **azResult;   /* Accumulated output */
106037  char *zErrMsg;     /* Error message text, if an error occurs */
106038  int nAlloc;        /* Slots allocated for azResult[] */
106039  int nRow;          /* Number of rows in the result */
106040  int nColumn;       /* Number of columns in the result */
106041  int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
106042  int rc;            /* Return code from sqlite3_exec() */
106043} TabResult;
106044
106045/*
106046** This routine is called once for each row in the result table.  Its job
106047** is to fill in the TabResult structure appropriately, allocating new
106048** memory as necessary.
106049*/
106050static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
106051  TabResult *p = (TabResult*)pArg;  /* Result accumulator */
106052  int need;                         /* Slots needed in p->azResult[] */
106053  int i;                            /* Loop counter */
106054  char *z;                          /* A single column of result */
106055
106056  /* Make sure there is enough space in p->azResult to hold everything
106057  ** we need to remember from this invocation of the callback.
106058  */
106059  if( p->nRow==0 && argv!=0 ){
106060    need = nCol*2;
106061  }else{
106062    need = nCol;
106063  }
106064  if( p->nData + need > p->nAlloc ){
106065    char **azNew;
106066    p->nAlloc = p->nAlloc*2 + need;
106067    azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
106068    if( azNew==0 ) goto malloc_failed;
106069    p->azResult = azNew;
106070  }
106071
106072  /* If this is the first row, then generate an extra row containing
106073  ** the names of all columns.
106074  */
106075  if( p->nRow==0 ){
106076    p->nColumn = nCol;
106077    for(i=0; i<nCol; i++){
106078      z = sqlite3_mprintf("%s", colv[i]);
106079      if( z==0 ) goto malloc_failed;
106080      p->azResult[p->nData++] = z;
106081    }
106082  }else if( p->nColumn!=nCol ){
106083    sqlite3_free(p->zErrMsg);
106084    p->zErrMsg = sqlite3_mprintf(
106085       "sqlite3_get_table() called with two or more incompatible queries"
106086    );
106087    p->rc = SQLITE_ERROR;
106088    return 1;
106089  }
106090
106091  /* Copy over the row data
106092  */
106093  if( argv!=0 ){
106094    for(i=0; i<nCol; i++){
106095      if( argv[i]==0 ){
106096        z = 0;
106097      }else{
106098        int n = sqlite3Strlen30(argv[i])+1;
106099        z = sqlite3_malloc( n );
106100        if( z==0 ) goto malloc_failed;
106101        memcpy(z, argv[i], n);
106102      }
106103      p->azResult[p->nData++] = z;
106104    }
106105    p->nRow++;
106106  }
106107  return 0;
106108
106109malloc_failed:
106110  p->rc = SQLITE_NOMEM;
106111  return 1;
106112}
106113
106114/*
106115** Query the database.  But instead of invoking a callback for each row,
106116** malloc() for space to hold the result and return the entire results
106117** at the conclusion of the call.
106118**
106119** The result that is written to ***pazResult is held in memory obtained
106120** from malloc().  But the caller cannot free this memory directly.
106121** Instead, the entire table should be passed to sqlite3_free_table() when
106122** the calling procedure is finished using it.
106123*/
106124SQLITE_API int sqlite3_get_table(
106125  sqlite3 *db,                /* The database on which the SQL executes */
106126  const char *zSql,           /* The SQL to be executed */
106127  char ***pazResult,          /* Write the result table here */
106128  int *pnRow,                 /* Write the number of rows in the result here */
106129  int *pnColumn,              /* Write the number of columns of result here */
106130  char **pzErrMsg             /* Write error messages here */
106131){
106132  int rc;
106133  TabResult res;
106134
106135  *pazResult = 0;
106136  if( pnColumn ) *pnColumn = 0;
106137  if( pnRow ) *pnRow = 0;
106138  if( pzErrMsg ) *pzErrMsg = 0;
106139  res.zErrMsg = 0;
106140  res.nRow = 0;
106141  res.nColumn = 0;
106142  res.nData = 1;
106143  res.nAlloc = 20;
106144  res.rc = SQLITE_OK;
106145  res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
106146  if( res.azResult==0 ){
106147     db->errCode = SQLITE_NOMEM;
106148     return SQLITE_NOMEM;
106149  }
106150  res.azResult[0] = 0;
106151  rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
106152  assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
106153  res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
106154  if( (rc&0xff)==SQLITE_ABORT ){
106155    sqlite3_free_table(&res.azResult[1]);
106156    if( res.zErrMsg ){
106157      if( pzErrMsg ){
106158        sqlite3_free(*pzErrMsg);
106159        *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
106160      }
106161      sqlite3_free(res.zErrMsg);
106162    }
106163    db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
106164    return res.rc;
106165  }
106166  sqlite3_free(res.zErrMsg);
106167  if( rc!=SQLITE_OK ){
106168    sqlite3_free_table(&res.azResult[1]);
106169    return rc;
106170  }
106171  if( res.nAlloc>res.nData ){
106172    char **azNew;
106173    azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
106174    if( azNew==0 ){
106175      sqlite3_free_table(&res.azResult[1]);
106176      db->errCode = SQLITE_NOMEM;
106177      return SQLITE_NOMEM;
106178    }
106179    res.azResult = azNew;
106180  }
106181  *pazResult = &res.azResult[1];
106182  if( pnColumn ) *pnColumn = res.nColumn;
106183  if( pnRow ) *pnRow = res.nRow;
106184  return rc;
106185}
106186
106187/*
106188** This routine frees the space the sqlite3_get_table() malloced.
106189*/
106190SQLITE_API void sqlite3_free_table(
106191  char **azResult            /* Result returned from from sqlite3_get_table() */
106192){
106193  if( azResult ){
106194    int i, n;
106195    azResult--;
106196    assert( azResult!=0 );
106197    n = SQLITE_PTR_TO_INT(azResult[0]);
106198    for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
106199    sqlite3_free(azResult);
106200  }
106201}
106202
106203#endif /* SQLITE_OMIT_GET_TABLE */
106204
106205/************** End of table.c ***********************************************/
106206/************** Begin file trigger.c *****************************************/
106207/*
106208**
106209** The author disclaims copyright to this source code.  In place of
106210** a legal notice, here is a blessing:
106211**
106212**    May you do good and not evil.
106213**    May you find forgiveness for yourself and forgive others.
106214**    May you share freely, never taking more than you give.
106215**
106216*************************************************************************
106217** This file contains the implementation for TRIGGERs
106218*/
106219
106220#ifndef SQLITE_OMIT_TRIGGER
106221/*
106222** Delete a linked list of TriggerStep structures.
106223*/
106224SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
106225  while( pTriggerStep ){
106226    TriggerStep * pTmp = pTriggerStep;
106227    pTriggerStep = pTriggerStep->pNext;
106228
106229    sqlite3ExprDelete(db, pTmp->pWhere);
106230    sqlite3ExprListDelete(db, pTmp->pExprList);
106231    sqlite3SelectDelete(db, pTmp->pSelect);
106232    sqlite3IdListDelete(db, pTmp->pIdList);
106233
106234    sqlite3DbFree(db, pTmp);
106235  }
106236}
106237
106238/*
106239** Given table pTab, return a list of all the triggers attached to
106240** the table. The list is connected by Trigger.pNext pointers.
106241**
106242** All of the triggers on pTab that are in the same database as pTab
106243** are already attached to pTab->pTrigger.  But there might be additional
106244** triggers on pTab in the TEMP schema.  This routine prepends all
106245** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
106246** and returns the combined list.
106247**
106248** To state it another way:  This routine returns a list of all triggers
106249** that fire off of pTab.  The list will include any TEMP triggers on
106250** pTab as well as the triggers lised in pTab->pTrigger.
106251*/
106252SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
106253  Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
106254  Trigger *pList = 0;                  /* List of triggers to return */
106255
106256  if( pParse->disableTriggers ){
106257    return 0;
106258  }
106259
106260  if( pTmpSchema!=pTab->pSchema ){
106261    HashElem *p;
106262    assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
106263    for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
106264      Trigger *pTrig = (Trigger *)sqliteHashData(p);
106265      if( pTrig->pTabSchema==pTab->pSchema
106266       && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
106267      ){
106268        pTrig->pNext = (pList ? pList : pTab->pTrigger);
106269        pList = pTrig;
106270      }
106271    }
106272  }
106273
106274  return (pList ? pList : pTab->pTrigger);
106275}
106276
106277/*
106278** This is called by the parser when it sees a CREATE TRIGGER statement
106279** up to the point of the BEGIN before the trigger actions.  A Trigger
106280** structure is generated based on the information available and stored
106281** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
106282** sqlite3FinishTrigger() function is called to complete the trigger
106283** construction process.
106284*/
106285SQLITE_PRIVATE void sqlite3BeginTrigger(
106286  Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
106287  Token *pName1,      /* The name of the trigger */
106288  Token *pName2,      /* The name of the trigger */
106289  int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
106290  int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
106291  IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
106292  SrcList *pTableName,/* The name of the table/view the trigger applies to */
106293  Expr *pWhen,        /* WHEN clause */
106294  int isTemp,         /* True if the TEMPORARY keyword is present */
106295  int noErr           /* Suppress errors if the trigger already exists */
106296){
106297  Trigger *pTrigger = 0;  /* The new trigger */
106298  Table *pTab;            /* Table that the trigger fires off of */
106299  char *zName = 0;        /* Name of the trigger */
106300  sqlite3 *db = pParse->db;  /* The database connection */
106301  int iDb;                /* The database to store the trigger in */
106302  Token *pName;           /* The unqualified db name */
106303  DbFixer sFix;           /* State vector for the DB fixer */
106304  int iTabDb;             /* Index of the database holding pTab */
106305
106306  assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
106307  assert( pName2!=0 );
106308  assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
106309  assert( op>0 && op<0xff );
106310  if( isTemp ){
106311    /* If TEMP was specified, then the trigger name may not be qualified. */
106312    if( pName2->n>0 ){
106313      sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
106314      goto trigger_cleanup;
106315    }
106316    iDb = 1;
106317    pName = pName1;
106318  }else{
106319    /* Figure out the db that the trigger will be created in */
106320    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
106321    if( iDb<0 ){
106322      goto trigger_cleanup;
106323    }
106324  }
106325  if( !pTableName || db->mallocFailed ){
106326    goto trigger_cleanup;
106327  }
106328
106329  /* A long-standing parser bug is that this syntax was allowed:
106330  **
106331  **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
106332  **                                                 ^^^^^^^^
106333  **
106334  ** To maintain backwards compatibility, ignore the database
106335  ** name on pTableName if we are reparsing our of SQLITE_MASTER.
106336  */
106337  if( db->init.busy && iDb!=1 ){
106338    sqlite3DbFree(db, pTableName->a[0].zDatabase);
106339    pTableName->a[0].zDatabase = 0;
106340  }
106341
106342  /* If the trigger name was unqualified, and the table is a temp table,
106343  ** then set iDb to 1 to create the trigger in the temporary database.
106344  ** If sqlite3SrcListLookup() returns 0, indicating the table does not
106345  ** exist, the error is caught by the block below.
106346  */
106347  pTab = sqlite3SrcListLookup(pParse, pTableName);
106348  if( db->init.busy==0 && pName2->n==0 && pTab
106349        && pTab->pSchema==db->aDb[1].pSchema ){
106350    iDb = 1;
106351  }
106352
106353  /* Ensure the table name matches database name and that the table exists */
106354  if( db->mallocFailed ) goto trigger_cleanup;
106355  assert( pTableName->nSrc==1 );
106356  sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
106357  if( sqlite3FixSrcList(&sFix, pTableName) ){
106358    goto trigger_cleanup;
106359  }
106360  pTab = sqlite3SrcListLookup(pParse, pTableName);
106361  if( !pTab ){
106362    /* The table does not exist. */
106363    if( db->init.iDb==1 ){
106364      /* Ticket #3810.
106365      ** Normally, whenever a table is dropped, all associated triggers are
106366      ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
106367      ** and the table is dropped by a different database connection, the
106368      ** trigger is not visible to the database connection that does the
106369      ** drop so the trigger cannot be dropped.  This results in an
106370      ** "orphaned trigger" - a trigger whose associated table is missing.
106371      */
106372      db->init.orphanTrigger = 1;
106373    }
106374    goto trigger_cleanup;
106375  }
106376  if( IsVirtual(pTab) ){
106377    sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
106378    goto trigger_cleanup;
106379  }
106380
106381  /* Check that the trigger name is not reserved and that no trigger of the
106382  ** specified name exists */
106383  zName = sqlite3NameFromToken(db, pName);
106384  if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
106385    goto trigger_cleanup;
106386  }
106387  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
106388  if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
106389                      zName, sqlite3Strlen30(zName)) ){
106390    if( !noErr ){
106391      sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
106392    }else{
106393      assert( !db->init.busy );
106394      sqlite3CodeVerifySchema(pParse, iDb);
106395    }
106396    goto trigger_cleanup;
106397  }
106398
106399  /* Do not create a trigger on a system table */
106400  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
106401    sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
106402    pParse->nErr++;
106403    goto trigger_cleanup;
106404  }
106405
106406  /* INSTEAD of triggers are only for views and views only support INSTEAD
106407  ** of triggers.
106408  */
106409  if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
106410    sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
106411        (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
106412    goto trigger_cleanup;
106413  }
106414  if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
106415    sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
106416        " trigger on table: %S", pTableName, 0);
106417    goto trigger_cleanup;
106418  }
106419  iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
106420
106421#ifndef SQLITE_OMIT_AUTHORIZATION
106422  {
106423    int code = SQLITE_CREATE_TRIGGER;
106424    const char *zDb = db->aDb[iTabDb].zName;
106425    const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
106426    if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
106427    if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
106428      goto trigger_cleanup;
106429    }
106430    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
106431      goto trigger_cleanup;
106432    }
106433  }
106434#endif
106435
106436  /* INSTEAD OF triggers can only appear on views and BEFORE triggers
106437  ** cannot appear on views.  So we might as well translate every
106438  ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
106439  ** elsewhere.
106440  */
106441  if (tr_tm == TK_INSTEAD){
106442    tr_tm = TK_BEFORE;
106443  }
106444
106445  /* Build the Trigger object */
106446  pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
106447  if( pTrigger==0 ) goto trigger_cleanup;
106448  pTrigger->zName = zName;
106449  zName = 0;
106450  pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
106451  pTrigger->pSchema = db->aDb[iDb].pSchema;
106452  pTrigger->pTabSchema = pTab->pSchema;
106453  pTrigger->op = (u8)op;
106454  pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
106455  pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
106456  pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
106457  assert( pParse->pNewTrigger==0 );
106458  pParse->pNewTrigger = pTrigger;
106459
106460trigger_cleanup:
106461  sqlite3DbFree(db, zName);
106462  sqlite3SrcListDelete(db, pTableName);
106463  sqlite3IdListDelete(db, pColumns);
106464  sqlite3ExprDelete(db, pWhen);
106465  if( !pParse->pNewTrigger ){
106466    sqlite3DeleteTrigger(db, pTrigger);
106467  }else{
106468    assert( pParse->pNewTrigger==pTrigger );
106469  }
106470}
106471
106472/*
106473** This routine is called after all of the trigger actions have been parsed
106474** in order to complete the process of building the trigger.
106475*/
106476SQLITE_PRIVATE void sqlite3FinishTrigger(
106477  Parse *pParse,          /* Parser context */
106478  TriggerStep *pStepList, /* The triggered program */
106479  Token *pAll             /* Token that describes the complete CREATE TRIGGER */
106480){
106481  Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
106482  char *zName;                            /* Name of trigger */
106483  sqlite3 *db = pParse->db;               /* The database */
106484  DbFixer sFix;                           /* Fixer object */
106485  int iDb;                                /* Database containing the trigger */
106486  Token nameToken;                        /* Trigger name for error reporting */
106487
106488  pParse->pNewTrigger = 0;
106489  if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
106490  zName = pTrig->zName;
106491  iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
106492  pTrig->step_list = pStepList;
106493  while( pStepList ){
106494    pStepList->pTrig = pTrig;
106495    pStepList = pStepList->pNext;
106496  }
106497  nameToken.z = pTrig->zName;
106498  nameToken.n = sqlite3Strlen30(nameToken.z);
106499  sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
106500  if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
106501   || sqlite3FixExpr(&sFix, pTrig->pWhen)
106502  ){
106503    goto triggerfinish_cleanup;
106504  }
106505
106506  /* if we are not initializing,
106507  ** build the sqlite_master entry
106508  */
106509  if( !db->init.busy ){
106510    Vdbe *v;
106511    char *z;
106512
106513    /* Make an entry in the sqlite_master table */
106514    v = sqlite3GetVdbe(pParse);
106515    if( v==0 ) goto triggerfinish_cleanup;
106516    sqlite3BeginWriteOperation(pParse, 0, iDb);
106517    z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
106518    sqlite3NestedParse(pParse,
106519       "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
106520       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
106521       pTrig->table, z);
106522    sqlite3DbFree(db, z);
106523    sqlite3ChangeCookie(pParse, iDb);
106524    sqlite3VdbeAddParseSchemaOp(v, iDb,
106525        sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
106526  }
106527
106528  if( db->init.busy ){
106529    Trigger *pLink = pTrig;
106530    Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
106531    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
106532    pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
106533    if( pTrig ){
106534      db->mallocFailed = 1;
106535    }else if( pLink->pSchema==pLink->pTabSchema ){
106536      Table *pTab;
106537      int n = sqlite3Strlen30(pLink->table);
106538      pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
106539      assert( pTab!=0 );
106540      pLink->pNext = pTab->pTrigger;
106541      pTab->pTrigger = pLink;
106542    }
106543  }
106544
106545triggerfinish_cleanup:
106546  sqlite3DeleteTrigger(db, pTrig);
106547  assert( !pParse->pNewTrigger );
106548  sqlite3DeleteTriggerStep(db, pStepList);
106549}
106550
106551/*
106552** Turn a SELECT statement (that the pSelect parameter points to) into
106553** a trigger step.  Return a pointer to a TriggerStep structure.
106554**
106555** The parser calls this routine when it finds a SELECT statement in
106556** body of a TRIGGER.
106557*/
106558SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
106559  TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
106560  if( pTriggerStep==0 ) {
106561    sqlite3SelectDelete(db, pSelect);
106562    return 0;
106563  }
106564  pTriggerStep->op = TK_SELECT;
106565  pTriggerStep->pSelect = pSelect;
106566  pTriggerStep->orconf = OE_Default;
106567  return pTriggerStep;
106568}
106569
106570/*
106571** Allocate space to hold a new trigger step.  The allocated space
106572** holds both the TriggerStep object and the TriggerStep.target.z string.
106573**
106574** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
106575*/
106576static TriggerStep *triggerStepAllocate(
106577  sqlite3 *db,                /* Database connection */
106578  u8 op,                      /* Trigger opcode */
106579  Token *pName                /* The target name */
106580){
106581  TriggerStep *pTriggerStep;
106582
106583  pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
106584  if( pTriggerStep ){
106585    char *z = (char*)&pTriggerStep[1];
106586    memcpy(z, pName->z, pName->n);
106587    pTriggerStep->target.z = z;
106588    pTriggerStep->target.n = pName->n;
106589    pTriggerStep->op = op;
106590  }
106591  return pTriggerStep;
106592}
106593
106594/*
106595** Build a trigger step out of an INSERT statement.  Return a pointer
106596** to the new trigger step.
106597**
106598** The parser calls this routine when it sees an INSERT inside the
106599** body of a trigger.
106600*/
106601SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
106602  sqlite3 *db,        /* The database connection */
106603  Token *pTableName,  /* Name of the table into which we insert */
106604  IdList *pColumn,    /* List of columns in pTableName to insert into */
106605  Select *pSelect,    /* A SELECT statement that supplies values */
106606  u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
106607){
106608  TriggerStep *pTriggerStep;
106609
106610  assert(pSelect != 0 || db->mallocFailed);
106611
106612  pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
106613  if( pTriggerStep ){
106614    pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
106615    pTriggerStep->pIdList = pColumn;
106616    pTriggerStep->orconf = orconf;
106617  }else{
106618    sqlite3IdListDelete(db, pColumn);
106619  }
106620  sqlite3SelectDelete(db, pSelect);
106621
106622  return pTriggerStep;
106623}
106624
106625/*
106626** Construct a trigger step that implements an UPDATE statement and return
106627** a pointer to that trigger step.  The parser calls this routine when it
106628** sees an UPDATE statement inside the body of a CREATE TRIGGER.
106629*/
106630SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
106631  sqlite3 *db,         /* The database connection */
106632  Token *pTableName,   /* Name of the table to be updated */
106633  ExprList *pEList,    /* The SET clause: list of column and new values */
106634  Expr *pWhere,        /* The WHERE clause */
106635  u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
106636){
106637  TriggerStep *pTriggerStep;
106638
106639  pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
106640  if( pTriggerStep ){
106641    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
106642    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
106643    pTriggerStep->orconf = orconf;
106644  }
106645  sqlite3ExprListDelete(db, pEList);
106646  sqlite3ExprDelete(db, pWhere);
106647  return pTriggerStep;
106648}
106649
106650/*
106651** Construct a trigger step that implements a DELETE statement and return
106652** a pointer to that trigger step.  The parser calls this routine when it
106653** sees a DELETE statement inside the body of a CREATE TRIGGER.
106654*/
106655SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
106656  sqlite3 *db,            /* Database connection */
106657  Token *pTableName,      /* The table from which rows are deleted */
106658  Expr *pWhere            /* The WHERE clause */
106659){
106660  TriggerStep *pTriggerStep;
106661
106662  pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
106663  if( pTriggerStep ){
106664    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
106665    pTriggerStep->orconf = OE_Default;
106666  }
106667  sqlite3ExprDelete(db, pWhere);
106668  return pTriggerStep;
106669}
106670
106671/*
106672** Recursively delete a Trigger structure
106673*/
106674SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
106675  if( pTrigger==0 ) return;
106676  sqlite3DeleteTriggerStep(db, pTrigger->step_list);
106677  sqlite3DbFree(db, pTrigger->zName);
106678  sqlite3DbFree(db, pTrigger->table);
106679  sqlite3ExprDelete(db, pTrigger->pWhen);
106680  sqlite3IdListDelete(db, pTrigger->pColumns);
106681  sqlite3DbFree(db, pTrigger);
106682}
106683
106684/*
106685** This function is called to drop a trigger from the database schema.
106686**
106687** This may be called directly from the parser and therefore identifies
106688** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
106689** same job as this routine except it takes a pointer to the trigger
106690** instead of the trigger name.
106691**/
106692SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
106693  Trigger *pTrigger = 0;
106694  int i;
106695  const char *zDb;
106696  const char *zName;
106697  int nName;
106698  sqlite3 *db = pParse->db;
106699
106700  if( db->mallocFailed ) goto drop_trigger_cleanup;
106701  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
106702    goto drop_trigger_cleanup;
106703  }
106704
106705  assert( pName->nSrc==1 );
106706  zDb = pName->a[0].zDatabase;
106707  zName = pName->a[0].zName;
106708  nName = sqlite3Strlen30(zName);
106709  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
106710  for(i=OMIT_TEMPDB; i<db->nDb; i++){
106711    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
106712    if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
106713    assert( sqlite3SchemaMutexHeld(db, j, 0) );
106714    pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
106715    if( pTrigger ) break;
106716  }
106717  if( !pTrigger ){
106718    if( !noErr ){
106719      sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
106720    }else{
106721      sqlite3CodeVerifyNamedSchema(pParse, zDb);
106722    }
106723    pParse->checkSchema = 1;
106724    goto drop_trigger_cleanup;
106725  }
106726  sqlite3DropTriggerPtr(pParse, pTrigger);
106727
106728drop_trigger_cleanup:
106729  sqlite3SrcListDelete(db, pName);
106730}
106731
106732/*
106733** Return a pointer to the Table structure for the table that a trigger
106734** is set on.
106735*/
106736static Table *tableOfTrigger(Trigger *pTrigger){
106737  int n = sqlite3Strlen30(pTrigger->table);
106738  return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
106739}
106740
106741
106742/*
106743** Drop a trigger given a pointer to that trigger.
106744*/
106745SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
106746  Table   *pTable;
106747  Vdbe *v;
106748  sqlite3 *db = pParse->db;
106749  int iDb;
106750
106751  iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
106752  assert( iDb>=0 && iDb<db->nDb );
106753  pTable = tableOfTrigger(pTrigger);
106754  assert( pTable );
106755  assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
106756#ifndef SQLITE_OMIT_AUTHORIZATION
106757  {
106758    int code = SQLITE_DROP_TRIGGER;
106759    const char *zDb = db->aDb[iDb].zName;
106760    const char *zTab = SCHEMA_TABLE(iDb);
106761    if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
106762    if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
106763      sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
106764      return;
106765    }
106766  }
106767#endif
106768
106769  /* Generate code to destroy the database record of the trigger.
106770  */
106771  assert( pTable!=0 );
106772  if( (v = sqlite3GetVdbe(pParse))!=0 ){
106773    int base;
106774    static const int iLn = VDBE_OFFSET_LINENO(2);
106775    static const VdbeOpList dropTrigger[] = {
106776      { OP_Rewind,     0, ADDR(9),  0},
106777      { OP_String8,    0, 1,        0}, /* 1 */
106778      { OP_Column,     0, 1,        2},
106779      { OP_Ne,         2, ADDR(8),  1},
106780      { OP_String8,    0, 1,        0}, /* 4: "trigger" */
106781      { OP_Column,     0, 0,        2},
106782      { OP_Ne,         2, ADDR(8),  1},
106783      { OP_Delete,     0, 0,        0},
106784      { OP_Next,       0, ADDR(1),  0}, /* 8 */
106785    };
106786
106787    sqlite3BeginWriteOperation(pParse, 0, iDb);
106788    sqlite3OpenMasterTable(pParse, iDb);
106789    base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger, iLn);
106790    sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
106791    sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
106792    sqlite3ChangeCookie(pParse, iDb);
106793    sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
106794    sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
106795    if( pParse->nMem<3 ){
106796      pParse->nMem = 3;
106797    }
106798  }
106799}
106800
106801/*
106802** Remove a trigger from the hash tables of the sqlite* pointer.
106803*/
106804SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
106805  Trigger *pTrigger;
106806  Hash *pHash;
106807
106808  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
106809  pHash = &(db->aDb[iDb].pSchema->trigHash);
106810  pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
106811  if( ALWAYS(pTrigger) ){
106812    if( pTrigger->pSchema==pTrigger->pTabSchema ){
106813      Table *pTab = tableOfTrigger(pTrigger);
106814      Trigger **pp;
106815      for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
106816      *pp = (*pp)->pNext;
106817    }
106818    sqlite3DeleteTrigger(db, pTrigger);
106819    db->flags |= SQLITE_InternChanges;
106820  }
106821}
106822
106823/*
106824** pEList is the SET clause of an UPDATE statement.  Each entry
106825** in pEList is of the format <id>=<expr>.  If any of the entries
106826** in pEList have an <id> which matches an identifier in pIdList,
106827** then return TRUE.  If pIdList==NULL, then it is considered a
106828** wildcard that matches anything.  Likewise if pEList==NULL then
106829** it matches anything so always return true.  Return false only
106830** if there is no match.
106831*/
106832static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
106833  int e;
106834  if( pIdList==0 || NEVER(pEList==0) ) return 1;
106835  for(e=0; e<pEList->nExpr; e++){
106836    if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
106837  }
106838  return 0;
106839}
106840
106841/*
106842** Return a list of all triggers on table pTab if there exists at least
106843** one trigger that must be fired when an operation of type 'op' is
106844** performed on the table, and, if that operation is an UPDATE, if at
106845** least one of the columns in pChanges is being modified.
106846*/
106847SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
106848  Parse *pParse,          /* Parse context */
106849  Table *pTab,            /* The table the contains the triggers */
106850  int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
106851  ExprList *pChanges,     /* Columns that change in an UPDATE statement */
106852  int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
106853){
106854  int mask = 0;
106855  Trigger *pList = 0;
106856  Trigger *p;
106857
106858  if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
106859    pList = sqlite3TriggerList(pParse, pTab);
106860  }
106861  assert( pList==0 || IsVirtual(pTab)==0 );
106862  for(p=pList; p; p=p->pNext){
106863    if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
106864      mask |= p->tr_tm;
106865    }
106866  }
106867  if( pMask ){
106868    *pMask = mask;
106869  }
106870  return (mask ? pList : 0);
106871}
106872
106873/*
106874** Convert the pStep->target token into a SrcList and return a pointer
106875** to that SrcList.
106876**
106877** This routine adds a specific database name, if needed, to the target when
106878** forming the SrcList.  This prevents a trigger in one database from
106879** referring to a target in another database.  An exception is when the
106880** trigger is in TEMP in which case it can refer to any other database it
106881** wants.
106882*/
106883static SrcList *targetSrcList(
106884  Parse *pParse,       /* The parsing context */
106885  TriggerStep *pStep   /* The trigger containing the target token */
106886){
106887  int iDb;             /* Index of the database to use */
106888  SrcList *pSrc;       /* SrcList to be returned */
106889
106890  pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
106891  if( pSrc ){
106892    assert( pSrc->nSrc>0 );
106893    assert( pSrc->a!=0 );
106894    iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
106895    if( iDb==0 || iDb>=2 ){
106896      sqlite3 *db = pParse->db;
106897      assert( iDb<pParse->db->nDb );
106898      pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
106899    }
106900  }
106901  return pSrc;
106902}
106903
106904/*
106905** Generate VDBE code for the statements inside the body of a single
106906** trigger.
106907*/
106908static int codeTriggerProgram(
106909  Parse *pParse,            /* The parser context */
106910  TriggerStep *pStepList,   /* List of statements inside the trigger body */
106911  int orconf                /* Conflict algorithm. (OE_Abort, etc) */
106912){
106913  TriggerStep *pStep;
106914  Vdbe *v = pParse->pVdbe;
106915  sqlite3 *db = pParse->db;
106916
106917  assert( pParse->pTriggerTab && pParse->pToplevel );
106918  assert( pStepList );
106919  assert( v!=0 );
106920  for(pStep=pStepList; pStep; pStep=pStep->pNext){
106921    /* Figure out the ON CONFLICT policy that will be used for this step
106922    ** of the trigger program. If the statement that caused this trigger
106923    ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
106924    ** the ON CONFLICT policy that was specified as part of the trigger
106925    ** step statement. Example:
106926    **
106927    **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
106928    **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
106929    **   END;
106930    **
106931    **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
106932    **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
106933    */
106934    pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
106935    assert( pParse->okConstFactor==0 );
106936
106937    switch( pStep->op ){
106938      case TK_UPDATE: {
106939        sqlite3Update(pParse,
106940          targetSrcList(pParse, pStep),
106941          sqlite3ExprListDup(db, pStep->pExprList, 0),
106942          sqlite3ExprDup(db, pStep->pWhere, 0),
106943          pParse->eOrconf
106944        );
106945        break;
106946      }
106947      case TK_INSERT: {
106948        sqlite3Insert(pParse,
106949          targetSrcList(pParse, pStep),
106950          sqlite3SelectDup(db, pStep->pSelect, 0),
106951          sqlite3IdListDup(db, pStep->pIdList),
106952          pParse->eOrconf
106953        );
106954        break;
106955      }
106956      case TK_DELETE: {
106957        sqlite3DeleteFrom(pParse,
106958          targetSrcList(pParse, pStep),
106959          sqlite3ExprDup(db, pStep->pWhere, 0)
106960        );
106961        break;
106962      }
106963      default: assert( pStep->op==TK_SELECT ); {
106964        SelectDest sDest;
106965        Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
106966        sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
106967        sqlite3Select(pParse, pSelect, &sDest);
106968        sqlite3SelectDelete(db, pSelect);
106969        break;
106970      }
106971    }
106972    if( pStep->op!=TK_SELECT ){
106973      sqlite3VdbeAddOp0(v, OP_ResetCount);
106974    }
106975  }
106976
106977  return 0;
106978}
106979
106980#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
106981/*
106982** This function is used to add VdbeComment() annotations to a VDBE
106983** program. It is not used in production code, only for debugging.
106984*/
106985static const char *onErrorText(int onError){
106986  switch( onError ){
106987    case OE_Abort:    return "abort";
106988    case OE_Rollback: return "rollback";
106989    case OE_Fail:     return "fail";
106990    case OE_Replace:  return "replace";
106991    case OE_Ignore:   return "ignore";
106992    case OE_Default:  return "default";
106993  }
106994  return "n/a";
106995}
106996#endif
106997
106998/*
106999** Parse context structure pFrom has just been used to create a sub-vdbe
107000** (trigger program). If an error has occurred, transfer error information
107001** from pFrom to pTo.
107002*/
107003static void transferParseError(Parse *pTo, Parse *pFrom){
107004  assert( pFrom->zErrMsg==0 || pFrom->nErr );
107005  assert( pTo->zErrMsg==0 || pTo->nErr );
107006  if( pTo->nErr==0 ){
107007    pTo->zErrMsg = pFrom->zErrMsg;
107008    pTo->nErr = pFrom->nErr;
107009  }else{
107010    sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
107011  }
107012}
107013
107014/*
107015** Create and populate a new TriggerPrg object with a sub-program
107016** implementing trigger pTrigger with ON CONFLICT policy orconf.
107017*/
107018static TriggerPrg *codeRowTrigger(
107019  Parse *pParse,       /* Current parse context */
107020  Trigger *pTrigger,   /* Trigger to code */
107021  Table *pTab,         /* The table pTrigger is attached to */
107022  int orconf           /* ON CONFLICT policy to code trigger program with */
107023){
107024  Parse *pTop = sqlite3ParseToplevel(pParse);
107025  sqlite3 *db = pParse->db;   /* Database handle */
107026  TriggerPrg *pPrg;           /* Value to return */
107027  Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
107028  Vdbe *v;                    /* Temporary VM */
107029  NameContext sNC;            /* Name context for sub-vdbe */
107030  SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
107031  Parse *pSubParse;           /* Parse context for sub-vdbe */
107032  int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
107033
107034  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
107035  assert( pTop->pVdbe );
107036
107037  /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
107038  ** are freed if an error occurs, link them into the Parse.pTriggerPrg
107039  ** list of the top-level Parse object sooner rather than later.  */
107040  pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
107041  if( !pPrg ) return 0;
107042  pPrg->pNext = pTop->pTriggerPrg;
107043  pTop->pTriggerPrg = pPrg;
107044  pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
107045  if( !pProgram ) return 0;
107046  sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
107047  pPrg->pTrigger = pTrigger;
107048  pPrg->orconf = orconf;
107049  pPrg->aColmask[0] = 0xffffffff;
107050  pPrg->aColmask[1] = 0xffffffff;
107051
107052  /* Allocate and populate a new Parse context to use for coding the
107053  ** trigger sub-program.  */
107054  pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
107055  if( !pSubParse ) return 0;
107056  memset(&sNC, 0, sizeof(sNC));
107057  sNC.pParse = pSubParse;
107058  pSubParse->db = db;
107059  pSubParse->pTriggerTab = pTab;
107060  pSubParse->pToplevel = pTop;
107061  pSubParse->zAuthContext = pTrigger->zName;
107062  pSubParse->eTriggerOp = pTrigger->op;
107063  pSubParse->nQueryLoop = pParse->nQueryLoop;
107064
107065  v = sqlite3GetVdbe(pSubParse);
107066  if( v ){
107067    VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
107068      pTrigger->zName, onErrorText(orconf),
107069      (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
107070        (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
107071        (pTrigger->op==TK_INSERT ? "INSERT" : ""),
107072        (pTrigger->op==TK_DELETE ? "DELETE" : ""),
107073      pTab->zName
107074    ));
107075#ifndef SQLITE_OMIT_TRACE
107076    sqlite3VdbeChangeP4(v, -1,
107077      sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
107078    );
107079#endif
107080
107081    /* If one was specified, code the WHEN clause. If it evaluates to false
107082    ** (or NULL) the sub-vdbe is immediately halted by jumping to the
107083    ** OP_Halt inserted at the end of the program.  */
107084    if( pTrigger->pWhen ){
107085      pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
107086      if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
107087       && db->mallocFailed==0
107088      ){
107089        iEndTrigger = sqlite3VdbeMakeLabel(v);
107090        sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
107091      }
107092      sqlite3ExprDelete(db, pWhen);
107093    }
107094
107095    /* Code the trigger program into the sub-vdbe. */
107096    codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
107097
107098    /* Insert an OP_Halt at the end of the sub-program. */
107099    if( iEndTrigger ){
107100      sqlite3VdbeResolveLabel(v, iEndTrigger);
107101    }
107102    sqlite3VdbeAddOp0(v, OP_Halt);
107103    VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
107104
107105    transferParseError(pParse, pSubParse);
107106    if( db->mallocFailed==0 ){
107107      pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
107108    }
107109    pProgram->nMem = pSubParse->nMem;
107110    pProgram->nCsr = pSubParse->nTab;
107111    pProgram->nOnce = pSubParse->nOnce;
107112    pProgram->token = (void *)pTrigger;
107113    pPrg->aColmask[0] = pSubParse->oldmask;
107114    pPrg->aColmask[1] = pSubParse->newmask;
107115    sqlite3VdbeDelete(v);
107116  }
107117
107118  assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
107119  assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
107120  sqlite3ParserReset(pSubParse);
107121  sqlite3StackFree(db, pSubParse);
107122
107123  return pPrg;
107124}
107125
107126/*
107127** Return a pointer to a TriggerPrg object containing the sub-program for
107128** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
107129** TriggerPrg object exists, a new object is allocated and populated before
107130** being returned.
107131*/
107132static TriggerPrg *getRowTrigger(
107133  Parse *pParse,       /* Current parse context */
107134  Trigger *pTrigger,   /* Trigger to code */
107135  Table *pTab,         /* The table trigger pTrigger is attached to */
107136  int orconf           /* ON CONFLICT algorithm. */
107137){
107138  Parse *pRoot = sqlite3ParseToplevel(pParse);
107139  TriggerPrg *pPrg;
107140
107141  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
107142
107143  /* It may be that this trigger has already been coded (or is in the
107144  ** process of being coded). If this is the case, then an entry with
107145  ** a matching TriggerPrg.pTrigger field will be present somewhere
107146  ** in the Parse.pTriggerPrg list. Search for such an entry.  */
107147  for(pPrg=pRoot->pTriggerPrg;
107148      pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
107149      pPrg=pPrg->pNext
107150  );
107151
107152  /* If an existing TriggerPrg could not be located, create a new one. */
107153  if( !pPrg ){
107154    pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
107155  }
107156
107157  return pPrg;
107158}
107159
107160/*
107161** Generate code for the trigger program associated with trigger p on
107162** table pTab. The reg, orconf and ignoreJump parameters passed to this
107163** function are the same as those described in the header function for
107164** sqlite3CodeRowTrigger()
107165*/
107166SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
107167  Parse *pParse,       /* Parse context */
107168  Trigger *p,          /* Trigger to code */
107169  Table *pTab,         /* The table to code triggers from */
107170  int reg,             /* Reg array containing OLD.* and NEW.* values */
107171  int orconf,          /* ON CONFLICT policy */
107172  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
107173){
107174  Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
107175  TriggerPrg *pPrg;
107176  pPrg = getRowTrigger(pParse, p, pTab, orconf);
107177  assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
107178
107179  /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
107180  ** is a pointer to the sub-vdbe containing the trigger program.  */
107181  if( pPrg ){
107182    int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
107183
107184    sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
107185    sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
107186    VdbeComment(
107187        (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
107188
107189    /* Set the P5 operand of the OP_Program instruction to non-zero if
107190    ** recursive invocation of this trigger program is disallowed. Recursive
107191    ** invocation is disallowed if (a) the sub-program is really a trigger,
107192    ** not a foreign key action, and (b) the flag to enable recursive triggers
107193    ** is clear.  */
107194    sqlite3VdbeChangeP5(v, (u8)bRecursive);
107195  }
107196}
107197
107198/*
107199** This is called to code the required FOR EACH ROW triggers for an operation
107200** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
107201** is given by the op parameter. The tr_tm parameter determines whether the
107202** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
107203** parameter pChanges is passed the list of columns being modified.
107204**
107205** If there are no triggers that fire at the specified time for the specified
107206** operation on pTab, this function is a no-op.
107207**
107208** The reg argument is the address of the first in an array of registers
107209** that contain the values substituted for the new.* and old.* references
107210** in the trigger program. If N is the number of columns in table pTab
107211** (a copy of pTab->nCol), then registers are populated as follows:
107212**
107213**   Register       Contains
107214**   ------------------------------------------------------
107215**   reg+0          OLD.rowid
107216**   reg+1          OLD.* value of left-most column of pTab
107217**   ...            ...
107218**   reg+N          OLD.* value of right-most column of pTab
107219**   reg+N+1        NEW.rowid
107220**   reg+N+2        OLD.* value of left-most column of pTab
107221**   ...            ...
107222**   reg+N+N+1      NEW.* value of right-most column of pTab
107223**
107224** For ON DELETE triggers, the registers containing the NEW.* values will
107225** never be accessed by the trigger program, so they are not allocated or
107226** populated by the caller (there is no data to populate them with anyway).
107227** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
107228** are never accessed, and so are not allocated by the caller. So, for an
107229** ON INSERT trigger, the value passed to this function as parameter reg
107230** is not a readable register, although registers (reg+N) through
107231** (reg+N+N+1) are.
107232**
107233** Parameter orconf is the default conflict resolution algorithm for the
107234** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
107235** is the instruction that control should jump to if a trigger program
107236** raises an IGNORE exception.
107237*/
107238SQLITE_PRIVATE void sqlite3CodeRowTrigger(
107239  Parse *pParse,       /* Parse context */
107240  Trigger *pTrigger,   /* List of triggers on table pTab */
107241  int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
107242  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
107243  int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
107244  Table *pTab,         /* The table to code triggers from */
107245  int reg,             /* The first in an array of registers (see above) */
107246  int orconf,          /* ON CONFLICT policy */
107247  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
107248){
107249  Trigger *p;          /* Used to iterate through pTrigger list */
107250
107251  assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
107252  assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
107253  assert( (op==TK_UPDATE)==(pChanges!=0) );
107254
107255  for(p=pTrigger; p; p=p->pNext){
107256
107257    /* Sanity checking:  The schema for the trigger and for the table are
107258    ** always defined.  The trigger must be in the same schema as the table
107259    ** or else it must be a TEMP trigger. */
107260    assert( p->pSchema!=0 );
107261    assert( p->pTabSchema!=0 );
107262    assert( p->pSchema==p->pTabSchema
107263         || p->pSchema==pParse->db->aDb[1].pSchema );
107264
107265    /* Determine whether we should code this trigger */
107266    if( p->op==op
107267     && p->tr_tm==tr_tm
107268     && checkColumnOverlap(p->pColumns, pChanges)
107269    ){
107270      sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
107271    }
107272  }
107273}
107274
107275/*
107276** Triggers may access values stored in the old.* or new.* pseudo-table.
107277** This function returns a 32-bit bitmask indicating which columns of the
107278** old.* or new.* tables actually are used by triggers. This information
107279** may be used by the caller, for example, to avoid having to load the entire
107280** old.* record into memory when executing an UPDATE or DELETE command.
107281**
107282** Bit 0 of the returned mask is set if the left-most column of the
107283** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
107284** the second leftmost column value is required, and so on. If there
107285** are more than 32 columns in the table, and at least one of the columns
107286** with an index greater than 32 may be accessed, 0xffffffff is returned.
107287**
107288** It is not possible to determine if the old.rowid or new.rowid column is
107289** accessed by triggers. The caller must always assume that it is.
107290**
107291** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
107292** applies to the old.* table. If 1, the new.* table.
107293**
107294** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
107295** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
107296** included in the returned mask if the TRIGGER_BEFORE bit is set in the
107297** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
107298** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
107299*/
107300SQLITE_PRIVATE u32 sqlite3TriggerColmask(
107301  Parse *pParse,       /* Parse context */
107302  Trigger *pTrigger,   /* List of triggers on table pTab */
107303  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
107304  int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
107305  int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
107306  Table *pTab,         /* The table to code triggers from */
107307  int orconf           /* Default ON CONFLICT policy for trigger steps */
107308){
107309  const int op = pChanges ? TK_UPDATE : TK_DELETE;
107310  u32 mask = 0;
107311  Trigger *p;
107312
107313  assert( isNew==1 || isNew==0 );
107314  for(p=pTrigger; p; p=p->pNext){
107315    if( p->op==op && (tr_tm&p->tr_tm)
107316     && checkColumnOverlap(p->pColumns,pChanges)
107317    ){
107318      TriggerPrg *pPrg;
107319      pPrg = getRowTrigger(pParse, p, pTab, orconf);
107320      if( pPrg ){
107321        mask |= pPrg->aColmask[isNew];
107322      }
107323    }
107324  }
107325
107326  return mask;
107327}
107328
107329#endif /* !defined(SQLITE_OMIT_TRIGGER) */
107330
107331/************** End of trigger.c *********************************************/
107332/************** Begin file update.c ******************************************/
107333/*
107334** 2001 September 15
107335**
107336** The author disclaims copyright to this source code.  In place of
107337** a legal notice, here is a blessing:
107338**
107339**    May you do good and not evil.
107340**    May you find forgiveness for yourself and forgive others.
107341**    May you share freely, never taking more than you give.
107342**
107343*************************************************************************
107344** This file contains C code routines that are called by the parser
107345** to handle UPDATE statements.
107346*/
107347
107348#ifndef SQLITE_OMIT_VIRTUALTABLE
107349/* Forward declaration */
107350static void updateVirtualTable(
107351  Parse *pParse,       /* The parsing context */
107352  SrcList *pSrc,       /* The virtual table to be modified */
107353  Table *pTab,         /* The virtual table */
107354  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
107355  Expr *pRowidExpr,    /* Expression used to recompute the rowid */
107356  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
107357  Expr *pWhere,        /* WHERE clause of the UPDATE statement */
107358  int onError          /* ON CONFLICT strategy */
107359);
107360#endif /* SQLITE_OMIT_VIRTUALTABLE */
107361
107362/*
107363** The most recently coded instruction was an OP_Column to retrieve the
107364** i-th column of table pTab. This routine sets the P4 parameter of the
107365** OP_Column to the default value, if any.
107366**
107367** The default value of a column is specified by a DEFAULT clause in the
107368** column definition. This was either supplied by the user when the table
107369** was created, or added later to the table definition by an ALTER TABLE
107370** command. If the latter, then the row-records in the table btree on disk
107371** may not contain a value for the column and the default value, taken
107372** from the P4 parameter of the OP_Column instruction, is returned instead.
107373** If the former, then all row-records are guaranteed to include a value
107374** for the column and the P4 value is not required.
107375**
107376** Column definitions created by an ALTER TABLE command may only have
107377** literal default values specified: a number, null or a string. (If a more
107378** complicated default expression value was provided, it is evaluated
107379** when the ALTER TABLE is executed and one of the literal values written
107380** into the sqlite_master table.)
107381**
107382** Therefore, the P4 parameter is only required if the default value for
107383** the column is a literal number, string or null. The sqlite3ValueFromExpr()
107384** function is capable of transforming these types of expressions into
107385** sqlite3_value objects.
107386**
107387** If parameter iReg is not negative, code an OP_RealAffinity instruction
107388** on register iReg. This is used when an equivalent integer value is
107389** stored in place of an 8-byte floating point value in order to save
107390** space.
107391*/
107392SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
107393  assert( pTab!=0 );
107394  if( !pTab->pSelect ){
107395    sqlite3_value *pValue = 0;
107396    u8 enc = ENC(sqlite3VdbeDb(v));
107397    Column *pCol = &pTab->aCol[i];
107398    VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
107399    assert( i<pTab->nCol );
107400    sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
107401                         pCol->affinity, &pValue);
107402    if( pValue ){
107403      sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
107404    }
107405#ifndef SQLITE_OMIT_FLOATING_POINT
107406    if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
107407      sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
107408    }
107409#endif
107410  }
107411}
107412
107413/*
107414** Process an UPDATE statement.
107415**
107416**   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
107417**          \_______/ \________/     \______/       \________________/
107418*            onError   pTabList      pChanges             pWhere
107419*/
107420SQLITE_PRIVATE void sqlite3Update(
107421  Parse *pParse,         /* The parser context */
107422  SrcList *pTabList,     /* The table in which we should change things */
107423  ExprList *pChanges,    /* Things to be changed */
107424  Expr *pWhere,          /* The WHERE clause.  May be null */
107425  int onError            /* How to handle constraint errors */
107426){
107427  int i, j;              /* Loop counters */
107428  Table *pTab;           /* The table to be updated */
107429  int addrTop = 0;       /* VDBE instruction address of the start of the loop */
107430  WhereInfo *pWInfo;     /* Information about the WHERE clause */
107431  Vdbe *v;               /* The virtual database engine */
107432  Index *pIdx;           /* For looping over indices */
107433  Index *pPk;            /* The PRIMARY KEY index for WITHOUT ROWID tables */
107434  int nIdx;              /* Number of indices that need updating */
107435  int iBaseCur;          /* Base cursor number */
107436  int iDataCur;          /* Cursor for the canonical data btree */
107437  int iIdxCur;           /* Cursor for the first index */
107438  sqlite3 *db;           /* The database structure */
107439  int *aRegIdx = 0;      /* One register assigned to each index to be updated */
107440  int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
107441                         ** an expression for the i-th column of the table.
107442                         ** aXRef[i]==-1 if the i-th column is not changed. */
107443  u8 *aToOpen;           /* 1 for tables and indices to be opened */
107444  u8 chngPk;             /* PRIMARY KEY changed in a WITHOUT ROWID table */
107445  u8 chngRowid;          /* Rowid changed in a normal table */
107446  u8 chngKey;            /* Either chngPk or chngRowid */
107447  Expr *pRowidExpr = 0;  /* Expression defining the new record number */
107448  AuthContext sContext;  /* The authorization context */
107449  NameContext sNC;       /* The name-context to resolve expressions in */
107450  int iDb;               /* Database containing the table being updated */
107451  int okOnePass;         /* True for one-pass algorithm without the FIFO */
107452  int hasFK;             /* True if foreign key processing is required */
107453  int labelBreak;        /* Jump here to break out of UPDATE loop */
107454  int labelContinue;     /* Jump here to continue next step of UPDATE loop */
107455
107456#ifndef SQLITE_OMIT_TRIGGER
107457  int isView;            /* True when updating a view (INSTEAD OF trigger) */
107458  Trigger *pTrigger;     /* List of triggers on pTab, if required */
107459  int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
107460#endif
107461  int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
107462  int iEph = 0;          /* Ephemeral table holding all primary key values */
107463  int nKey = 0;          /* Number of elements in regKey for WITHOUT ROWID */
107464  int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
107465
107466  /* Register Allocations */
107467  int regRowCount = 0;   /* A count of rows changed */
107468  int regOldRowid;       /* The old rowid */
107469  int regNewRowid;       /* The new rowid */
107470  int regNew;            /* Content of the NEW.* table in triggers */
107471  int regOld = 0;        /* Content of OLD.* table in triggers */
107472  int regRowSet = 0;     /* Rowset of rows to be updated */
107473  int regKey = 0;        /* composite PRIMARY KEY value */
107474
107475  memset(&sContext, 0, sizeof(sContext));
107476  db = pParse->db;
107477  if( pParse->nErr || db->mallocFailed ){
107478    goto update_cleanup;
107479  }
107480  assert( pTabList->nSrc==1 );
107481
107482  /* Locate the table which we want to update.
107483  */
107484  pTab = sqlite3SrcListLookup(pParse, pTabList);
107485  if( pTab==0 ) goto update_cleanup;
107486  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
107487
107488  /* Figure out if we have any triggers and if the table being
107489  ** updated is a view.
107490  */
107491#ifndef SQLITE_OMIT_TRIGGER
107492  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
107493  isView = pTab->pSelect!=0;
107494  assert( pTrigger || tmask==0 );
107495#else
107496# define pTrigger 0
107497# define isView 0
107498# define tmask 0
107499#endif
107500#ifdef SQLITE_OMIT_VIEW
107501# undef isView
107502# define isView 0
107503#endif
107504
107505  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
107506    goto update_cleanup;
107507  }
107508  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
107509    goto update_cleanup;
107510  }
107511
107512  /* Allocate a cursors for the main database table and for all indices.
107513  ** The index cursors might not be used, but if they are used they
107514  ** need to occur right after the database cursor.  So go ahead and
107515  ** allocate enough space, just in case.
107516  */
107517  pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
107518  iIdxCur = iDataCur+1;
107519  pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
107520  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
107521    if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
107522      iDataCur = pParse->nTab;
107523      pTabList->a[0].iCursor = iDataCur;
107524    }
107525    pParse->nTab++;
107526  }
107527
107528  /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
107529  ** Initialize aXRef[] and aToOpen[] to their default values.
107530  */
107531  aXRef = sqlite3DbMallocRaw(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
107532  if( aXRef==0 ) goto update_cleanup;
107533  aRegIdx = aXRef+pTab->nCol;
107534  aToOpen = (u8*)(aRegIdx+nIdx);
107535  memset(aToOpen, 1, nIdx+1);
107536  aToOpen[nIdx+1] = 0;
107537  for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
107538
107539  /* Initialize the name-context */
107540  memset(&sNC, 0, sizeof(sNC));
107541  sNC.pParse = pParse;
107542  sNC.pSrcList = pTabList;
107543
107544  /* Resolve the column names in all the expressions of the
107545  ** of the UPDATE statement.  Also find the column index
107546  ** for each column to be updated in the pChanges array.  For each
107547  ** column to be updated, make sure we have authorization to change
107548  ** that column.
107549  */
107550  chngRowid = chngPk = 0;
107551  for(i=0; i<pChanges->nExpr; i++){
107552    if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
107553      goto update_cleanup;
107554    }
107555    for(j=0; j<pTab->nCol; j++){
107556      if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
107557        if( j==pTab->iPKey ){
107558          chngRowid = 1;
107559          pRowidExpr = pChanges->a[i].pExpr;
107560        }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
107561          chngPk = 1;
107562        }
107563        aXRef[j] = i;
107564        break;
107565      }
107566    }
107567    if( j>=pTab->nCol ){
107568      if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
107569        j = -1;
107570        chngRowid = 1;
107571        pRowidExpr = pChanges->a[i].pExpr;
107572      }else{
107573        sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
107574        pParse->checkSchema = 1;
107575        goto update_cleanup;
107576      }
107577    }
107578#ifndef SQLITE_OMIT_AUTHORIZATION
107579    {
107580      int rc;
107581      rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
107582                            j<0 ? "ROWID" : pTab->aCol[j].zName,
107583                            db->aDb[iDb].zName);
107584      if( rc==SQLITE_DENY ){
107585        goto update_cleanup;
107586      }else if( rc==SQLITE_IGNORE ){
107587        aXRef[j] = -1;
107588      }
107589    }
107590#endif
107591  }
107592  assert( (chngRowid & chngPk)==0 );
107593  assert( chngRowid==0 || chngRowid==1 );
107594  assert( chngPk==0 || chngPk==1 );
107595  chngKey = chngRowid + chngPk;
107596
107597  /* The SET expressions are not actually used inside the WHERE loop.
107598  ** So reset the colUsed mask
107599  */
107600  pTabList->a[0].colUsed = 0;
107601
107602  hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
107603
107604  /* There is one entry in the aRegIdx[] array for each index on the table
107605  ** being updated.  Fill in aRegIdx[] with a register number that will hold
107606  ** the key for accessing each index.
107607  */
107608  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
107609    int reg;
107610    if( chngKey || hasFK || pIdx->pPartIdxWhere || pIdx==pPk ){
107611      reg = ++pParse->nMem;
107612    }else{
107613      reg = 0;
107614      for(i=0; i<pIdx->nKeyCol; i++){
107615        if( aXRef[pIdx->aiColumn[i]]>=0 ){
107616          reg = ++pParse->nMem;
107617          break;
107618        }
107619      }
107620    }
107621    if( reg==0 ) aToOpen[j+1] = 0;
107622    aRegIdx[j] = reg;
107623  }
107624
107625  /* Begin generating code. */
107626  v = sqlite3GetVdbe(pParse);
107627  if( v==0 ) goto update_cleanup;
107628  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
107629  sqlite3BeginWriteOperation(pParse, 1, iDb);
107630
107631#ifndef SQLITE_OMIT_VIRTUALTABLE
107632  /* Virtual tables must be handled separately */
107633  if( IsVirtual(pTab) ){
107634    updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
107635                       pWhere, onError);
107636    pWhere = 0;
107637    pTabList = 0;
107638    goto update_cleanup;
107639  }
107640#endif
107641
107642  /* Allocate required registers. */
107643  regRowSet = ++pParse->nMem;
107644  regOldRowid = regNewRowid = ++pParse->nMem;
107645  if( chngPk || pTrigger || hasFK ){
107646    regOld = pParse->nMem + 1;
107647    pParse->nMem += pTab->nCol;
107648  }
107649  if( chngKey || pTrigger || hasFK ){
107650    regNewRowid = ++pParse->nMem;
107651  }
107652  regNew = pParse->nMem + 1;
107653  pParse->nMem += pTab->nCol;
107654
107655  /* Start the view context. */
107656  if( isView ){
107657    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
107658  }
107659
107660  /* If we are trying to update a view, realize that view into
107661  ** a ephemeral table.
107662  */
107663#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
107664  if( isView ){
107665    sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
107666  }
107667#endif
107668
107669  /* Resolve the column names in all the expressions in the
107670  ** WHERE clause.
107671  */
107672  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
107673    goto update_cleanup;
107674  }
107675
107676  /* Begin the database scan
107677  */
107678  if( HasRowid(pTab) ){
107679    sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
107680    pWInfo = sqlite3WhereBegin(
107681        pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, iIdxCur
107682    );
107683    if( pWInfo==0 ) goto update_cleanup;
107684    okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
107685
107686    /* Remember the rowid of every item to be updated.
107687    */
107688    sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
107689    if( !okOnePass ){
107690      sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
107691    }
107692
107693    /* End the database scan loop.
107694    */
107695    sqlite3WhereEnd(pWInfo);
107696  }else{
107697    int iPk;         /* First of nPk memory cells holding PRIMARY KEY value */
107698    i16 nPk;         /* Number of components of the PRIMARY KEY */
107699    int addrOpen;    /* Address of the OpenEphemeral instruction */
107700
107701    assert( pPk!=0 );
107702    nPk = pPk->nKeyCol;
107703    iPk = pParse->nMem+1;
107704    pParse->nMem += nPk;
107705    regKey = ++pParse->nMem;
107706    iEph = pParse->nTab++;
107707    sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
107708    addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
107709    sqlite3VdbeSetP4KeyInfo(pParse, pPk);
107710    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
107711                               WHERE_ONEPASS_DESIRED, iIdxCur);
107712    if( pWInfo==0 ) goto update_cleanup;
107713    okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
107714    for(i=0; i<nPk; i++){
107715      sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pPk->aiColumn[i],
107716                                      iPk+i);
107717    }
107718    if( okOnePass ){
107719      sqlite3VdbeChangeToNoop(v, addrOpen);
107720      nKey = nPk;
107721      regKey = iPk;
107722    }else{
107723      sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
107724                        sqlite3IndexAffinityStr(v, pPk), nPk);
107725      sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, regKey);
107726    }
107727    sqlite3WhereEnd(pWInfo);
107728  }
107729
107730  /* Initialize the count of updated rows
107731  */
107732  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
107733    regRowCount = ++pParse->nMem;
107734    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
107735  }
107736
107737  labelBreak = sqlite3VdbeMakeLabel(v);
107738  if( !isView ){
107739    /*
107740    ** Open every index that needs updating.  Note that if any
107741    ** index could potentially invoke a REPLACE conflict resolution
107742    ** action, then we need to open all indices because we might need
107743    ** to be deleting some records.
107744    */
107745    if( onError==OE_Replace ){
107746      memset(aToOpen, 1, nIdx+1);
107747    }else{
107748      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
107749        if( pIdx->onError==OE_Replace ){
107750          memset(aToOpen, 1, nIdx+1);
107751          break;
107752        }
107753      }
107754    }
107755    if( okOnePass ){
107756      if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
107757      if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
107758    }
107759    sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iBaseCur, aToOpen,
107760                               0, 0);
107761  }
107762
107763  /* Top of the update loop */
107764  if( okOnePass ){
107765    if( aToOpen[iDataCur-iBaseCur] ){
107766      assert( pPk!=0 );
107767      sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
107768      VdbeCoverageNeverTaken(v);
107769    }
107770    labelContinue = labelBreak;
107771    sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
107772    VdbeCoverage(v);
107773  }else if( pPk ){
107774    labelContinue = sqlite3VdbeMakeLabel(v);
107775    sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
107776    addrTop = sqlite3VdbeAddOp2(v, OP_RowKey, iEph, regKey);
107777    sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
107778    VdbeCoverage(v);
107779  }else{
107780    labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
107781                             regOldRowid);
107782    VdbeCoverage(v);
107783    sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
107784    VdbeCoverage(v);
107785  }
107786
107787  /* If the record number will change, set register regNewRowid to
107788  ** contain the new value. If the record number is not being modified,
107789  ** then regNewRowid is the same register as regOldRowid, which is
107790  ** already populated.  */
107791  assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
107792  if( chngRowid ){
107793    sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
107794    sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
107795  }
107796
107797  /* Compute the old pre-UPDATE content of the row being changed, if that
107798  ** information is needed */
107799  if( chngPk || hasFK || pTrigger ){
107800    u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
107801    oldmask |= sqlite3TriggerColmask(pParse,
107802        pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
107803    );
107804    for(i=0; i<pTab->nCol; i++){
107805      if( oldmask==0xffffffff
107806       || (i<32 && (oldmask & MASKBIT32(i))!=0)
107807       || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
107808      ){
107809        testcase(  oldmask!=0xffffffff && i==31 );
107810        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
107811      }else{
107812        sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
107813      }
107814    }
107815    if( chngRowid==0 && pPk==0 ){
107816      sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
107817    }
107818  }
107819
107820  /* Populate the array of registers beginning at regNew with the new
107821  ** row data. This array is used to check constaints, create the new
107822  ** table and index records, and as the values for any new.* references
107823  ** made by triggers.
107824  **
107825  ** If there are one or more BEFORE triggers, then do not populate the
107826  ** registers associated with columns that are (a) not modified by
107827  ** this UPDATE statement and (b) not accessed by new.* references. The
107828  ** values for registers not modified by the UPDATE must be reloaded from
107829  ** the database after the BEFORE triggers are fired anyway (as the trigger
107830  ** may have modified them). So not loading those that are not going to
107831  ** be used eliminates some redundant opcodes.
107832  */
107833  newmask = sqlite3TriggerColmask(
107834      pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
107835  );
107836  /*sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);*/
107837  for(i=0; i<pTab->nCol; i++){
107838    if( i==pTab->iPKey ){
107839      sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
107840    }else{
107841      j = aXRef[i];
107842      if( j>=0 ){
107843        sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
107844      }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
107845        /* This branch loads the value of a column that will not be changed
107846        ** into a register. This is done if there are no BEFORE triggers, or
107847        ** if there are one or more BEFORE triggers that use this value via
107848        ** a new.* reference in a trigger program.
107849        */
107850        testcase( i==31 );
107851        testcase( i==32 );
107852        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
107853      }else{
107854        sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
107855      }
107856    }
107857  }
107858
107859  /* Fire any BEFORE UPDATE triggers. This happens before constraints are
107860  ** verified. One could argue that this is wrong.
107861  */
107862  if( tmask&TRIGGER_BEFORE ){
107863    sqlite3TableAffinity(v, pTab, regNew);
107864    sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
107865        TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
107866
107867    /* The row-trigger may have deleted the row being updated. In this
107868    ** case, jump to the next row. No updates or AFTER triggers are
107869    ** required. This behavior - what happens when the row being updated
107870    ** is deleted or renamed by a BEFORE trigger - is left undefined in the
107871    ** documentation.
107872    */
107873    if( pPk ){
107874      sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
107875      VdbeCoverage(v);
107876    }else{
107877      sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
107878      VdbeCoverage(v);
107879    }
107880
107881    /* If it did not delete it, the row-trigger may still have modified
107882    ** some of the columns of the row being updated. Load the values for
107883    ** all columns not modified by the update statement into their
107884    ** registers in case this has happened.
107885    */
107886    for(i=0; i<pTab->nCol; i++){
107887      if( aXRef[i]<0 && i!=pTab->iPKey ){
107888        sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
107889      }
107890    }
107891  }
107892
107893  if( !isView ){
107894    int j1 = 0;           /* Address of jump instruction */
107895    int bReplace = 0;     /* True if REPLACE conflict resolution might happen */
107896
107897    /* Do constraint checks. */
107898    assert( regOldRowid>0 );
107899    sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
107900        regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace);
107901
107902    /* Do FK constraint checks. */
107903    if( hasFK ){
107904      sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
107905    }
107906
107907    /* Delete the index entries associated with the current record.  */
107908    if( bReplace || chngKey ){
107909      if( pPk ){
107910        j1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
107911      }else{
107912        j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
107913      }
107914      VdbeCoverageNeverTaken(v);
107915    }
107916    sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx);
107917
107918    /* If changing the record number, delete the old record.  */
107919    if( hasFK || chngKey || pPk!=0 ){
107920      sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
107921    }
107922    if( bReplace || chngKey ){
107923      sqlite3VdbeJumpHere(v, j1);
107924    }
107925
107926    if( hasFK ){
107927      sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
107928    }
107929
107930    /* Insert the new index entries and the new record. */
107931    sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
107932                             regNewRowid, aRegIdx, 1, 0, 0);
107933
107934    /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
107935    ** handle rows (possibly in other tables) that refer via a foreign key
107936    ** to the row just updated. */
107937    if( hasFK ){
107938      sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
107939    }
107940  }
107941
107942  /* Increment the row counter
107943  */
107944  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
107945    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
107946  }
107947
107948  sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
107949      TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
107950
107951  /* Repeat the above with the next record to be updated, until
107952  ** all record selected by the WHERE clause have been updated.
107953  */
107954  if( okOnePass ){
107955    /* Nothing to do at end-of-loop for a single-pass */
107956  }else if( pPk ){
107957    sqlite3VdbeResolveLabel(v, labelContinue);
107958    sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
107959  }else{
107960    sqlite3VdbeAddOp2(v, OP_Goto, 0, labelContinue);
107961  }
107962  sqlite3VdbeResolveLabel(v, labelBreak);
107963
107964  /* Close all tables */
107965  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
107966    assert( aRegIdx );
107967    if( aToOpen[i+1] ){
107968      sqlite3VdbeAddOp2(v, OP_Close, iIdxCur+i, 0);
107969    }
107970  }
107971  if( iDataCur<iIdxCur ) sqlite3VdbeAddOp2(v, OP_Close, iDataCur, 0);
107972
107973  /* Update the sqlite_sequence table by storing the content of the
107974  ** maximum rowid counter values recorded while inserting into
107975  ** autoincrement tables.
107976  */
107977  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
107978    sqlite3AutoincrementEnd(pParse);
107979  }
107980
107981  /*
107982  ** Return the number of rows that were changed. If this routine is
107983  ** generating code because of a call to sqlite3NestedParse(), do not
107984  ** invoke the callback function.
107985  */
107986  if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
107987    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
107988    sqlite3VdbeSetNumCols(v, 1);
107989    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
107990  }
107991
107992update_cleanup:
107993  sqlite3AuthContextPop(&sContext);
107994  sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
107995  sqlite3SrcListDelete(db, pTabList);
107996  sqlite3ExprListDelete(db, pChanges);
107997  sqlite3ExprDelete(db, pWhere);
107998  return;
107999}
108000/* Make sure "isView" and other macros defined above are undefined. Otherwise
108001** thely may interfere with compilation of other functions in this file
108002** (or in another file, if this file becomes part of the amalgamation).  */
108003#ifdef isView
108004 #undef isView
108005#endif
108006#ifdef pTrigger
108007 #undef pTrigger
108008#endif
108009
108010#ifndef SQLITE_OMIT_VIRTUALTABLE
108011/*
108012** Generate code for an UPDATE of a virtual table.
108013**
108014** The strategy is that we create an ephemerial table that contains
108015** for each row to be changed:
108016**
108017**   (A)  The original rowid of that row.
108018**   (B)  The revised rowid for the row. (note1)
108019**   (C)  The content of every column in the row.
108020**
108021** Then we loop over this ephemeral table and for each row in
108022** the ephermeral table call VUpdate.
108023**
108024** When finished, drop the ephemeral table.
108025**
108026** (note1) Actually, if we know in advance that (A) is always the same
108027** as (B) we only store (A), then duplicate (A) when pulling
108028** it out of the ephemeral table before calling VUpdate.
108029*/
108030static void updateVirtualTable(
108031  Parse *pParse,       /* The parsing context */
108032  SrcList *pSrc,       /* The virtual table to be modified */
108033  Table *pTab,         /* The virtual table */
108034  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
108035  Expr *pRowid,        /* Expression used to recompute the rowid */
108036  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
108037  Expr *pWhere,        /* WHERE clause of the UPDATE statement */
108038  int onError          /* ON CONFLICT strategy */
108039){
108040  Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
108041  ExprList *pEList = 0;     /* The result set of the SELECT statement */
108042  Select *pSelect = 0;      /* The SELECT statement */
108043  Expr *pExpr;              /* Temporary expression */
108044  int ephemTab;             /* Table holding the result of the SELECT */
108045  int i;                    /* Loop counter */
108046  int addr;                 /* Address of top of loop */
108047  int iReg;                 /* First register in set passed to OP_VUpdate */
108048  sqlite3 *db = pParse->db; /* Database connection */
108049  const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
108050  SelectDest dest;
108051
108052  /* Construct the SELECT statement that will find the new values for
108053  ** all updated rows.
108054  */
108055  pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
108056  if( pRowid ){
108057    pEList = sqlite3ExprListAppend(pParse, pEList,
108058                                   sqlite3ExprDup(db, pRowid, 0));
108059  }
108060  assert( pTab->iPKey<0 );
108061  for(i=0; i<pTab->nCol; i++){
108062    if( aXRef[i]>=0 ){
108063      pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
108064    }else{
108065      pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
108066    }
108067    pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
108068  }
108069  pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
108070
108071  /* Create the ephemeral table into which the update results will
108072  ** be stored.
108073  */
108074  assert( v );
108075  ephemTab = pParse->nTab++;
108076  sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
108077  sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
108078
108079  /* fill the ephemeral table
108080  */
108081  sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
108082  sqlite3Select(pParse, pSelect, &dest);
108083
108084  /* Generate code to scan the ephemeral table and call VUpdate. */
108085  iReg = ++pParse->nMem;
108086  pParse->nMem += pTab->nCol+1;
108087  addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0); VdbeCoverage(v);
108088  sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
108089  sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
108090  for(i=0; i<pTab->nCol; i++){
108091    sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
108092  }
108093  sqlite3VtabMakeWritable(pParse, pTab);
108094  sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
108095  sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
108096  sqlite3MayAbort(pParse);
108097  sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
108098  sqlite3VdbeJumpHere(v, addr);
108099  sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
108100
108101  /* Cleanup */
108102  sqlite3SelectDelete(db, pSelect);
108103}
108104#endif /* SQLITE_OMIT_VIRTUALTABLE */
108105
108106/************** End of update.c **********************************************/
108107/************** Begin file vacuum.c ******************************************/
108108/*
108109** 2003 April 6
108110**
108111** The author disclaims copyright to this source code.  In place of
108112** a legal notice, here is a blessing:
108113**
108114**    May you do good and not evil.
108115**    May you find forgiveness for yourself and forgive others.
108116**    May you share freely, never taking more than you give.
108117**
108118*************************************************************************
108119** This file contains code used to implement the VACUUM command.
108120**
108121** Most of the code in this file may be omitted by defining the
108122** SQLITE_OMIT_VACUUM macro.
108123*/
108124
108125#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
108126/*
108127** Finalize a prepared statement.  If there was an error, store the
108128** text of the error message in *pzErrMsg.  Return the result code.
108129*/
108130static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
108131  int rc;
108132  rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
108133  if( rc ){
108134    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
108135  }
108136  return rc;
108137}
108138
108139/*
108140** Execute zSql on database db. Return an error code.
108141*/
108142static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
108143  sqlite3_stmt *pStmt;
108144  VVA_ONLY( int rc; )
108145  if( !zSql ){
108146    return SQLITE_NOMEM;
108147  }
108148  if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
108149    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
108150    return sqlite3_errcode(db);
108151  }
108152  VVA_ONLY( rc = ) sqlite3_step(pStmt);
108153  assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
108154  return vacuumFinalize(db, pStmt, pzErrMsg);
108155}
108156
108157/*
108158** Execute zSql on database db. The statement returns exactly
108159** one column. Execute this as SQL on the same database.
108160*/
108161static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
108162  sqlite3_stmt *pStmt;
108163  int rc;
108164
108165  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
108166  if( rc!=SQLITE_OK ) return rc;
108167
108168  while( SQLITE_ROW==sqlite3_step(pStmt) ){
108169    rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
108170    if( rc!=SQLITE_OK ){
108171      vacuumFinalize(db, pStmt, pzErrMsg);
108172      return rc;
108173    }
108174  }
108175
108176  return vacuumFinalize(db, pStmt, pzErrMsg);
108177}
108178
108179/*
108180** The VACUUM command is used to clean up the database,
108181** collapse free space, etc.  It is modelled after the VACUUM command
108182** in PostgreSQL.  The VACUUM command works as follows:
108183**
108184**   (1)  Create a new transient database file
108185**   (2)  Copy all content from the database being vacuumed into
108186**        the new transient database file
108187**   (3)  Copy content from the transient database back into the
108188**        original database.
108189**
108190** The transient database requires temporary disk space approximately
108191** equal to the size of the original database.  The copy operation of
108192** step (3) requires additional temporary disk space approximately equal
108193** to the size of the original database for the rollback journal.
108194** Hence, temporary disk space that is approximately 2x the size of the
108195** orginal database is required.  Every page of the database is written
108196** approximately 3 times:  Once for step (2) and twice for step (3).
108197** Two writes per page are required in step (3) because the original
108198** database content must be written into the rollback journal prior to
108199** overwriting the database with the vacuumed content.
108200**
108201** Only 1x temporary space and only 1x writes would be required if
108202** the copy of step (3) were replace by deleting the original database
108203** and renaming the transient database as the original.  But that will
108204** not work if other processes are attached to the original database.
108205** And a power loss in between deleting the original and renaming the
108206** transient would cause the database file to appear to be deleted
108207** following reboot.
108208*/
108209SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
108210  Vdbe *v = sqlite3GetVdbe(pParse);
108211  if( v ){
108212    sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
108213    sqlite3VdbeUsesBtree(v, 0);
108214  }
108215  return;
108216}
108217
108218/*
108219** This routine implements the OP_Vacuum opcode of the VDBE.
108220*/
108221SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
108222  int rc = SQLITE_OK;     /* Return code from service routines */
108223  Btree *pMain;           /* The database being vacuumed */
108224  Btree *pTemp;           /* The temporary database we vacuum into */
108225  char *zSql = 0;         /* SQL statements */
108226  int saved_flags;        /* Saved value of the db->flags */
108227  int saved_nChange;      /* Saved value of db->nChange */
108228  int saved_nTotalChange; /* Saved value of db->nTotalChange */
108229  void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
108230  Db *pDb = 0;            /* Database to detach at end of vacuum */
108231  int isMemDb;            /* True if vacuuming a :memory: database */
108232  int nRes;               /* Bytes of reserved space at the end of each page */
108233  int nDb;                /* Number of attached databases */
108234
108235  if( !db->autoCommit ){
108236    sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
108237    return SQLITE_ERROR;
108238  }
108239  if( db->nVdbeActive>1 ){
108240    sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
108241    return SQLITE_ERROR;
108242  }
108243
108244  /* Save the current value of the database flags so that it can be
108245  ** restored before returning. Then set the writable-schema flag, and
108246  ** disable CHECK and foreign key constraints.  */
108247  saved_flags = db->flags;
108248  saved_nChange = db->nChange;
108249  saved_nTotalChange = db->nTotalChange;
108250  saved_xTrace = db->xTrace;
108251  db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
108252  db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
108253  db->xTrace = 0;
108254
108255  pMain = db->aDb[0].pBt;
108256  isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
108257
108258  /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
108259  ** can be set to 'off' for this file, as it is not recovered if a crash
108260  ** occurs anyway. The integrity of the database is maintained by a
108261  ** (possibly synchronous) transaction opened on the main database before
108262  ** sqlite3BtreeCopyFile() is called.
108263  **
108264  ** An optimisation would be to use a non-journaled pager.
108265  ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
108266  ** that actually made the VACUUM run slower.  Very little journalling
108267  ** actually occurs when doing a vacuum since the vacuum_db is initially
108268  ** empty.  Only the journal header is written.  Apparently it takes more
108269  ** time to parse and run the PRAGMA to turn journalling off than it does
108270  ** to write the journal header file.
108271  */
108272  nDb = db->nDb;
108273  if( sqlite3TempInMemory(db) ){
108274    zSql = "ATTACH ':memory:' AS vacuum_db;";
108275  }else{
108276    zSql = "ATTACH '' AS vacuum_db;";
108277  }
108278  rc = execSql(db, pzErrMsg, zSql);
108279  if( db->nDb>nDb ){
108280    pDb = &db->aDb[db->nDb-1];
108281    assert( strcmp(pDb->zName,"vacuum_db")==0 );
108282  }
108283  if( rc!=SQLITE_OK ) goto end_of_vacuum;
108284  pTemp = db->aDb[db->nDb-1].pBt;
108285
108286  /* The call to execSql() to attach the temp database has left the file
108287  ** locked (as there was more than one active statement when the transaction
108288  ** to read the schema was concluded. Unlock it here so that this doesn't
108289  ** cause problems for the call to BtreeSetPageSize() below.  */
108290  sqlite3BtreeCommit(pTemp);
108291
108292  nRes = sqlite3BtreeGetReserve(pMain);
108293
108294  /* A VACUUM cannot change the pagesize of an encrypted database. */
108295#ifdef SQLITE_HAS_CODEC
108296  if( db->nextPagesize ){
108297    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
108298    int nKey;
108299    char *zKey;
108300    sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
108301    if( nKey ) db->nextPagesize = 0;
108302  }
108303#endif
108304
108305  rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
108306  if( rc!=SQLITE_OK ) goto end_of_vacuum;
108307
108308  /* Begin a transaction and take an exclusive lock on the main database
108309  ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
108310  ** to ensure that we do not try to change the page-size on a WAL database.
108311  */
108312  rc = execSql(db, pzErrMsg, "BEGIN;");
108313  if( rc!=SQLITE_OK ) goto end_of_vacuum;
108314  rc = sqlite3BtreeBeginTrans(pMain, 2);
108315  if( rc!=SQLITE_OK ) goto end_of_vacuum;
108316
108317  /* Do not attempt to change the page size for a WAL database */
108318  if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
108319                                               ==PAGER_JOURNALMODE_WAL ){
108320    db->nextPagesize = 0;
108321  }
108322
108323  if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
108324   || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
108325   || NEVER(db->mallocFailed)
108326  ){
108327    rc = SQLITE_NOMEM;
108328    goto end_of_vacuum;
108329  }
108330
108331#ifndef SQLITE_OMIT_AUTOVACUUM
108332  sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
108333                                           sqlite3BtreeGetAutoVacuum(pMain));
108334#endif
108335
108336  /* Query the schema of the main database. Create a mirror schema
108337  ** in the temporary database.
108338  */
108339  rc = execExecSql(db, pzErrMsg,
108340      "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
108341      "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
108342      "   AND coalesce(rootpage,1)>0"
108343  );
108344  if( rc!=SQLITE_OK ) goto end_of_vacuum;
108345  rc = execExecSql(db, pzErrMsg,
108346      "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
108347      "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
108348  if( rc!=SQLITE_OK ) goto end_of_vacuum;
108349  rc = execExecSql(db, pzErrMsg,
108350      "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
108351      "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
108352  if( rc!=SQLITE_OK ) goto end_of_vacuum;
108353
108354  /* Loop through the tables in the main database. For each, do
108355  ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
108356  ** the contents to the temporary database.
108357  */
108358  rc = execExecSql(db, pzErrMsg,
108359      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
108360      "|| ' SELECT * FROM main.' || quote(name) || ';'"
108361      "FROM main.sqlite_master "
108362      "WHERE type = 'table' AND name!='sqlite_sequence' "
108363      "  AND coalesce(rootpage,1)>0"
108364  );
108365  if( rc!=SQLITE_OK ) goto end_of_vacuum;
108366
108367  /* Copy over the sequence table
108368  */
108369  rc = execExecSql(db, pzErrMsg,
108370      "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
108371      "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
108372  );
108373  if( rc!=SQLITE_OK ) goto end_of_vacuum;
108374  rc = execExecSql(db, pzErrMsg,
108375      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
108376      "|| ' SELECT * FROM main.' || quote(name) || ';' "
108377      "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
108378  );
108379  if( rc!=SQLITE_OK ) goto end_of_vacuum;
108380
108381
108382  /* Copy the triggers, views, and virtual tables from the main database
108383  ** over to the temporary database.  None of these objects has any
108384  ** associated storage, so all we have to do is copy their entries
108385  ** from the SQLITE_MASTER table.
108386  */
108387  rc = execSql(db, pzErrMsg,
108388      "INSERT INTO vacuum_db.sqlite_master "
108389      "  SELECT type, name, tbl_name, rootpage, sql"
108390      "    FROM main.sqlite_master"
108391      "   WHERE type='view' OR type='trigger'"
108392      "      OR (type='table' AND rootpage=0)"
108393  );
108394  if( rc ) goto end_of_vacuum;
108395
108396  /* At this point, there is a write transaction open on both the
108397  ** vacuum database and the main database. Assuming no error occurs,
108398  ** both transactions are closed by this block - the main database
108399  ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
108400  ** call to sqlite3BtreeCommit().
108401  */
108402  {
108403    u32 meta;
108404    int i;
108405
108406    /* This array determines which meta meta values are preserved in the
108407    ** vacuum.  Even entries are the meta value number and odd entries
108408    ** are an increment to apply to the meta value after the vacuum.
108409    ** The increment is used to increase the schema cookie so that other
108410    ** connections to the same database will know to reread the schema.
108411    */
108412    static const unsigned char aCopy[] = {
108413       BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
108414       BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
108415       BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
108416       BTREE_USER_VERSION,       0,  /* Preserve the user version */
108417       BTREE_APPLICATION_ID,     0,  /* Preserve the application id */
108418    };
108419
108420    assert( 1==sqlite3BtreeIsInTrans(pTemp) );
108421    assert( 1==sqlite3BtreeIsInTrans(pMain) );
108422
108423    /* Copy Btree meta values */
108424    for(i=0; i<ArraySize(aCopy); i+=2){
108425      /* GetMeta() and UpdateMeta() cannot fail in this context because
108426      ** we already have page 1 loaded into cache and marked dirty. */
108427      sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
108428      rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
108429      if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
108430    }
108431
108432    rc = sqlite3BtreeCopyFile(pMain, pTemp);
108433    if( rc!=SQLITE_OK ) goto end_of_vacuum;
108434    rc = sqlite3BtreeCommit(pTemp);
108435    if( rc!=SQLITE_OK ) goto end_of_vacuum;
108436#ifndef SQLITE_OMIT_AUTOVACUUM
108437    sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
108438#endif
108439  }
108440
108441  assert( rc==SQLITE_OK );
108442  rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
108443
108444end_of_vacuum:
108445  /* Restore the original value of db->flags */
108446  db->flags = saved_flags;
108447  db->nChange = saved_nChange;
108448  db->nTotalChange = saved_nTotalChange;
108449  db->xTrace = saved_xTrace;
108450  sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
108451
108452  /* Currently there is an SQL level transaction open on the vacuum
108453  ** database. No locks are held on any other files (since the main file
108454  ** was committed at the btree level). So it safe to end the transaction
108455  ** by manually setting the autoCommit flag to true and detaching the
108456  ** vacuum database. The vacuum_db journal file is deleted when the pager
108457  ** is closed by the DETACH.
108458  */
108459  db->autoCommit = 1;
108460
108461  if( pDb ){
108462    sqlite3BtreeClose(pDb->pBt);
108463    pDb->pBt = 0;
108464    pDb->pSchema = 0;
108465  }
108466
108467  /* This both clears the schemas and reduces the size of the db->aDb[]
108468  ** array. */
108469  sqlite3ResetAllSchemasOfConnection(db);
108470
108471  return rc;
108472}
108473
108474#endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
108475
108476/************** End of vacuum.c **********************************************/
108477/************** Begin file vtab.c ********************************************/
108478/*
108479** 2006 June 10
108480**
108481** The author disclaims copyright to this source code.  In place of
108482** a legal notice, here is a blessing:
108483**
108484**    May you do good and not evil.
108485**    May you find forgiveness for yourself and forgive others.
108486**    May you share freely, never taking more than you give.
108487**
108488*************************************************************************
108489** This file contains code used to help implement virtual tables.
108490*/
108491#ifndef SQLITE_OMIT_VIRTUALTABLE
108492
108493/*
108494** Before a virtual table xCreate() or xConnect() method is invoked, the
108495** sqlite3.pVtabCtx member variable is set to point to an instance of
108496** this struct allocated on the stack. It is used by the implementation of
108497** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
108498** are invoked only from within xCreate and xConnect methods.
108499*/
108500struct VtabCtx {
108501  VTable *pVTable;    /* The virtual table being constructed */
108502  Table *pTab;        /* The Table object to which the virtual table belongs */
108503};
108504
108505/*
108506** The actual function that does the work of creating a new module.
108507** This function implements the sqlite3_create_module() and
108508** sqlite3_create_module_v2() interfaces.
108509*/
108510static int createModule(
108511  sqlite3 *db,                    /* Database in which module is registered */
108512  const char *zName,              /* Name assigned to this module */
108513  const sqlite3_module *pModule,  /* The definition of the module */
108514  void *pAux,                     /* Context pointer for xCreate/xConnect */
108515  void (*xDestroy)(void *)        /* Module destructor function */
108516){
108517  int rc = SQLITE_OK;
108518  int nName;
108519
108520  sqlite3_mutex_enter(db->mutex);
108521  nName = sqlite3Strlen30(zName);
108522  if( sqlite3HashFind(&db->aModule, zName, nName) ){
108523    rc = SQLITE_MISUSE_BKPT;
108524  }else{
108525    Module *pMod;
108526    pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
108527    if( pMod ){
108528      Module *pDel;
108529      char *zCopy = (char *)(&pMod[1]);
108530      memcpy(zCopy, zName, nName+1);
108531      pMod->zName = zCopy;
108532      pMod->pModule = pModule;
108533      pMod->pAux = pAux;
108534      pMod->xDestroy = xDestroy;
108535      pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,nName,(void*)pMod);
108536      assert( pDel==0 || pDel==pMod );
108537      if( pDel ){
108538        db->mallocFailed = 1;
108539        sqlite3DbFree(db, pDel);
108540      }
108541    }
108542  }
108543  rc = sqlite3ApiExit(db, rc);
108544  if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
108545
108546  sqlite3_mutex_leave(db->mutex);
108547  return rc;
108548}
108549
108550
108551/*
108552** External API function used to create a new virtual-table module.
108553*/
108554SQLITE_API int sqlite3_create_module(
108555  sqlite3 *db,                    /* Database in which module is registered */
108556  const char *zName,              /* Name assigned to this module */
108557  const sqlite3_module *pModule,  /* The definition of the module */
108558  void *pAux                      /* Context pointer for xCreate/xConnect */
108559){
108560  return createModule(db, zName, pModule, pAux, 0);
108561}
108562
108563/*
108564** External API function used to create a new virtual-table module.
108565*/
108566SQLITE_API int sqlite3_create_module_v2(
108567  sqlite3 *db,                    /* Database in which module is registered */
108568  const char *zName,              /* Name assigned to this module */
108569  const sqlite3_module *pModule,  /* The definition of the module */
108570  void *pAux,                     /* Context pointer for xCreate/xConnect */
108571  void (*xDestroy)(void *)        /* Module destructor function */
108572){
108573  return createModule(db, zName, pModule, pAux, xDestroy);
108574}
108575
108576/*
108577** Lock the virtual table so that it cannot be disconnected.
108578** Locks nest.  Every lock should have a corresponding unlock.
108579** If an unlock is omitted, resources leaks will occur.
108580**
108581** If a disconnect is attempted while a virtual table is locked,
108582** the disconnect is deferred until all locks have been removed.
108583*/
108584SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
108585  pVTab->nRef++;
108586}
108587
108588
108589/*
108590** pTab is a pointer to a Table structure representing a virtual-table.
108591** Return a pointer to the VTable object used by connection db to access
108592** this virtual-table, if one has been created, or NULL otherwise.
108593*/
108594SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
108595  VTable *pVtab;
108596  assert( IsVirtual(pTab) );
108597  for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
108598  return pVtab;
108599}
108600
108601/*
108602** Decrement the ref-count on a virtual table object. When the ref-count
108603** reaches zero, call the xDisconnect() method to delete the object.
108604*/
108605SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
108606  sqlite3 *db = pVTab->db;
108607
108608  assert( db );
108609  assert( pVTab->nRef>0 );
108610  assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
108611
108612  pVTab->nRef--;
108613  if( pVTab->nRef==0 ){
108614    sqlite3_vtab *p = pVTab->pVtab;
108615    if( p ){
108616      p->pModule->xDisconnect(p);
108617    }
108618    sqlite3DbFree(db, pVTab);
108619  }
108620}
108621
108622/*
108623** Table p is a virtual table. This function moves all elements in the
108624** p->pVTable list to the sqlite3.pDisconnect lists of their associated
108625** database connections to be disconnected at the next opportunity.
108626** Except, if argument db is not NULL, then the entry associated with
108627** connection db is left in the p->pVTable list.
108628*/
108629static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
108630  VTable *pRet = 0;
108631  VTable *pVTable = p->pVTable;
108632  p->pVTable = 0;
108633
108634  /* Assert that the mutex (if any) associated with the BtShared database
108635  ** that contains table p is held by the caller. See header comments
108636  ** above function sqlite3VtabUnlockList() for an explanation of why
108637  ** this makes it safe to access the sqlite3.pDisconnect list of any
108638  ** database connection that may have an entry in the p->pVTable list.
108639  */
108640  assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
108641
108642  while( pVTable ){
108643    sqlite3 *db2 = pVTable->db;
108644    VTable *pNext = pVTable->pNext;
108645    assert( db2 );
108646    if( db2==db ){
108647      pRet = pVTable;
108648      p->pVTable = pRet;
108649      pRet->pNext = 0;
108650    }else{
108651      pVTable->pNext = db2->pDisconnect;
108652      db2->pDisconnect = pVTable;
108653    }
108654    pVTable = pNext;
108655  }
108656
108657  assert( !db || pRet );
108658  return pRet;
108659}
108660
108661/*
108662** Table *p is a virtual table. This function removes the VTable object
108663** for table *p associated with database connection db from the linked
108664** list in p->pVTab. It also decrements the VTable ref count. This is
108665** used when closing database connection db to free all of its VTable
108666** objects without disturbing the rest of the Schema object (which may
108667** be being used by other shared-cache connections).
108668*/
108669SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
108670  VTable **ppVTab;
108671
108672  assert( IsVirtual(p) );
108673  assert( sqlite3BtreeHoldsAllMutexes(db) );
108674  assert( sqlite3_mutex_held(db->mutex) );
108675
108676  for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
108677    if( (*ppVTab)->db==db  ){
108678      VTable *pVTab = *ppVTab;
108679      *ppVTab = pVTab->pNext;
108680      sqlite3VtabUnlock(pVTab);
108681      break;
108682    }
108683  }
108684}
108685
108686
108687/*
108688** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
108689**
108690** This function may only be called when the mutexes associated with all
108691** shared b-tree databases opened using connection db are held by the
108692** caller. This is done to protect the sqlite3.pDisconnect list. The
108693** sqlite3.pDisconnect list is accessed only as follows:
108694**
108695**   1) By this function. In this case, all BtShared mutexes and the mutex
108696**      associated with the database handle itself must be held.
108697**
108698**   2) By function vtabDisconnectAll(), when it adds a VTable entry to
108699**      the sqlite3.pDisconnect list. In this case either the BtShared mutex
108700**      associated with the database the virtual table is stored in is held
108701**      or, if the virtual table is stored in a non-sharable database, then
108702**      the database handle mutex is held.
108703**
108704** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
108705** by multiple threads. It is thread-safe.
108706*/
108707SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
108708  VTable *p = db->pDisconnect;
108709  db->pDisconnect = 0;
108710
108711  assert( sqlite3BtreeHoldsAllMutexes(db) );
108712  assert( sqlite3_mutex_held(db->mutex) );
108713
108714  if( p ){
108715    sqlite3ExpirePreparedStatements(db);
108716    do {
108717      VTable *pNext = p->pNext;
108718      sqlite3VtabUnlock(p);
108719      p = pNext;
108720    }while( p );
108721  }
108722}
108723
108724/*
108725** Clear any and all virtual-table information from the Table record.
108726** This routine is called, for example, just before deleting the Table
108727** record.
108728**
108729** Since it is a virtual-table, the Table structure contains a pointer
108730** to the head of a linked list of VTable structures. Each VTable
108731** structure is associated with a single sqlite3* user of the schema.
108732** The reference count of the VTable structure associated with database
108733** connection db is decremented immediately (which may lead to the
108734** structure being xDisconnected and free). Any other VTable structures
108735** in the list are moved to the sqlite3.pDisconnect list of the associated
108736** database connection.
108737*/
108738SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
108739  if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
108740  if( p->azModuleArg ){
108741    int i;
108742    for(i=0; i<p->nModuleArg; i++){
108743      if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
108744    }
108745    sqlite3DbFree(db, p->azModuleArg);
108746  }
108747}
108748
108749/*
108750** Add a new module argument to pTable->azModuleArg[].
108751** The string is not copied - the pointer is stored.  The
108752** string will be freed automatically when the table is
108753** deleted.
108754*/
108755static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
108756  int i = pTable->nModuleArg++;
108757  int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
108758  char **azModuleArg;
108759  azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
108760  if( azModuleArg==0 ){
108761    int j;
108762    for(j=0; j<i; j++){
108763      sqlite3DbFree(db, pTable->azModuleArg[j]);
108764    }
108765    sqlite3DbFree(db, zArg);
108766    sqlite3DbFree(db, pTable->azModuleArg);
108767    pTable->nModuleArg = 0;
108768  }else{
108769    azModuleArg[i] = zArg;
108770    azModuleArg[i+1] = 0;
108771  }
108772  pTable->azModuleArg = azModuleArg;
108773}
108774
108775/*
108776** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
108777** statement.  The module name has been parsed, but the optional list
108778** of parameters that follow the module name are still pending.
108779*/
108780SQLITE_PRIVATE void sqlite3VtabBeginParse(
108781  Parse *pParse,        /* Parsing context */
108782  Token *pName1,        /* Name of new table, or database name */
108783  Token *pName2,        /* Name of new table or NULL */
108784  Token *pModuleName,   /* Name of the module for the virtual table */
108785  int ifNotExists       /* No error if the table already exists */
108786){
108787  int iDb;              /* The database the table is being created in */
108788  Table *pTable;        /* The new virtual table */
108789  sqlite3 *db;          /* Database connection */
108790
108791  sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
108792  pTable = pParse->pNewTable;
108793  if( pTable==0 ) return;
108794  assert( 0==pTable->pIndex );
108795
108796  db = pParse->db;
108797  iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
108798  assert( iDb>=0 );
108799
108800  pTable->tabFlags |= TF_Virtual;
108801  pTable->nModuleArg = 0;
108802  addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
108803  addModuleArgument(db, pTable, 0);
108804  addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
108805  pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
108806
108807#ifndef SQLITE_OMIT_AUTHORIZATION
108808  /* Creating a virtual table invokes the authorization callback twice.
108809  ** The first invocation, to obtain permission to INSERT a row into the
108810  ** sqlite_master table, has already been made by sqlite3StartTable().
108811  ** The second call, to obtain permission to create the table, is made now.
108812  */
108813  if( pTable->azModuleArg ){
108814    sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
108815            pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
108816  }
108817#endif
108818}
108819
108820/*
108821** This routine takes the module argument that has been accumulating
108822** in pParse->zArg[] and appends it to the list of arguments on the
108823** virtual table currently under construction in pParse->pTable.
108824*/
108825static void addArgumentToVtab(Parse *pParse){
108826  if( pParse->sArg.z && pParse->pNewTable ){
108827    const char *z = (const char*)pParse->sArg.z;
108828    int n = pParse->sArg.n;
108829    sqlite3 *db = pParse->db;
108830    addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
108831  }
108832}
108833
108834/*
108835** The parser calls this routine after the CREATE VIRTUAL TABLE statement
108836** has been completely parsed.
108837*/
108838SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
108839  Table *pTab = pParse->pNewTable;  /* The table being constructed */
108840  sqlite3 *db = pParse->db;         /* The database connection */
108841
108842  if( pTab==0 ) return;
108843  addArgumentToVtab(pParse);
108844  pParse->sArg.z = 0;
108845  if( pTab->nModuleArg<1 ) return;
108846
108847  /* If the CREATE VIRTUAL TABLE statement is being entered for the
108848  ** first time (in other words if the virtual table is actually being
108849  ** created now instead of just being read out of sqlite_master) then
108850  ** do additional initialization work and store the statement text
108851  ** in the sqlite_master table.
108852  */
108853  if( !db->init.busy ){
108854    char *zStmt;
108855    char *zWhere;
108856    int iDb;
108857    Vdbe *v;
108858
108859    /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
108860    if( pEnd ){
108861      pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
108862    }
108863    zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
108864
108865    /* A slot for the record has already been allocated in the
108866    ** SQLITE_MASTER table.  We just need to update that slot with all
108867    ** the information we've collected.
108868    **
108869    ** The VM register number pParse->regRowid holds the rowid of an
108870    ** entry in the sqlite_master table tht was created for this vtab
108871    ** by sqlite3StartTable().
108872    */
108873    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
108874    sqlite3NestedParse(pParse,
108875      "UPDATE %Q.%s "
108876         "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
108877       "WHERE rowid=#%d",
108878      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
108879      pTab->zName,
108880      pTab->zName,
108881      zStmt,
108882      pParse->regRowid
108883    );
108884    sqlite3DbFree(db, zStmt);
108885    v = sqlite3GetVdbe(pParse);
108886    sqlite3ChangeCookie(pParse, iDb);
108887
108888    sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
108889    zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
108890    sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
108891    sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
108892                         pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
108893  }
108894
108895  /* If we are rereading the sqlite_master table create the in-memory
108896  ** record of the table. The xConnect() method is not called until
108897  ** the first time the virtual table is used in an SQL statement. This
108898  ** allows a schema that contains virtual tables to be loaded before
108899  ** the required virtual table implementations are registered.  */
108900  else {
108901    Table *pOld;
108902    Schema *pSchema = pTab->pSchema;
108903    const char *zName = pTab->zName;
108904    int nName = sqlite3Strlen30(zName);
108905    assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
108906    pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
108907    if( pOld ){
108908      db->mallocFailed = 1;
108909      assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
108910      return;
108911    }
108912    pParse->pNewTable = 0;
108913  }
108914}
108915
108916/*
108917** The parser calls this routine when it sees the first token
108918** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
108919*/
108920SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
108921  addArgumentToVtab(pParse);
108922  pParse->sArg.z = 0;
108923  pParse->sArg.n = 0;
108924}
108925
108926/*
108927** The parser calls this routine for each token after the first token
108928** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
108929*/
108930SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
108931  Token *pArg = &pParse->sArg;
108932  if( pArg->z==0 ){
108933    pArg->z = p->z;
108934    pArg->n = p->n;
108935  }else{
108936    assert(pArg->z < p->z);
108937    pArg->n = (int)(&p->z[p->n] - pArg->z);
108938  }
108939}
108940
108941/*
108942** Invoke a virtual table constructor (either xCreate or xConnect). The
108943** pointer to the function to invoke is passed as the fourth parameter
108944** to this procedure.
108945*/
108946static int vtabCallConstructor(
108947  sqlite3 *db,
108948  Table *pTab,
108949  Module *pMod,
108950  int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
108951  char **pzErr
108952){
108953  VtabCtx sCtx, *pPriorCtx;
108954  VTable *pVTable;
108955  int rc;
108956  const char *const*azArg = (const char *const*)pTab->azModuleArg;
108957  int nArg = pTab->nModuleArg;
108958  char *zErr = 0;
108959  char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
108960  int iDb;
108961
108962  if( !zModuleName ){
108963    return SQLITE_NOMEM;
108964  }
108965
108966  pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
108967  if( !pVTable ){
108968    sqlite3DbFree(db, zModuleName);
108969    return SQLITE_NOMEM;
108970  }
108971  pVTable->db = db;
108972  pVTable->pMod = pMod;
108973
108974  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
108975  pTab->azModuleArg[1] = db->aDb[iDb].zName;
108976
108977  /* Invoke the virtual table constructor */
108978  assert( &db->pVtabCtx );
108979  assert( xConstruct );
108980  sCtx.pTab = pTab;
108981  sCtx.pVTable = pVTable;
108982  pPriorCtx = db->pVtabCtx;
108983  db->pVtabCtx = &sCtx;
108984  rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
108985  db->pVtabCtx = pPriorCtx;
108986  if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
108987
108988  if( SQLITE_OK!=rc ){
108989    if( zErr==0 ){
108990      *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
108991    }else {
108992      *pzErr = sqlite3MPrintf(db, "%s", zErr);
108993      sqlite3_free(zErr);
108994    }
108995    sqlite3DbFree(db, pVTable);
108996  }else if( ALWAYS(pVTable->pVtab) ){
108997    /* Justification of ALWAYS():  A correct vtab constructor must allocate
108998    ** the sqlite3_vtab object if successful.  */
108999    pVTable->pVtab->pModule = pMod->pModule;
109000    pVTable->nRef = 1;
109001    if( sCtx.pTab ){
109002      const char *zFormat = "vtable constructor did not declare schema: %s";
109003      *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
109004      sqlite3VtabUnlock(pVTable);
109005      rc = SQLITE_ERROR;
109006    }else{
109007      int iCol;
109008      /* If everything went according to plan, link the new VTable structure
109009      ** into the linked list headed by pTab->pVTable. Then loop through the
109010      ** columns of the table to see if any of them contain the token "hidden".
109011      ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
109012      ** the type string.  */
109013      pVTable->pNext = pTab->pVTable;
109014      pTab->pVTable = pVTable;
109015
109016      for(iCol=0; iCol<pTab->nCol; iCol++){
109017        char *zType = pTab->aCol[iCol].zType;
109018        int nType;
109019        int i = 0;
109020        if( !zType ) continue;
109021        nType = sqlite3Strlen30(zType);
109022        if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
109023          for(i=0; i<nType; i++){
109024            if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
109025             && (zType[i+7]=='\0' || zType[i+7]==' ')
109026            ){
109027              i++;
109028              break;
109029            }
109030          }
109031        }
109032        if( i<nType ){
109033          int j;
109034          int nDel = 6 + (zType[i+6] ? 1 : 0);
109035          for(j=i; (j+nDel)<=nType; j++){
109036            zType[j] = zType[j+nDel];
109037          }
109038          if( zType[i]=='\0' && i>0 ){
109039            assert(zType[i-1]==' ');
109040            zType[i-1] = '\0';
109041          }
109042          pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
109043        }
109044      }
109045    }
109046  }
109047
109048  sqlite3DbFree(db, zModuleName);
109049  return rc;
109050}
109051
109052/*
109053** This function is invoked by the parser to call the xConnect() method
109054** of the virtual table pTab. If an error occurs, an error code is returned
109055** and an error left in pParse.
109056**
109057** This call is a no-op if table pTab is not a virtual table.
109058*/
109059SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
109060  sqlite3 *db = pParse->db;
109061  const char *zMod;
109062  Module *pMod;
109063  int rc;
109064
109065  assert( pTab );
109066  if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
109067    return SQLITE_OK;
109068  }
109069
109070  /* Locate the required virtual table module */
109071  zMod = pTab->azModuleArg[0];
109072  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
109073
109074  if( !pMod ){
109075    const char *zModule = pTab->azModuleArg[0];
109076    sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
109077    rc = SQLITE_ERROR;
109078  }else{
109079    char *zErr = 0;
109080    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
109081    if( rc!=SQLITE_OK ){
109082      sqlite3ErrorMsg(pParse, "%s", zErr);
109083    }
109084    sqlite3DbFree(db, zErr);
109085  }
109086
109087  return rc;
109088}
109089/*
109090** Grow the db->aVTrans[] array so that there is room for at least one
109091** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
109092*/
109093static int growVTrans(sqlite3 *db){
109094  const int ARRAY_INCR = 5;
109095
109096  /* Grow the sqlite3.aVTrans array if required */
109097  if( (db->nVTrans%ARRAY_INCR)==0 ){
109098    VTable **aVTrans;
109099    int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
109100    aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
109101    if( !aVTrans ){
109102      return SQLITE_NOMEM;
109103    }
109104    memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
109105    db->aVTrans = aVTrans;
109106  }
109107
109108  return SQLITE_OK;
109109}
109110
109111/*
109112** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
109113** have already been reserved using growVTrans().
109114*/
109115static void addToVTrans(sqlite3 *db, VTable *pVTab){
109116  /* Add pVtab to the end of sqlite3.aVTrans */
109117  db->aVTrans[db->nVTrans++] = pVTab;
109118  sqlite3VtabLock(pVTab);
109119}
109120
109121/*
109122** This function is invoked by the vdbe to call the xCreate method
109123** of the virtual table named zTab in database iDb.
109124**
109125** If an error occurs, *pzErr is set to point an an English language
109126** description of the error and an SQLITE_XXX error code is returned.
109127** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
109128*/
109129SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
109130  int rc = SQLITE_OK;
109131  Table *pTab;
109132  Module *pMod;
109133  const char *zMod;
109134
109135  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
109136  assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
109137
109138  /* Locate the required virtual table module */
109139  zMod = pTab->azModuleArg[0];
109140  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
109141
109142  /* If the module has been registered and includes a Create method,
109143  ** invoke it now. If the module has not been registered, return an
109144  ** error. Otherwise, do nothing.
109145  */
109146  if( !pMod ){
109147    *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
109148    rc = SQLITE_ERROR;
109149  }else{
109150    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
109151  }
109152
109153  /* Justification of ALWAYS():  The xConstructor method is required to
109154  ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
109155  if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
109156    rc = growVTrans(db);
109157    if( rc==SQLITE_OK ){
109158      addToVTrans(db, sqlite3GetVTable(db, pTab));
109159    }
109160  }
109161
109162  return rc;
109163}
109164
109165/*
109166** This function is used to set the schema of a virtual table.  It is only
109167** valid to call this function from within the xCreate() or xConnect() of a
109168** virtual table module.
109169*/
109170SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
109171  Parse *pParse;
109172
109173  int rc = SQLITE_OK;
109174  Table *pTab;
109175  char *zErr = 0;
109176
109177  sqlite3_mutex_enter(db->mutex);
109178  if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
109179    sqlite3Error(db, SQLITE_MISUSE, 0);
109180    sqlite3_mutex_leave(db->mutex);
109181    return SQLITE_MISUSE_BKPT;
109182  }
109183  assert( (pTab->tabFlags & TF_Virtual)!=0 );
109184
109185  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
109186  if( pParse==0 ){
109187    rc = SQLITE_NOMEM;
109188  }else{
109189    pParse->declareVtab = 1;
109190    pParse->db = db;
109191    pParse->nQueryLoop = 1;
109192
109193    if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
109194     && pParse->pNewTable
109195     && !db->mallocFailed
109196     && !pParse->pNewTable->pSelect
109197     && (pParse->pNewTable->tabFlags & TF_Virtual)==0
109198    ){
109199      if( !pTab->aCol ){
109200        pTab->aCol = pParse->pNewTable->aCol;
109201        pTab->nCol = pParse->pNewTable->nCol;
109202        pParse->pNewTable->nCol = 0;
109203        pParse->pNewTable->aCol = 0;
109204      }
109205      db->pVtabCtx->pTab = 0;
109206    }else{
109207      sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
109208      sqlite3DbFree(db, zErr);
109209      rc = SQLITE_ERROR;
109210    }
109211    pParse->declareVtab = 0;
109212
109213    if( pParse->pVdbe ){
109214      sqlite3VdbeFinalize(pParse->pVdbe);
109215    }
109216    sqlite3DeleteTable(db, pParse->pNewTable);
109217    sqlite3ParserReset(pParse);
109218    sqlite3StackFree(db, pParse);
109219  }
109220
109221  assert( (rc&0xff)==rc );
109222  rc = sqlite3ApiExit(db, rc);
109223  sqlite3_mutex_leave(db->mutex);
109224  return rc;
109225}
109226
109227/*
109228** This function is invoked by the vdbe to call the xDestroy method
109229** of the virtual table named zTab in database iDb. This occurs
109230** when a DROP TABLE is mentioned.
109231**
109232** This call is a no-op if zTab is not a virtual table.
109233*/
109234SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
109235  int rc = SQLITE_OK;
109236  Table *pTab;
109237
109238  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
109239  if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
109240    VTable *p = vtabDisconnectAll(db, pTab);
109241
109242    assert( rc==SQLITE_OK );
109243    rc = p->pMod->pModule->xDestroy(p->pVtab);
109244
109245    /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
109246    if( rc==SQLITE_OK ){
109247      assert( pTab->pVTable==p && p->pNext==0 );
109248      p->pVtab = 0;
109249      pTab->pVTable = 0;
109250      sqlite3VtabUnlock(p);
109251    }
109252  }
109253
109254  return rc;
109255}
109256
109257/*
109258** This function invokes either the xRollback or xCommit method
109259** of each of the virtual tables in the sqlite3.aVTrans array. The method
109260** called is identified by the second argument, "offset", which is
109261** the offset of the method to call in the sqlite3_module structure.
109262**
109263** The array is cleared after invoking the callbacks.
109264*/
109265static void callFinaliser(sqlite3 *db, int offset){
109266  int i;
109267  if( db->aVTrans ){
109268    for(i=0; i<db->nVTrans; i++){
109269      VTable *pVTab = db->aVTrans[i];
109270      sqlite3_vtab *p = pVTab->pVtab;
109271      if( p ){
109272        int (*x)(sqlite3_vtab *);
109273        x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
109274        if( x ) x(p);
109275      }
109276      pVTab->iSavepoint = 0;
109277      sqlite3VtabUnlock(pVTab);
109278    }
109279    sqlite3DbFree(db, db->aVTrans);
109280    db->nVTrans = 0;
109281    db->aVTrans = 0;
109282  }
109283}
109284
109285/*
109286** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
109287** array. Return the error code for the first error that occurs, or
109288** SQLITE_OK if all xSync operations are successful.
109289**
109290** If an error message is available, leave it in p->zErrMsg.
109291*/
109292SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
109293  int i;
109294  int rc = SQLITE_OK;
109295  VTable **aVTrans = db->aVTrans;
109296
109297  db->aVTrans = 0;
109298  for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
109299    int (*x)(sqlite3_vtab *);
109300    sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
109301    if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
109302      rc = x(pVtab);
109303      sqlite3VtabImportErrmsg(p, pVtab);
109304    }
109305  }
109306  db->aVTrans = aVTrans;
109307  return rc;
109308}
109309
109310/*
109311** Invoke the xRollback method of all virtual tables in the
109312** sqlite3.aVTrans array. Then clear the array itself.
109313*/
109314SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
109315  callFinaliser(db, offsetof(sqlite3_module,xRollback));
109316  return SQLITE_OK;
109317}
109318
109319/*
109320** Invoke the xCommit method of all virtual tables in the
109321** sqlite3.aVTrans array. Then clear the array itself.
109322*/
109323SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
109324  callFinaliser(db, offsetof(sqlite3_module,xCommit));
109325  return SQLITE_OK;
109326}
109327
109328/*
109329** If the virtual table pVtab supports the transaction interface
109330** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
109331** not currently open, invoke the xBegin method now.
109332**
109333** If the xBegin call is successful, place the sqlite3_vtab pointer
109334** in the sqlite3.aVTrans array.
109335*/
109336SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
109337  int rc = SQLITE_OK;
109338  const sqlite3_module *pModule;
109339
109340  /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
109341  ** than zero, then this function is being called from within a
109342  ** virtual module xSync() callback. It is illegal to write to
109343  ** virtual module tables in this case, so return SQLITE_LOCKED.
109344  */
109345  if( sqlite3VtabInSync(db) ){
109346    return SQLITE_LOCKED;
109347  }
109348  if( !pVTab ){
109349    return SQLITE_OK;
109350  }
109351  pModule = pVTab->pVtab->pModule;
109352
109353  if( pModule->xBegin ){
109354    int i;
109355
109356    /* If pVtab is already in the aVTrans array, return early */
109357    for(i=0; i<db->nVTrans; i++){
109358      if( db->aVTrans[i]==pVTab ){
109359        return SQLITE_OK;
109360      }
109361    }
109362
109363    /* Invoke the xBegin method. If successful, add the vtab to the
109364    ** sqlite3.aVTrans[] array. */
109365    rc = growVTrans(db);
109366    if( rc==SQLITE_OK ){
109367      rc = pModule->xBegin(pVTab->pVtab);
109368      if( rc==SQLITE_OK ){
109369        addToVTrans(db, pVTab);
109370      }
109371    }
109372  }
109373  return rc;
109374}
109375
109376/*
109377** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
109378** virtual tables that currently have an open transaction. Pass iSavepoint
109379** as the second argument to the virtual table method invoked.
109380**
109381** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
109382** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
109383** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
109384** an open transaction is invoked.
109385**
109386** If any virtual table method returns an error code other than SQLITE_OK,
109387** processing is abandoned and the error returned to the caller of this
109388** function immediately. If all calls to virtual table methods are successful,
109389** SQLITE_OK is returned.
109390*/
109391SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
109392  int rc = SQLITE_OK;
109393
109394  assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
109395  assert( iSavepoint>=0 );
109396  if( db->aVTrans ){
109397    int i;
109398    for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
109399      VTable *pVTab = db->aVTrans[i];
109400      const sqlite3_module *pMod = pVTab->pMod->pModule;
109401      if( pVTab->pVtab && pMod->iVersion>=2 ){
109402        int (*xMethod)(sqlite3_vtab *, int);
109403        switch( op ){
109404          case SAVEPOINT_BEGIN:
109405            xMethod = pMod->xSavepoint;
109406            pVTab->iSavepoint = iSavepoint+1;
109407            break;
109408          case SAVEPOINT_ROLLBACK:
109409            xMethod = pMod->xRollbackTo;
109410            break;
109411          default:
109412            xMethod = pMod->xRelease;
109413            break;
109414        }
109415        if( xMethod && pVTab->iSavepoint>iSavepoint ){
109416          rc = xMethod(pVTab->pVtab, iSavepoint);
109417        }
109418      }
109419    }
109420  }
109421  return rc;
109422}
109423
109424/*
109425** The first parameter (pDef) is a function implementation.  The
109426** second parameter (pExpr) is the first argument to this function.
109427** If pExpr is a column in a virtual table, then let the virtual
109428** table implementation have an opportunity to overload the function.
109429**
109430** This routine is used to allow virtual table implementations to
109431** overload MATCH, LIKE, GLOB, and REGEXP operators.
109432**
109433** Return either the pDef argument (indicating no change) or a
109434** new FuncDef structure that is marked as ephemeral using the
109435** SQLITE_FUNC_EPHEM flag.
109436*/
109437SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
109438  sqlite3 *db,    /* Database connection for reporting malloc problems */
109439  FuncDef *pDef,  /* Function to possibly overload */
109440  int nArg,       /* Number of arguments to the function */
109441  Expr *pExpr     /* First argument to the function */
109442){
109443  Table *pTab;
109444  sqlite3_vtab *pVtab;
109445  sqlite3_module *pMod;
109446  void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
109447  void *pArg = 0;
109448  FuncDef *pNew;
109449  int rc = 0;
109450  char *zLowerName;
109451  unsigned char *z;
109452
109453
109454  /* Check to see the left operand is a column in a virtual table */
109455  if( NEVER(pExpr==0) ) return pDef;
109456  if( pExpr->op!=TK_COLUMN ) return pDef;
109457  pTab = pExpr->pTab;
109458  if( NEVER(pTab==0) ) return pDef;
109459  if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
109460  pVtab = sqlite3GetVTable(db, pTab)->pVtab;
109461  assert( pVtab!=0 );
109462  assert( pVtab->pModule!=0 );
109463  pMod = (sqlite3_module *)pVtab->pModule;
109464  if( pMod->xFindFunction==0 ) return pDef;
109465
109466  /* Call the xFindFunction method on the virtual table implementation
109467  ** to see if the implementation wants to overload this function
109468  */
109469  zLowerName = sqlite3DbStrDup(db, pDef->zName);
109470  if( zLowerName ){
109471    for(z=(unsigned char*)zLowerName; *z; z++){
109472      *z = sqlite3UpperToLower[*z];
109473    }
109474    rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
109475    sqlite3DbFree(db, zLowerName);
109476  }
109477  if( rc==0 ){
109478    return pDef;
109479  }
109480
109481  /* Create a new ephemeral function definition for the overloaded
109482  ** function */
109483  pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
109484                             + sqlite3Strlen30(pDef->zName) + 1);
109485  if( pNew==0 ){
109486    return pDef;
109487  }
109488  *pNew = *pDef;
109489  pNew->zName = (char *)&pNew[1];
109490  memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
109491  pNew->xFunc = xFunc;
109492  pNew->pUserData = pArg;
109493  pNew->funcFlags |= SQLITE_FUNC_EPHEM;
109494  return pNew;
109495}
109496
109497/*
109498** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
109499** array so that an OP_VBegin will get generated for it.  Add pTab to the
109500** array if it is missing.  If pTab is already in the array, this routine
109501** is a no-op.
109502*/
109503SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
109504  Parse *pToplevel = sqlite3ParseToplevel(pParse);
109505  int i, n;
109506  Table **apVtabLock;
109507
109508  assert( IsVirtual(pTab) );
109509  for(i=0; i<pToplevel->nVtabLock; i++){
109510    if( pTab==pToplevel->apVtabLock[i] ) return;
109511  }
109512  n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
109513  apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
109514  if( apVtabLock ){
109515    pToplevel->apVtabLock = apVtabLock;
109516    pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
109517  }else{
109518    pToplevel->db->mallocFailed = 1;
109519  }
109520}
109521
109522/*
109523** Return the ON CONFLICT resolution mode in effect for the virtual
109524** table update operation currently in progress.
109525**
109526** The results of this routine are undefined unless it is called from
109527** within an xUpdate method.
109528*/
109529SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
109530  static const unsigned char aMap[] = {
109531    SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
109532  };
109533  assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
109534  assert( OE_Ignore==4 && OE_Replace==5 );
109535  assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
109536  return (int)aMap[db->vtabOnConflict-1];
109537}
109538
109539/*
109540** Call from within the xCreate() or xConnect() methods to provide
109541** the SQLite core with additional information about the behavior
109542** of the virtual table being implemented.
109543*/
109544SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
109545  va_list ap;
109546  int rc = SQLITE_OK;
109547
109548  sqlite3_mutex_enter(db->mutex);
109549
109550  va_start(ap, op);
109551  switch( op ){
109552    case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
109553      VtabCtx *p = db->pVtabCtx;
109554      if( !p ){
109555        rc = SQLITE_MISUSE_BKPT;
109556      }else{
109557        assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
109558        p->pVTable->bConstraint = (u8)va_arg(ap, int);
109559      }
109560      break;
109561    }
109562    default:
109563      rc = SQLITE_MISUSE_BKPT;
109564      break;
109565  }
109566  va_end(ap);
109567
109568  if( rc!=SQLITE_OK ) sqlite3Error(db, rc, 0);
109569  sqlite3_mutex_leave(db->mutex);
109570  return rc;
109571}
109572
109573#endif /* SQLITE_OMIT_VIRTUALTABLE */
109574
109575/************** End of vtab.c ************************************************/
109576/************** Begin file where.c *******************************************/
109577/*
109578** 2001 September 15
109579**
109580** The author disclaims copyright to this source code.  In place of
109581** a legal notice, here is a blessing:
109582**
109583**    May you do good and not evil.
109584**    May you find forgiveness for yourself and forgive others.
109585**    May you share freely, never taking more than you give.
109586**
109587*************************************************************************
109588** This module contains C code that generates VDBE code used to process
109589** the WHERE clause of SQL statements.  This module is responsible for
109590** generating the code that loops through a table looking for applicable
109591** rows.  Indices are selected and used to speed the search when doing
109592** so is applicable.  Because this module is responsible for selecting
109593** indices, you might also think of this module as the "query optimizer".
109594*/
109595/************** Include whereInt.h in the middle of where.c ******************/
109596/************** Begin file whereInt.h ****************************************/
109597/*
109598** 2013-11-12
109599**
109600** The author disclaims copyright to this source code.  In place of
109601** a legal notice, here is a blessing:
109602**
109603**    May you do good and not evil.
109604**    May you find forgiveness for yourself and forgive others.
109605**    May you share freely, never taking more than you give.
109606**
109607*************************************************************************
109608**
109609** This file contains structure and macro definitions for the query
109610** planner logic in "where.c".  These definitions are broken out into
109611** a separate source file for easier editing.
109612*/
109613
109614/*
109615** Trace output macros
109616*/
109617#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
109618/***/ int sqlite3WhereTrace = 0;
109619#endif
109620#if defined(SQLITE_DEBUG) \
109621    && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
109622# define WHERETRACE(K,X)  if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
109623# define WHERETRACE_ENABLED 1
109624#else
109625# define WHERETRACE(K,X)
109626#endif
109627
109628/* Forward references
109629*/
109630typedef struct WhereClause WhereClause;
109631typedef struct WhereMaskSet WhereMaskSet;
109632typedef struct WhereOrInfo WhereOrInfo;
109633typedef struct WhereAndInfo WhereAndInfo;
109634typedef struct WhereLevel WhereLevel;
109635typedef struct WhereLoop WhereLoop;
109636typedef struct WherePath WherePath;
109637typedef struct WhereTerm WhereTerm;
109638typedef struct WhereLoopBuilder WhereLoopBuilder;
109639typedef struct WhereScan WhereScan;
109640typedef struct WhereOrCost WhereOrCost;
109641typedef struct WhereOrSet WhereOrSet;
109642
109643/*
109644** This object contains information needed to implement a single nested
109645** loop in WHERE clause.
109646**
109647** Contrast this object with WhereLoop.  This object describes the
109648** implementation of the loop.  WhereLoop describes the algorithm.
109649** This object contains a pointer to the WhereLoop algorithm as one of
109650** its elements.
109651**
109652** The WhereInfo object contains a single instance of this object for
109653** each term in the FROM clause (which is to say, for each of the
109654** nested loops as implemented).  The order of WhereLevel objects determines
109655** the loop nested order, with WhereInfo.a[0] being the outer loop and
109656** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
109657*/
109658struct WhereLevel {
109659  int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
109660  int iTabCur;          /* The VDBE cursor used to access the table */
109661  int iIdxCur;          /* The VDBE cursor used to access pIdx */
109662  int addrBrk;          /* Jump here to break out of the loop */
109663  int addrNxt;          /* Jump here to start the next IN combination */
109664  int addrSkip;         /* Jump here for next iteration of skip-scan */
109665  int addrCont;         /* Jump here to continue with the next loop cycle */
109666  int addrFirst;        /* First instruction of interior of the loop */
109667  int addrBody;         /* Beginning of the body of this loop */
109668  u8 iFrom;             /* Which entry in the FROM clause */
109669  u8 op, p3, p5;        /* Opcode, P3 & P5 of the opcode that ends the loop */
109670  int p1, p2;           /* Operands of the opcode used to ends the loop */
109671  union {               /* Information that depends on pWLoop->wsFlags */
109672    struct {
109673      int nIn;              /* Number of entries in aInLoop[] */
109674      struct InLoop {
109675        int iCur;              /* The VDBE cursor used by this IN operator */
109676        int addrInTop;         /* Top of the IN loop */
109677        u8 eEndLoopOp;         /* IN Loop terminator. OP_Next or OP_Prev */
109678      } *aInLoop;           /* Information about each nested IN operator */
109679    } in;                 /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
109680    Index *pCovidx;       /* Possible covering index for WHERE_MULTI_OR */
109681  } u;
109682  struct WhereLoop *pWLoop;  /* The selected WhereLoop object */
109683  Bitmask notReady;          /* FROM entries not usable at this level */
109684};
109685
109686/*
109687** Each instance of this object represents an algorithm for evaluating one
109688** term of a join.  Every term of the FROM clause will have at least
109689** one corresponding WhereLoop object (unless INDEXED BY constraints
109690** prevent a query solution - which is an error) and many terms of the
109691** FROM clause will have multiple WhereLoop objects, each describing a
109692** potential way of implementing that FROM-clause term, together with
109693** dependencies and cost estimates for using the chosen algorithm.
109694**
109695** Query planning consists of building up a collection of these WhereLoop
109696** objects, then computing a particular sequence of WhereLoop objects, with
109697** one WhereLoop object per FROM clause term, that satisfy all dependencies
109698** and that minimize the overall cost.
109699*/
109700struct WhereLoop {
109701  Bitmask prereq;       /* Bitmask of other loops that must run first */
109702  Bitmask maskSelf;     /* Bitmask identifying table iTab */
109703#ifdef SQLITE_DEBUG
109704  char cId;             /* Symbolic ID of this loop for debugging use */
109705#endif
109706  u8 iTab;              /* Position in FROM clause of table for this loop */
109707  u8 iSortIdx;          /* Sorting index number.  0==None */
109708  LogEst rSetup;        /* One-time setup cost (ex: create transient index) */
109709  LogEst rRun;          /* Cost of running each loop */
109710  LogEst nOut;          /* Estimated number of output rows */
109711  union {
109712    struct {               /* Information for internal btree tables */
109713      u16 nEq;               /* Number of equality constraints */
109714      u16 nSkip;             /* Number of initial index columns to skip */
109715      Index *pIndex;         /* Index used, or NULL */
109716    } btree;
109717    struct {               /* Information for virtual tables */
109718      int idxNum;            /* Index number */
109719      u8 needFree;           /* True if sqlite3_free(idxStr) is needed */
109720      i8 isOrdered;          /* True if satisfies ORDER BY */
109721      u16 omitMask;          /* Terms that may be omitted */
109722      char *idxStr;          /* Index identifier string */
109723    } vtab;
109724  } u;
109725  u32 wsFlags;          /* WHERE_* flags describing the plan */
109726  u16 nLTerm;           /* Number of entries in aLTerm[] */
109727  /**** whereLoopXfer() copies fields above ***********************/
109728# define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
109729  u16 nLSlot;           /* Number of slots allocated for aLTerm[] */
109730  WhereTerm **aLTerm;   /* WhereTerms used */
109731  WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
109732  WhereTerm *aLTermSpace[4];  /* Initial aLTerm[] space */
109733};
109734
109735/* This object holds the prerequisites and the cost of running a
109736** subquery on one operand of an OR operator in the WHERE clause.
109737** See WhereOrSet for additional information
109738*/
109739struct WhereOrCost {
109740  Bitmask prereq;     /* Prerequisites */
109741  LogEst rRun;        /* Cost of running this subquery */
109742  LogEst nOut;        /* Number of outputs for this subquery */
109743};
109744
109745/* The WhereOrSet object holds a set of possible WhereOrCosts that
109746** correspond to the subquery(s) of OR-clause processing.  Only the
109747** best N_OR_COST elements are retained.
109748*/
109749#define N_OR_COST 3
109750struct WhereOrSet {
109751  u16 n;                      /* Number of valid a[] entries */
109752  WhereOrCost a[N_OR_COST];   /* Set of best costs */
109753};
109754
109755
109756/* Forward declaration of methods */
109757static int whereLoopResize(sqlite3*, WhereLoop*, int);
109758
109759/*
109760** Each instance of this object holds a sequence of WhereLoop objects
109761** that implement some or all of a query plan.
109762**
109763** Think of each WhereLoop object as a node in a graph with arcs
109764** showing dependencies and costs for travelling between nodes.  (That is
109765** not a completely accurate description because WhereLoop costs are a
109766** vector, not a scalar, and because dependencies are many-to-one, not
109767** one-to-one as are graph nodes.  But it is a useful visualization aid.)
109768** Then a WherePath object is a path through the graph that visits some
109769** or all of the WhereLoop objects once.
109770**
109771** The "solver" works by creating the N best WherePath objects of length
109772** 1.  Then using those as a basis to compute the N best WherePath objects
109773** of length 2.  And so forth until the length of WherePaths equals the
109774** number of nodes in the FROM clause.  The best (lowest cost) WherePath
109775** at the end is the choosen query plan.
109776*/
109777struct WherePath {
109778  Bitmask maskLoop;     /* Bitmask of all WhereLoop objects in this path */
109779  Bitmask revLoop;      /* aLoop[]s that should be reversed for ORDER BY */
109780  LogEst nRow;          /* Estimated number of rows generated by this path */
109781  LogEst rCost;         /* Total cost of this path */
109782  i8 isOrdered;         /* No. of ORDER BY terms satisfied. -1 for unknown */
109783  WhereLoop **aLoop;    /* Array of WhereLoop objects implementing this path */
109784};
109785
109786/*
109787** The query generator uses an array of instances of this structure to
109788** help it analyze the subexpressions of the WHERE clause.  Each WHERE
109789** clause subexpression is separated from the others by AND operators,
109790** usually, or sometimes subexpressions separated by OR.
109791**
109792** All WhereTerms are collected into a single WhereClause structure.
109793** The following identity holds:
109794**
109795**        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
109796**
109797** When a term is of the form:
109798**
109799**              X <op> <expr>
109800**
109801** where X is a column name and <op> is one of certain operators,
109802** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
109803** cursor number and column number for X.  WhereTerm.eOperator records
109804** the <op> using a bitmask encoding defined by WO_xxx below.  The
109805** use of a bitmask encoding for the operator allows us to search
109806** quickly for terms that match any of several different operators.
109807**
109808** A WhereTerm might also be two or more subterms connected by OR:
109809**
109810**         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
109811**
109812** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
109813** and the WhereTerm.u.pOrInfo field points to auxiliary information that
109814** is collected about the OR clause.
109815**
109816** If a term in the WHERE clause does not match either of the two previous
109817** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
109818** to the original subexpression content and wtFlags is set up appropriately
109819** but no other fields in the WhereTerm object are meaningful.
109820**
109821** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
109822** but they do so indirectly.  A single WhereMaskSet structure translates
109823** cursor number into bits and the translated bit is stored in the prereq
109824** fields.  The translation is used in order to maximize the number of
109825** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
109826** spread out over the non-negative integers.  For example, the cursor
109827** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
109828** translates these sparse cursor numbers into consecutive integers
109829** beginning with 0 in order to make the best possible use of the available
109830** bits in the Bitmask.  So, in the example above, the cursor numbers
109831** would be mapped into integers 0 through 7.
109832**
109833** The number of terms in a join is limited by the number of bits
109834** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
109835** is only able to process joins with 64 or fewer tables.
109836*/
109837struct WhereTerm {
109838  Expr *pExpr;            /* Pointer to the subexpression that is this term */
109839  int iParent;            /* Disable pWC->a[iParent] when this term disabled */
109840  int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
109841  union {
109842    int leftColumn;         /* Column number of X in "X <op> <expr>" */
109843    WhereOrInfo *pOrInfo;   /* Extra information if (eOperator & WO_OR)!=0 */
109844    WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
109845  } u;
109846  LogEst truthProb;       /* Probability of truth for this expression */
109847  u16 eOperator;          /* A WO_xx value describing <op> */
109848  u8 wtFlags;             /* TERM_xxx bit flags.  See below */
109849  u8 nChild;              /* Number of children that must disable us */
109850  WhereClause *pWC;       /* The clause this term is part of */
109851  Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
109852  Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
109853};
109854
109855/*
109856** Allowed values of WhereTerm.wtFlags
109857*/
109858#define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
109859#define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
109860#define TERM_CODED      0x04   /* This term is already coded */
109861#define TERM_COPIED     0x08   /* Has a child */
109862#define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
109863#define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
109864#define TERM_OR_OK      0x40   /* Used during OR-clause processing */
109865#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
109866#  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
109867#else
109868#  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
109869#endif
109870
109871/*
109872** An instance of the WhereScan object is used as an iterator for locating
109873** terms in the WHERE clause that are useful to the query planner.
109874*/
109875struct WhereScan {
109876  WhereClause *pOrigWC;      /* Original, innermost WhereClause */
109877  WhereClause *pWC;          /* WhereClause currently being scanned */
109878  char *zCollName;           /* Required collating sequence, if not NULL */
109879  char idxaff;               /* Must match this affinity, if zCollName!=NULL */
109880  unsigned char nEquiv;      /* Number of entries in aEquiv[] */
109881  unsigned char iEquiv;      /* Next unused slot in aEquiv[] */
109882  u32 opMask;                /* Acceptable operators */
109883  int k;                     /* Resume scanning at this->pWC->a[this->k] */
109884  int aEquiv[22];            /* Cursor,Column pairs for equivalence classes */
109885};
109886
109887/*
109888** An instance of the following structure holds all information about a
109889** WHERE clause.  Mostly this is a container for one or more WhereTerms.
109890**
109891** Explanation of pOuter:  For a WHERE clause of the form
109892**
109893**           a AND ((b AND c) OR (d AND e)) AND f
109894**
109895** There are separate WhereClause objects for the whole clause and for
109896** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
109897** subclauses points to the WhereClause object for the whole clause.
109898*/
109899struct WhereClause {
109900  WhereInfo *pWInfo;       /* WHERE clause processing context */
109901  WhereClause *pOuter;     /* Outer conjunction */
109902  u8 op;                   /* Split operator.  TK_AND or TK_OR */
109903  int nTerm;               /* Number of terms */
109904  int nSlot;               /* Number of entries in a[] */
109905  WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
109906#if defined(SQLITE_SMALL_STACK)
109907  WhereTerm aStatic[1];    /* Initial static space for a[] */
109908#else
109909  WhereTerm aStatic[8];    /* Initial static space for a[] */
109910#endif
109911};
109912
109913/*
109914** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
109915** a dynamically allocated instance of the following structure.
109916*/
109917struct WhereOrInfo {
109918  WhereClause wc;          /* Decomposition into subterms */
109919  Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
109920};
109921
109922/*
109923** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
109924** a dynamically allocated instance of the following structure.
109925*/
109926struct WhereAndInfo {
109927  WhereClause wc;          /* The subexpression broken out */
109928};
109929
109930/*
109931** An instance of the following structure keeps track of a mapping
109932** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
109933**
109934** The VDBE cursor numbers are small integers contained in
109935** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
109936** clause, the cursor numbers might not begin with 0 and they might
109937** contain gaps in the numbering sequence.  But we want to make maximum
109938** use of the bits in our bitmasks.  This structure provides a mapping
109939** from the sparse cursor numbers into consecutive integers beginning
109940** with 0.
109941**
109942** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
109943** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
109944**
109945** For example, if the WHERE clause expression used these VDBE
109946** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
109947** would map those cursor numbers into bits 0 through 5.
109948**
109949** Note that the mapping is not necessarily ordered.  In the example
109950** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
109951** 57->5, 73->4.  Or one of 719 other combinations might be used. It
109952** does not really matter.  What is important is that sparse cursor
109953** numbers all get mapped into bit numbers that begin with 0 and contain
109954** no gaps.
109955*/
109956struct WhereMaskSet {
109957  int n;                        /* Number of assigned cursor values */
109958  int ix[BMS];                  /* Cursor assigned to each bit */
109959};
109960
109961/*
109962** This object is a convenience wrapper holding all information needed
109963** to construct WhereLoop objects for a particular query.
109964*/
109965struct WhereLoopBuilder {
109966  WhereInfo *pWInfo;        /* Information about this WHERE */
109967  WhereClause *pWC;         /* WHERE clause terms */
109968  ExprList *pOrderBy;       /* ORDER BY clause */
109969  WhereLoop *pNew;          /* Template WhereLoop */
109970  WhereOrSet *pOrSet;       /* Record best loops here, if not NULL */
109971#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
109972  UnpackedRecord *pRec;     /* Probe for stat4 (if required) */
109973  int nRecValid;            /* Number of valid fields currently in pRec */
109974#endif
109975};
109976
109977/*
109978** The WHERE clause processing routine has two halves.  The
109979** first part does the start of the WHERE loop and the second
109980** half does the tail of the WHERE loop.  An instance of
109981** this structure is returned by the first half and passed
109982** into the second half to give some continuity.
109983**
109984** An instance of this object holds the complete state of the query
109985** planner.
109986*/
109987struct WhereInfo {
109988  Parse *pParse;            /* Parsing and code generating context */
109989  SrcList *pTabList;        /* List of tables in the join */
109990  ExprList *pOrderBy;       /* The ORDER BY clause or NULL */
109991  ExprList *pResultSet;     /* Result set. DISTINCT operates on these */
109992  WhereLoop *pLoops;        /* List of all WhereLoop objects */
109993  Bitmask revMask;          /* Mask of ORDER BY terms that need reversing */
109994  LogEst nRowOut;           /* Estimated number of output rows */
109995  u16 wctrlFlags;           /* Flags originally passed to sqlite3WhereBegin() */
109996  i8 nOBSat;                /* Number of ORDER BY terms satisfied by indices */
109997  u8 sorted;                /* True if really sorted (not just grouped) */
109998  u8 okOnePass;             /* Ok to use one-pass algorithm for UPDATE/DELETE */
109999  u8 untestedTerms;         /* Not all WHERE terms resolved by outer loop */
110000  u8 eDistinct;             /* One of the WHERE_DISTINCT_* values below */
110001  u8 nLevel;                /* Number of nested loop */
110002  int iTop;                 /* The very beginning of the WHERE loop */
110003  int iContinue;            /* Jump here to continue with next record */
110004  int iBreak;               /* Jump here to break out of the loop */
110005  int savedNQueryLoop;      /* pParse->nQueryLoop outside the WHERE loop */
110006  int aiCurOnePass[2];      /* OP_OpenWrite cursors for the ONEPASS opt */
110007  WhereMaskSet sMaskSet;    /* Map cursor numbers to bitmasks */
110008  WhereClause sWC;          /* Decomposition of the WHERE clause */
110009  WhereLevel a[1];          /* Information about each nest loop in WHERE */
110010};
110011
110012/*
110013** Bitmasks for the operators on WhereTerm objects.  These are all
110014** operators that are of interest to the query planner.  An
110015** OR-ed combination of these values can be used when searching for
110016** particular WhereTerms within a WhereClause.
110017*/
110018#define WO_IN     0x001
110019#define WO_EQ     0x002
110020#define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
110021#define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
110022#define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
110023#define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
110024#define WO_MATCH  0x040
110025#define WO_ISNULL 0x080
110026#define WO_OR     0x100       /* Two or more OR-connected terms */
110027#define WO_AND    0x200       /* Two or more AND-connected terms */
110028#define WO_EQUIV  0x400       /* Of the form A==B, both columns */
110029#define WO_NOOP   0x800       /* This term does not restrict search space */
110030
110031#define WO_ALL    0xfff       /* Mask of all possible WO_* values */
110032#define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
110033
110034/*
110035** These are definitions of bits in the WhereLoop.wsFlags field.
110036** The particular combination of bits in each WhereLoop help to
110037** determine the algorithm that WhereLoop represents.
110038*/
110039#define WHERE_COLUMN_EQ    0x00000001  /* x=EXPR */
110040#define WHERE_COLUMN_RANGE 0x00000002  /* x<EXPR and/or x>EXPR */
110041#define WHERE_COLUMN_IN    0x00000004  /* x IN (...) */
110042#define WHERE_COLUMN_NULL  0x00000008  /* x IS NULL */
110043#define WHERE_CONSTRAINT   0x0000000f  /* Any of the WHERE_COLUMN_xxx values */
110044#define WHERE_TOP_LIMIT    0x00000010  /* x<EXPR or x<=EXPR constraint */
110045#define WHERE_BTM_LIMIT    0x00000020  /* x>EXPR or x>=EXPR constraint */
110046#define WHERE_BOTH_LIMIT   0x00000030  /* Both x>EXPR and x<EXPR */
110047#define WHERE_IDX_ONLY     0x00000040  /* Use index only - omit table */
110048#define WHERE_IPK          0x00000100  /* x is the INTEGER PRIMARY KEY */
110049#define WHERE_INDEXED      0x00000200  /* WhereLoop.u.btree.pIndex is valid */
110050#define WHERE_VIRTUALTABLE 0x00000400  /* WhereLoop.u.vtab is valid */
110051#define WHERE_IN_ABLE      0x00000800  /* Able to support an IN operator */
110052#define WHERE_ONEROW       0x00001000  /* Selects no more than one row */
110053#define WHERE_MULTI_OR     0x00002000  /* OR using multiple indices */
110054#define WHERE_AUTO_INDEX   0x00004000  /* Uses an ephemeral index */
110055#define WHERE_SKIPSCAN     0x00008000  /* Uses the skip-scan algorithm */
110056#define WHERE_UNQ_WANTED   0x00010000  /* WHERE_ONEROW would have been helpful*/
110057
110058/************** End of whereInt.h ********************************************/
110059/************** Continuing where we left off in where.c **********************/
110060
110061/*
110062** Return the estimated number of output rows from a WHERE clause
110063*/
110064SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
110065  return sqlite3LogEstToInt(pWInfo->nRowOut);
110066}
110067
110068/*
110069** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
110070** WHERE clause returns outputs for DISTINCT processing.
110071*/
110072SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
110073  return pWInfo->eDistinct;
110074}
110075
110076/*
110077** Return TRUE if the WHERE clause returns rows in ORDER BY order.
110078** Return FALSE if the output needs to be sorted.
110079*/
110080SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
110081  return pWInfo->nOBSat;
110082}
110083
110084/*
110085** Return the VDBE address or label to jump to in order to continue
110086** immediately with the next row of a WHERE clause.
110087*/
110088SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
110089  assert( pWInfo->iContinue!=0 );
110090  return pWInfo->iContinue;
110091}
110092
110093/*
110094** Return the VDBE address or label to jump to in order to break
110095** out of a WHERE loop.
110096*/
110097SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
110098  return pWInfo->iBreak;
110099}
110100
110101/*
110102** Return TRUE if an UPDATE or DELETE statement can operate directly on
110103** the rowids returned by a WHERE clause.  Return FALSE if doing an
110104** UPDATE or DELETE might change subsequent WHERE clause results.
110105**
110106** If the ONEPASS optimization is used (if this routine returns true)
110107** then also write the indices of open cursors used by ONEPASS
110108** into aiCur[0] and aiCur[1].  iaCur[0] gets the cursor of the data
110109** table and iaCur[1] gets the cursor used by an auxiliary index.
110110** Either value may be -1, indicating that cursor is not used.
110111** Any cursors returned will have been opened for writing.
110112**
110113** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
110114** unable to use the ONEPASS optimization.
110115*/
110116SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
110117  memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
110118  return pWInfo->okOnePass;
110119}
110120
110121/*
110122** Move the content of pSrc into pDest
110123*/
110124static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
110125  pDest->n = pSrc->n;
110126  memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
110127}
110128
110129/*
110130** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
110131**
110132** The new entry might overwrite an existing entry, or it might be
110133** appended, or it might be discarded.  Do whatever is the right thing
110134** so that pSet keeps the N_OR_COST best entries seen so far.
110135*/
110136static int whereOrInsert(
110137  WhereOrSet *pSet,      /* The WhereOrSet to be updated */
110138  Bitmask prereq,        /* Prerequisites of the new entry */
110139  LogEst rRun,           /* Run-cost of the new entry */
110140  LogEst nOut            /* Number of outputs for the new entry */
110141){
110142  u16 i;
110143  WhereOrCost *p;
110144  for(i=pSet->n, p=pSet->a; i>0; i--, p++){
110145    if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
110146      goto whereOrInsert_done;
110147    }
110148    if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
110149      return 0;
110150    }
110151  }
110152  if( pSet->n<N_OR_COST ){
110153    p = &pSet->a[pSet->n++];
110154    p->nOut = nOut;
110155  }else{
110156    p = pSet->a;
110157    for(i=1; i<pSet->n; i++){
110158      if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
110159    }
110160    if( p->rRun<=rRun ) return 0;
110161  }
110162whereOrInsert_done:
110163  p->prereq = prereq;
110164  p->rRun = rRun;
110165  if( p->nOut>nOut ) p->nOut = nOut;
110166  return 1;
110167}
110168
110169/*
110170** Initialize a preallocated WhereClause structure.
110171*/
110172static void whereClauseInit(
110173  WhereClause *pWC,        /* The WhereClause to be initialized */
110174  WhereInfo *pWInfo        /* The WHERE processing context */
110175){
110176  pWC->pWInfo = pWInfo;
110177  pWC->pOuter = 0;
110178  pWC->nTerm = 0;
110179  pWC->nSlot = ArraySize(pWC->aStatic);
110180  pWC->a = pWC->aStatic;
110181}
110182
110183/* Forward reference */
110184static void whereClauseClear(WhereClause*);
110185
110186/*
110187** Deallocate all memory associated with a WhereOrInfo object.
110188*/
110189static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
110190  whereClauseClear(&p->wc);
110191  sqlite3DbFree(db, p);
110192}
110193
110194/*
110195** Deallocate all memory associated with a WhereAndInfo object.
110196*/
110197static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
110198  whereClauseClear(&p->wc);
110199  sqlite3DbFree(db, p);
110200}
110201
110202/*
110203** Deallocate a WhereClause structure.  The WhereClause structure
110204** itself is not freed.  This routine is the inverse of whereClauseInit().
110205*/
110206static void whereClauseClear(WhereClause *pWC){
110207  int i;
110208  WhereTerm *a;
110209  sqlite3 *db = pWC->pWInfo->pParse->db;
110210  for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
110211    if( a->wtFlags & TERM_DYNAMIC ){
110212      sqlite3ExprDelete(db, a->pExpr);
110213    }
110214    if( a->wtFlags & TERM_ORINFO ){
110215      whereOrInfoDelete(db, a->u.pOrInfo);
110216    }else if( a->wtFlags & TERM_ANDINFO ){
110217      whereAndInfoDelete(db, a->u.pAndInfo);
110218    }
110219  }
110220  if( pWC->a!=pWC->aStatic ){
110221    sqlite3DbFree(db, pWC->a);
110222  }
110223}
110224
110225/*
110226** Add a single new WhereTerm entry to the WhereClause object pWC.
110227** The new WhereTerm object is constructed from Expr p and with wtFlags.
110228** The index in pWC->a[] of the new WhereTerm is returned on success.
110229** 0 is returned if the new WhereTerm could not be added due to a memory
110230** allocation error.  The memory allocation failure will be recorded in
110231** the db->mallocFailed flag so that higher-level functions can detect it.
110232**
110233** This routine will increase the size of the pWC->a[] array as necessary.
110234**
110235** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
110236** for freeing the expression p is assumed by the WhereClause object pWC.
110237** This is true even if this routine fails to allocate a new WhereTerm.
110238**
110239** WARNING:  This routine might reallocate the space used to store
110240** WhereTerms.  All pointers to WhereTerms should be invalidated after
110241** calling this routine.  Such pointers may be reinitialized by referencing
110242** the pWC->a[] array.
110243*/
110244static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
110245  WhereTerm *pTerm;
110246  int idx;
110247  testcase( wtFlags & TERM_VIRTUAL );
110248  if( pWC->nTerm>=pWC->nSlot ){
110249    WhereTerm *pOld = pWC->a;
110250    sqlite3 *db = pWC->pWInfo->pParse->db;
110251    pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
110252    if( pWC->a==0 ){
110253      if( wtFlags & TERM_DYNAMIC ){
110254        sqlite3ExprDelete(db, p);
110255      }
110256      pWC->a = pOld;
110257      return 0;
110258    }
110259    memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
110260    if( pOld!=pWC->aStatic ){
110261      sqlite3DbFree(db, pOld);
110262    }
110263    pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
110264  }
110265  pTerm = &pWC->a[idx = pWC->nTerm++];
110266  if( p && ExprHasProperty(p, EP_Unlikely) ){
110267    pTerm->truthProb = sqlite3LogEst(p->iTable) - 99;
110268  }else{
110269    pTerm->truthProb = 1;
110270  }
110271  pTerm->pExpr = sqlite3ExprSkipCollate(p);
110272  pTerm->wtFlags = wtFlags;
110273  pTerm->pWC = pWC;
110274  pTerm->iParent = -1;
110275  return idx;
110276}
110277
110278/*
110279** This routine identifies subexpressions in the WHERE clause where
110280** each subexpression is separated by the AND operator or some other
110281** operator specified in the op parameter.  The WhereClause structure
110282** is filled with pointers to subexpressions.  For example:
110283**
110284**    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
110285**           \________/     \_______________/     \________________/
110286**            slot[0]            slot[1]               slot[2]
110287**
110288** The original WHERE clause in pExpr is unaltered.  All this routine
110289** does is make slot[] entries point to substructure within pExpr.
110290**
110291** In the previous sentence and in the diagram, "slot[]" refers to
110292** the WhereClause.a[] array.  The slot[] array grows as needed to contain
110293** all terms of the WHERE clause.
110294*/
110295static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
110296  pWC->op = op;
110297  if( pExpr==0 ) return;
110298  if( pExpr->op!=op ){
110299    whereClauseInsert(pWC, pExpr, 0);
110300  }else{
110301    whereSplit(pWC, pExpr->pLeft, op);
110302    whereSplit(pWC, pExpr->pRight, op);
110303  }
110304}
110305
110306/*
110307** Initialize a WhereMaskSet object
110308*/
110309#define initMaskSet(P)  (P)->n=0
110310
110311/*
110312** Return the bitmask for the given cursor number.  Return 0 if
110313** iCursor is not in the set.
110314*/
110315static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
110316  int i;
110317  assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
110318  for(i=0; i<pMaskSet->n; i++){
110319    if( pMaskSet->ix[i]==iCursor ){
110320      return MASKBIT(i);
110321    }
110322  }
110323  return 0;
110324}
110325
110326/*
110327** Create a new mask for cursor iCursor.
110328**
110329** There is one cursor per table in the FROM clause.  The number of
110330** tables in the FROM clause is limited by a test early in the
110331** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
110332** array will never overflow.
110333*/
110334static void createMask(WhereMaskSet *pMaskSet, int iCursor){
110335  assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
110336  pMaskSet->ix[pMaskSet->n++] = iCursor;
110337}
110338
110339/*
110340** These routines walk (recursively) an expression tree and generate
110341** a bitmask indicating which tables are used in that expression
110342** tree.
110343*/
110344static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
110345static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
110346static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
110347  Bitmask mask = 0;
110348  if( p==0 ) return 0;
110349  if( p->op==TK_COLUMN ){
110350    mask = getMask(pMaskSet, p->iTable);
110351    return mask;
110352  }
110353  mask = exprTableUsage(pMaskSet, p->pRight);
110354  mask |= exprTableUsage(pMaskSet, p->pLeft);
110355  if( ExprHasProperty(p, EP_xIsSelect) ){
110356    mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
110357  }else{
110358    mask |= exprListTableUsage(pMaskSet, p->x.pList);
110359  }
110360  return mask;
110361}
110362static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
110363  int i;
110364  Bitmask mask = 0;
110365  if( pList ){
110366    for(i=0; i<pList->nExpr; i++){
110367      mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
110368    }
110369  }
110370  return mask;
110371}
110372static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
110373  Bitmask mask = 0;
110374  while( pS ){
110375    SrcList *pSrc = pS->pSrc;
110376    mask |= exprListTableUsage(pMaskSet, pS->pEList);
110377    mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
110378    mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
110379    mask |= exprTableUsage(pMaskSet, pS->pWhere);
110380    mask |= exprTableUsage(pMaskSet, pS->pHaving);
110381    if( ALWAYS(pSrc!=0) ){
110382      int i;
110383      for(i=0; i<pSrc->nSrc; i++){
110384        mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
110385        mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
110386      }
110387    }
110388    pS = pS->pPrior;
110389  }
110390  return mask;
110391}
110392
110393/*
110394** Return TRUE if the given operator is one of the operators that is
110395** allowed for an indexable WHERE clause term.  The allowed operators are
110396** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
110397*/
110398static int allowedOp(int op){
110399  assert( TK_GT>TK_EQ && TK_GT<TK_GE );
110400  assert( TK_LT>TK_EQ && TK_LT<TK_GE );
110401  assert( TK_LE>TK_EQ && TK_LE<TK_GE );
110402  assert( TK_GE==TK_EQ+4 );
110403  return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
110404}
110405
110406/*
110407** Swap two objects of type TYPE.
110408*/
110409#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
110410
110411/*
110412** Commute a comparison operator.  Expressions of the form "X op Y"
110413** are converted into "Y op X".
110414**
110415** If left/right precedence rules come into play when determining the
110416** collating sequence, then COLLATE operators are adjusted to ensure
110417** that the collating sequence does not change.  For example:
110418** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
110419** the left hand side of a comparison overrides any collation sequence
110420** attached to the right. For the same reason the EP_Collate flag
110421** is not commuted.
110422*/
110423static void exprCommute(Parse *pParse, Expr *pExpr){
110424  u16 expRight = (pExpr->pRight->flags & EP_Collate);
110425  u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
110426  assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
110427  if( expRight==expLeft ){
110428    /* Either X and Y both have COLLATE operator or neither do */
110429    if( expRight ){
110430      /* Both X and Y have COLLATE operators.  Make sure X is always
110431      ** used by clearing the EP_Collate flag from Y. */
110432      pExpr->pRight->flags &= ~EP_Collate;
110433    }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
110434      /* Neither X nor Y have COLLATE operators, but X has a non-default
110435      ** collating sequence.  So add the EP_Collate marker on X to cause
110436      ** it to be searched first. */
110437      pExpr->pLeft->flags |= EP_Collate;
110438    }
110439  }
110440  SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
110441  if( pExpr->op>=TK_GT ){
110442    assert( TK_LT==TK_GT+2 );
110443    assert( TK_GE==TK_LE+2 );
110444    assert( TK_GT>TK_EQ );
110445    assert( TK_GT<TK_LE );
110446    assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
110447    pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
110448  }
110449}
110450
110451/*
110452** Translate from TK_xx operator to WO_xx bitmask.
110453*/
110454static u16 operatorMask(int op){
110455  u16 c;
110456  assert( allowedOp(op) );
110457  if( op==TK_IN ){
110458    c = WO_IN;
110459  }else if( op==TK_ISNULL ){
110460    c = WO_ISNULL;
110461  }else{
110462    assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
110463    c = (u16)(WO_EQ<<(op-TK_EQ));
110464  }
110465  assert( op!=TK_ISNULL || c==WO_ISNULL );
110466  assert( op!=TK_IN || c==WO_IN );
110467  assert( op!=TK_EQ || c==WO_EQ );
110468  assert( op!=TK_LT || c==WO_LT );
110469  assert( op!=TK_LE || c==WO_LE );
110470  assert( op!=TK_GT || c==WO_GT );
110471  assert( op!=TK_GE || c==WO_GE );
110472  return c;
110473}
110474
110475/*
110476** Advance to the next WhereTerm that matches according to the criteria
110477** established when the pScan object was initialized by whereScanInit().
110478** Return NULL if there are no more matching WhereTerms.
110479*/
110480static WhereTerm *whereScanNext(WhereScan *pScan){
110481  int iCur;            /* The cursor on the LHS of the term */
110482  int iColumn;         /* The column on the LHS of the term.  -1 for IPK */
110483  Expr *pX;            /* An expression being tested */
110484  WhereClause *pWC;    /* Shorthand for pScan->pWC */
110485  WhereTerm *pTerm;    /* The term being tested */
110486  int k = pScan->k;    /* Where to start scanning */
110487
110488  while( pScan->iEquiv<=pScan->nEquiv ){
110489    iCur = pScan->aEquiv[pScan->iEquiv-2];
110490    iColumn = pScan->aEquiv[pScan->iEquiv-1];
110491    while( (pWC = pScan->pWC)!=0 ){
110492      for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
110493        if( pTerm->leftCursor==iCur
110494         && pTerm->u.leftColumn==iColumn
110495         && (pScan->iEquiv<=2 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
110496        ){
110497          if( (pTerm->eOperator & WO_EQUIV)!=0
110498           && pScan->nEquiv<ArraySize(pScan->aEquiv)
110499          ){
110500            int j;
110501            pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
110502            assert( pX->op==TK_COLUMN );
110503            for(j=0; j<pScan->nEquiv; j+=2){
110504              if( pScan->aEquiv[j]==pX->iTable
110505               && pScan->aEquiv[j+1]==pX->iColumn ){
110506                  break;
110507              }
110508            }
110509            if( j==pScan->nEquiv ){
110510              pScan->aEquiv[j] = pX->iTable;
110511              pScan->aEquiv[j+1] = pX->iColumn;
110512              pScan->nEquiv += 2;
110513            }
110514          }
110515          if( (pTerm->eOperator & pScan->opMask)!=0 ){
110516            /* Verify the affinity and collating sequence match */
110517            if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
110518              CollSeq *pColl;
110519              Parse *pParse = pWC->pWInfo->pParse;
110520              pX = pTerm->pExpr;
110521              if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
110522                continue;
110523              }
110524              assert(pX->pLeft);
110525              pColl = sqlite3BinaryCompareCollSeq(pParse,
110526                                                  pX->pLeft, pX->pRight);
110527              if( pColl==0 ) pColl = pParse->db->pDfltColl;
110528              if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
110529                continue;
110530              }
110531            }
110532            if( (pTerm->eOperator & WO_EQ)!=0
110533             && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
110534             && pX->iTable==pScan->aEquiv[0]
110535             && pX->iColumn==pScan->aEquiv[1]
110536            ){
110537              continue;
110538            }
110539            pScan->k = k+1;
110540            return pTerm;
110541          }
110542        }
110543      }
110544      pScan->pWC = pScan->pWC->pOuter;
110545      k = 0;
110546    }
110547    pScan->pWC = pScan->pOrigWC;
110548    k = 0;
110549    pScan->iEquiv += 2;
110550  }
110551  return 0;
110552}
110553
110554/*
110555** Initialize a WHERE clause scanner object.  Return a pointer to the
110556** first match.  Return NULL if there are no matches.
110557**
110558** The scanner will be searching the WHERE clause pWC.  It will look
110559** for terms of the form "X <op> <expr>" where X is column iColumn of table
110560** iCur.  The <op> must be one of the operators described by opMask.
110561**
110562** If the search is for X and the WHERE clause contains terms of the
110563** form X=Y then this routine might also return terms of the form
110564** "Y <op> <expr>".  The number of levels of transitivity is limited,
110565** but is enough to handle most commonly occurring SQL statements.
110566**
110567** If X is not the INTEGER PRIMARY KEY then X must be compatible with
110568** index pIdx.
110569*/
110570static WhereTerm *whereScanInit(
110571  WhereScan *pScan,       /* The WhereScan object being initialized */
110572  WhereClause *pWC,       /* The WHERE clause to be scanned */
110573  int iCur,               /* Cursor to scan for */
110574  int iColumn,            /* Column to scan for */
110575  u32 opMask,             /* Operator(s) to scan for */
110576  Index *pIdx             /* Must be compatible with this index */
110577){
110578  int j;
110579
110580  /* memset(pScan, 0, sizeof(*pScan)); */
110581  pScan->pOrigWC = pWC;
110582  pScan->pWC = pWC;
110583  if( pIdx && iColumn>=0 ){
110584    pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
110585    for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
110586      if( NEVER(j>=pIdx->nKeyCol) ) return 0;
110587    }
110588    pScan->zCollName = pIdx->azColl[j];
110589  }else{
110590    pScan->idxaff = 0;
110591    pScan->zCollName = 0;
110592  }
110593  pScan->opMask = opMask;
110594  pScan->k = 0;
110595  pScan->aEquiv[0] = iCur;
110596  pScan->aEquiv[1] = iColumn;
110597  pScan->nEquiv = 2;
110598  pScan->iEquiv = 2;
110599  return whereScanNext(pScan);
110600}
110601
110602/*
110603** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
110604** where X is a reference to the iColumn of table iCur and <op> is one of
110605** the WO_xx operator codes specified by the op parameter.
110606** Return a pointer to the term.  Return 0 if not found.
110607**
110608** The term returned might by Y=<expr> if there is another constraint in
110609** the WHERE clause that specifies that X=Y.  Any such constraints will be
110610** identified by the WO_EQUIV bit in the pTerm->eOperator field.  The
110611** aEquiv[] array holds X and all its equivalents, with each SQL variable
110612** taking up two slots in aEquiv[].  The first slot is for the cursor number
110613** and the second is for the column number.  There are 22 slots in aEquiv[]
110614** so that means we can look for X plus up to 10 other equivalent values.
110615** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
110616** and ... and A9=A10 and A10=<expr>.
110617**
110618** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
110619** then try for the one with no dependencies on <expr> - in other words where
110620** <expr> is a constant expression of some kind.  Only return entries of
110621** the form "X <op> Y" where Y is a column in another table if no terms of
110622** the form "X <op> <const-expr>" exist.   If no terms with a constant RHS
110623** exist, try to return a term that does not use WO_EQUIV.
110624*/
110625static WhereTerm *findTerm(
110626  WhereClause *pWC,     /* The WHERE clause to be searched */
110627  int iCur,             /* Cursor number of LHS */
110628  int iColumn,          /* Column number of LHS */
110629  Bitmask notReady,     /* RHS must not overlap with this mask */
110630  u32 op,               /* Mask of WO_xx values describing operator */
110631  Index *pIdx           /* Must be compatible with this index, if not NULL */
110632){
110633  WhereTerm *pResult = 0;
110634  WhereTerm *p;
110635  WhereScan scan;
110636
110637  p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
110638  while( p ){
110639    if( (p->prereqRight & notReady)==0 ){
110640      if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
110641        return p;
110642      }
110643      if( pResult==0 ) pResult = p;
110644    }
110645    p = whereScanNext(&scan);
110646  }
110647  return pResult;
110648}
110649
110650/* Forward reference */
110651static void exprAnalyze(SrcList*, WhereClause*, int);
110652
110653/*
110654** Call exprAnalyze on all terms in a WHERE clause.
110655*/
110656static void exprAnalyzeAll(
110657  SrcList *pTabList,       /* the FROM clause */
110658  WhereClause *pWC         /* the WHERE clause to be analyzed */
110659){
110660  int i;
110661  for(i=pWC->nTerm-1; i>=0; i--){
110662    exprAnalyze(pTabList, pWC, i);
110663  }
110664}
110665
110666#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
110667/*
110668** Check to see if the given expression is a LIKE or GLOB operator that
110669** can be optimized using inequality constraints.  Return TRUE if it is
110670** so and false if not.
110671**
110672** In order for the operator to be optimizible, the RHS must be a string
110673** literal that does not begin with a wildcard.
110674*/
110675static int isLikeOrGlob(
110676  Parse *pParse,    /* Parsing and code generating context */
110677  Expr *pExpr,      /* Test this expression */
110678  Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
110679  int *pisComplete, /* True if the only wildcard is % in the last character */
110680  int *pnoCase      /* True if uppercase is equivalent to lowercase */
110681){
110682  const char *z = 0;         /* String on RHS of LIKE operator */
110683  Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
110684  ExprList *pList;           /* List of operands to the LIKE operator */
110685  int c;                     /* One character in z[] */
110686  int cnt;                   /* Number of non-wildcard prefix characters */
110687  char wc[3];                /* Wildcard characters */
110688  sqlite3 *db = pParse->db;  /* Database connection */
110689  sqlite3_value *pVal = 0;
110690  int op;                    /* Opcode of pRight */
110691
110692  if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
110693    return 0;
110694  }
110695#ifdef SQLITE_EBCDIC
110696  if( *pnoCase ) return 0;
110697#endif
110698  pList = pExpr->x.pList;
110699  pLeft = pList->a[1].pExpr;
110700  if( pLeft->op!=TK_COLUMN
110701   || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
110702   || IsVirtual(pLeft->pTab)
110703  ){
110704    /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
110705    ** be the name of an indexed column with TEXT affinity. */
110706    return 0;
110707  }
110708  assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
110709
110710  pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
110711  op = pRight->op;
110712  if( op==TK_VARIABLE ){
110713    Vdbe *pReprepare = pParse->pReprepare;
110714    int iCol = pRight->iColumn;
110715    pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
110716    if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
110717      z = (char *)sqlite3_value_text(pVal);
110718    }
110719    sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
110720    assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
110721  }else if( op==TK_STRING ){
110722    z = pRight->u.zToken;
110723  }
110724  if( z ){
110725    cnt = 0;
110726    while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
110727      cnt++;
110728    }
110729    if( cnt!=0 && 255!=(u8)z[cnt-1] ){
110730      Expr *pPrefix;
110731      *pisComplete = c==wc[0] && z[cnt+1]==0;
110732      pPrefix = sqlite3Expr(db, TK_STRING, z);
110733      if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
110734      *ppPrefix = pPrefix;
110735      if( op==TK_VARIABLE ){
110736        Vdbe *v = pParse->pVdbe;
110737        sqlite3VdbeSetVarmask(v, pRight->iColumn);
110738        if( *pisComplete && pRight->u.zToken[1] ){
110739          /* If the rhs of the LIKE expression is a variable, and the current
110740          ** value of the variable means there is no need to invoke the LIKE
110741          ** function, then no OP_Variable will be added to the program.
110742          ** This causes problems for the sqlite3_bind_parameter_name()
110743          ** API. To workaround them, add a dummy OP_Variable here.
110744          */
110745          int r1 = sqlite3GetTempReg(pParse);
110746          sqlite3ExprCodeTarget(pParse, pRight, r1);
110747          sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
110748          sqlite3ReleaseTempReg(pParse, r1);
110749        }
110750      }
110751    }else{
110752      z = 0;
110753    }
110754  }
110755
110756  sqlite3ValueFree(pVal);
110757  return (z!=0);
110758}
110759#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
110760
110761
110762#ifndef SQLITE_OMIT_VIRTUALTABLE
110763/*
110764** Check to see if the given expression is of the form
110765**
110766**         column MATCH expr
110767**
110768** If it is then return TRUE.  If not, return FALSE.
110769*/
110770static int isMatchOfColumn(
110771  Expr *pExpr      /* Test this expression */
110772){
110773  ExprList *pList;
110774
110775  if( pExpr->op!=TK_FUNCTION ){
110776    return 0;
110777  }
110778  if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
110779    return 0;
110780  }
110781  pList = pExpr->x.pList;
110782  if( pList->nExpr!=2 ){
110783    return 0;
110784  }
110785  if( pList->a[1].pExpr->op != TK_COLUMN ){
110786    return 0;
110787  }
110788  return 1;
110789}
110790#endif /* SQLITE_OMIT_VIRTUALTABLE */
110791
110792/*
110793** If the pBase expression originated in the ON or USING clause of
110794** a join, then transfer the appropriate markings over to derived.
110795*/
110796static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
110797  if( pDerived ){
110798    pDerived->flags |= pBase->flags & EP_FromJoin;
110799    pDerived->iRightJoinTable = pBase->iRightJoinTable;
110800  }
110801}
110802
110803#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
110804/*
110805** Analyze a term that consists of two or more OR-connected
110806** subterms.  So in:
110807**
110808**     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
110809**                          ^^^^^^^^^^^^^^^^^^^^
110810**
110811** This routine analyzes terms such as the middle term in the above example.
110812** A WhereOrTerm object is computed and attached to the term under
110813** analysis, regardless of the outcome of the analysis.  Hence:
110814**
110815**     WhereTerm.wtFlags   |=  TERM_ORINFO
110816**     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
110817**
110818** The term being analyzed must have two or more of OR-connected subterms.
110819** A single subterm might be a set of AND-connected sub-subterms.
110820** Examples of terms under analysis:
110821**
110822**     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
110823**     (B)     x=expr1 OR expr2=x OR x=expr3
110824**     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
110825**     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
110826**     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
110827**
110828** CASE 1:
110829**
110830** If all subterms are of the form T.C=expr for some single column of C and
110831** a single table T (as shown in example B above) then create a new virtual
110832** term that is an equivalent IN expression.  In other words, if the term
110833** being analyzed is:
110834**
110835**      x = expr1  OR  expr2 = x  OR  x = expr3
110836**
110837** then create a new virtual term like this:
110838**
110839**      x IN (expr1,expr2,expr3)
110840**
110841** CASE 2:
110842**
110843** If all subterms are indexable by a single table T, then set
110844**
110845**     WhereTerm.eOperator              =  WO_OR
110846**     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
110847**
110848** A subterm is "indexable" if it is of the form
110849** "T.C <op> <expr>" where C is any column of table T and
110850** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
110851** A subterm is also indexable if it is an AND of two or more
110852** subsubterms at least one of which is indexable.  Indexable AND
110853** subterms have their eOperator set to WO_AND and they have
110854** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
110855**
110856** From another point of view, "indexable" means that the subterm could
110857** potentially be used with an index if an appropriate index exists.
110858** This analysis does not consider whether or not the index exists; that
110859** is decided elsewhere.  This analysis only looks at whether subterms
110860** appropriate for indexing exist.
110861**
110862** All examples A through E above satisfy case 2.  But if a term
110863** also statisfies case 1 (such as B) we know that the optimizer will
110864** always prefer case 1, so in that case we pretend that case 2 is not
110865** satisfied.
110866**
110867** It might be the case that multiple tables are indexable.  For example,
110868** (E) above is indexable on tables P, Q, and R.
110869**
110870** Terms that satisfy case 2 are candidates for lookup by using
110871** separate indices to find rowids for each subterm and composing
110872** the union of all rowids using a RowSet object.  This is similar
110873** to "bitmap indices" in other database engines.
110874**
110875** OTHERWISE:
110876**
110877** If neither case 1 nor case 2 apply, then leave the eOperator set to
110878** zero.  This term is not useful for search.
110879*/
110880static void exprAnalyzeOrTerm(
110881  SrcList *pSrc,            /* the FROM clause */
110882  WhereClause *pWC,         /* the complete WHERE clause */
110883  int idxTerm               /* Index of the OR-term to be analyzed */
110884){
110885  WhereInfo *pWInfo = pWC->pWInfo;        /* WHERE clause processing context */
110886  Parse *pParse = pWInfo->pParse;         /* Parser context */
110887  sqlite3 *db = pParse->db;               /* Database connection */
110888  WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
110889  Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
110890  int i;                                  /* Loop counters */
110891  WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
110892  WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
110893  WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
110894  Bitmask chngToIN;         /* Tables that might satisfy case 1 */
110895  Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
110896
110897  /*
110898  ** Break the OR clause into its separate subterms.  The subterms are
110899  ** stored in a WhereClause structure containing within the WhereOrInfo
110900  ** object that is attached to the original OR clause term.
110901  */
110902  assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
110903  assert( pExpr->op==TK_OR );
110904  pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
110905  if( pOrInfo==0 ) return;
110906  pTerm->wtFlags |= TERM_ORINFO;
110907  pOrWc = &pOrInfo->wc;
110908  whereClauseInit(pOrWc, pWInfo);
110909  whereSplit(pOrWc, pExpr, TK_OR);
110910  exprAnalyzeAll(pSrc, pOrWc);
110911  if( db->mallocFailed ) return;
110912  assert( pOrWc->nTerm>=2 );
110913
110914  /*
110915  ** Compute the set of tables that might satisfy cases 1 or 2.
110916  */
110917  indexable = ~(Bitmask)0;
110918  chngToIN = ~(Bitmask)0;
110919  for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
110920    if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
110921      WhereAndInfo *pAndInfo;
110922      assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
110923      chngToIN = 0;
110924      pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
110925      if( pAndInfo ){
110926        WhereClause *pAndWC;
110927        WhereTerm *pAndTerm;
110928        int j;
110929        Bitmask b = 0;
110930        pOrTerm->u.pAndInfo = pAndInfo;
110931        pOrTerm->wtFlags |= TERM_ANDINFO;
110932        pOrTerm->eOperator = WO_AND;
110933        pAndWC = &pAndInfo->wc;
110934        whereClauseInit(pAndWC, pWC->pWInfo);
110935        whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
110936        exprAnalyzeAll(pSrc, pAndWC);
110937        pAndWC->pOuter = pWC;
110938        testcase( db->mallocFailed );
110939        if( !db->mallocFailed ){
110940          for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
110941            assert( pAndTerm->pExpr );
110942            if( allowedOp(pAndTerm->pExpr->op) ){
110943              b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
110944            }
110945          }
110946        }
110947        indexable &= b;
110948      }
110949    }else if( pOrTerm->wtFlags & TERM_COPIED ){
110950      /* Skip this term for now.  We revisit it when we process the
110951      ** corresponding TERM_VIRTUAL term */
110952    }else{
110953      Bitmask b;
110954      b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
110955      if( pOrTerm->wtFlags & TERM_VIRTUAL ){
110956        WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
110957        b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
110958      }
110959      indexable &= b;
110960      if( (pOrTerm->eOperator & WO_EQ)==0 ){
110961        chngToIN = 0;
110962      }else{
110963        chngToIN &= b;
110964      }
110965    }
110966  }
110967
110968  /*
110969  ** Record the set of tables that satisfy case 2.  The set might be
110970  ** empty.
110971  */
110972  pOrInfo->indexable = indexable;
110973  pTerm->eOperator = indexable==0 ? 0 : WO_OR;
110974
110975  /*
110976  ** chngToIN holds a set of tables that *might* satisfy case 1.  But
110977  ** we have to do some additional checking to see if case 1 really
110978  ** is satisfied.
110979  **
110980  ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
110981  ** that there is no possibility of transforming the OR clause into an
110982  ** IN operator because one or more terms in the OR clause contain
110983  ** something other than == on a column in the single table.  The 1-bit
110984  ** case means that every term of the OR clause is of the form
110985  ** "table.column=expr" for some single table.  The one bit that is set
110986  ** will correspond to the common table.  We still need to check to make
110987  ** sure the same column is used on all terms.  The 2-bit case is when
110988  ** the all terms are of the form "table1.column=table2.column".  It
110989  ** might be possible to form an IN operator with either table1.column
110990  ** or table2.column as the LHS if either is common to every term of
110991  ** the OR clause.
110992  **
110993  ** Note that terms of the form "table.column1=table.column2" (the
110994  ** same table on both sizes of the ==) cannot be optimized.
110995  */
110996  if( chngToIN ){
110997    int okToChngToIN = 0;     /* True if the conversion to IN is valid */
110998    int iColumn = -1;         /* Column index on lhs of IN operator */
110999    int iCursor = -1;         /* Table cursor common to all terms */
111000    int j = 0;                /* Loop counter */
111001
111002    /* Search for a table and column that appears on one side or the
111003    ** other of the == operator in every subterm.  That table and column
111004    ** will be recorded in iCursor and iColumn.  There might not be any
111005    ** such table and column.  Set okToChngToIN if an appropriate table
111006    ** and column is found but leave okToChngToIN false if not found.
111007    */
111008    for(j=0; j<2 && !okToChngToIN; j++){
111009      pOrTerm = pOrWc->a;
111010      for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
111011        assert( pOrTerm->eOperator & WO_EQ );
111012        pOrTerm->wtFlags &= ~TERM_OR_OK;
111013        if( pOrTerm->leftCursor==iCursor ){
111014          /* This is the 2-bit case and we are on the second iteration and
111015          ** current term is from the first iteration.  So skip this term. */
111016          assert( j==1 );
111017          continue;
111018        }
111019        if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
111020          /* This term must be of the form t1.a==t2.b where t2 is in the
111021          ** chngToIN set but t1 is not.  This term will be either preceeded
111022          ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
111023          ** and use its inversion. */
111024          testcase( pOrTerm->wtFlags & TERM_COPIED );
111025          testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
111026          assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
111027          continue;
111028        }
111029        iColumn = pOrTerm->u.leftColumn;
111030        iCursor = pOrTerm->leftCursor;
111031        break;
111032      }
111033      if( i<0 ){
111034        /* No candidate table+column was found.  This can only occur
111035        ** on the second iteration */
111036        assert( j==1 );
111037        assert( IsPowerOfTwo(chngToIN) );
111038        assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
111039        break;
111040      }
111041      testcase( j==1 );
111042
111043      /* We have found a candidate table and column.  Check to see if that
111044      ** table and column is common to every term in the OR clause */
111045      okToChngToIN = 1;
111046      for(; i>=0 && okToChngToIN; i--, pOrTerm++){
111047        assert( pOrTerm->eOperator & WO_EQ );
111048        if( pOrTerm->leftCursor!=iCursor ){
111049          pOrTerm->wtFlags &= ~TERM_OR_OK;
111050        }else if( pOrTerm->u.leftColumn!=iColumn ){
111051          okToChngToIN = 0;
111052        }else{
111053          int affLeft, affRight;
111054          /* If the right-hand side is also a column, then the affinities
111055          ** of both right and left sides must be such that no type
111056          ** conversions are required on the right.  (Ticket #2249)
111057          */
111058          affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
111059          affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
111060          if( affRight!=0 && affRight!=affLeft ){
111061            okToChngToIN = 0;
111062          }else{
111063            pOrTerm->wtFlags |= TERM_OR_OK;
111064          }
111065        }
111066      }
111067    }
111068
111069    /* At this point, okToChngToIN is true if original pTerm satisfies
111070    ** case 1.  In that case, construct a new virtual term that is
111071    ** pTerm converted into an IN operator.
111072    */
111073    if( okToChngToIN ){
111074      Expr *pDup;            /* A transient duplicate expression */
111075      ExprList *pList = 0;   /* The RHS of the IN operator */
111076      Expr *pLeft = 0;       /* The LHS of the IN operator */
111077      Expr *pNew;            /* The complete IN operator */
111078
111079      for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
111080        if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
111081        assert( pOrTerm->eOperator & WO_EQ );
111082        assert( pOrTerm->leftCursor==iCursor );
111083        assert( pOrTerm->u.leftColumn==iColumn );
111084        pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
111085        pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
111086        pLeft = pOrTerm->pExpr->pLeft;
111087      }
111088      assert( pLeft!=0 );
111089      pDup = sqlite3ExprDup(db, pLeft, 0);
111090      pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
111091      if( pNew ){
111092        int idxNew;
111093        transferJoinMarkings(pNew, pExpr);
111094        assert( !ExprHasProperty(pNew, EP_xIsSelect) );
111095        pNew->x.pList = pList;
111096        idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
111097        testcase( idxNew==0 );
111098        exprAnalyze(pSrc, pWC, idxNew);
111099        pTerm = &pWC->a[idxTerm];
111100        pWC->a[idxNew].iParent = idxTerm;
111101        pTerm->nChild = 1;
111102      }else{
111103        sqlite3ExprListDelete(db, pList);
111104      }
111105      pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 2 */
111106    }
111107  }
111108}
111109#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
111110
111111/*
111112** The input to this routine is an WhereTerm structure with only the
111113** "pExpr" field filled in.  The job of this routine is to analyze the
111114** subexpression and populate all the other fields of the WhereTerm
111115** structure.
111116**
111117** If the expression is of the form "<expr> <op> X" it gets commuted
111118** to the standard form of "X <op> <expr>".
111119**
111120** If the expression is of the form "X <op> Y" where both X and Y are
111121** columns, then the original expression is unchanged and a new virtual
111122** term of the form "Y <op> X" is added to the WHERE clause and
111123** analyzed separately.  The original term is marked with TERM_COPIED
111124** and the new term is marked with TERM_DYNAMIC (because it's pExpr
111125** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
111126** is a commuted copy of a prior term.)  The original term has nChild=1
111127** and the copy has idxParent set to the index of the original term.
111128*/
111129static void exprAnalyze(
111130  SrcList *pSrc,            /* the FROM clause */
111131  WhereClause *pWC,         /* the WHERE clause */
111132  int idxTerm               /* Index of the term to be analyzed */
111133){
111134  WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
111135  WhereTerm *pTerm;                /* The term to be analyzed */
111136  WhereMaskSet *pMaskSet;          /* Set of table index masks */
111137  Expr *pExpr;                     /* The expression to be analyzed */
111138  Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
111139  Bitmask prereqAll;               /* Prerequesites of pExpr */
111140  Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
111141  Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
111142  int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
111143  int noCase = 0;                  /* LIKE/GLOB distinguishes case */
111144  int op;                          /* Top-level operator.  pExpr->op */
111145  Parse *pParse = pWInfo->pParse;  /* Parsing context */
111146  sqlite3 *db = pParse->db;        /* Database connection */
111147
111148  if( db->mallocFailed ){
111149    return;
111150  }
111151  pTerm = &pWC->a[idxTerm];
111152  pMaskSet = &pWInfo->sMaskSet;
111153  pExpr = pTerm->pExpr;
111154  assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
111155  prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
111156  op = pExpr->op;
111157  if( op==TK_IN ){
111158    assert( pExpr->pRight==0 );
111159    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
111160      pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
111161    }else{
111162      pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
111163    }
111164  }else if( op==TK_ISNULL ){
111165    pTerm->prereqRight = 0;
111166  }else{
111167    pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
111168  }
111169  prereqAll = exprTableUsage(pMaskSet, pExpr);
111170  if( ExprHasProperty(pExpr, EP_FromJoin) ){
111171    Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
111172    prereqAll |= x;
111173    extraRight = x-1;  /* ON clause terms may not be used with an index
111174                       ** on left table of a LEFT JOIN.  Ticket #3015 */
111175  }
111176  pTerm->prereqAll = prereqAll;
111177  pTerm->leftCursor = -1;
111178  pTerm->iParent = -1;
111179  pTerm->eOperator = 0;
111180  if( allowedOp(op) ){
111181    Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
111182    Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
111183    u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
111184    if( pLeft->op==TK_COLUMN ){
111185      pTerm->leftCursor = pLeft->iTable;
111186      pTerm->u.leftColumn = pLeft->iColumn;
111187      pTerm->eOperator = operatorMask(op) & opMask;
111188    }
111189    if( pRight && pRight->op==TK_COLUMN ){
111190      WhereTerm *pNew;
111191      Expr *pDup;
111192      u16 eExtraOp = 0;        /* Extra bits for pNew->eOperator */
111193      if( pTerm->leftCursor>=0 ){
111194        int idxNew;
111195        pDup = sqlite3ExprDup(db, pExpr, 0);
111196        if( db->mallocFailed ){
111197          sqlite3ExprDelete(db, pDup);
111198          return;
111199        }
111200        idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
111201        if( idxNew==0 ) return;
111202        pNew = &pWC->a[idxNew];
111203        pNew->iParent = idxTerm;
111204        pTerm = &pWC->a[idxTerm];
111205        pTerm->nChild = 1;
111206        pTerm->wtFlags |= TERM_COPIED;
111207        if( pExpr->op==TK_EQ
111208         && !ExprHasProperty(pExpr, EP_FromJoin)
111209         && OptimizationEnabled(db, SQLITE_Transitive)
111210        ){
111211          pTerm->eOperator |= WO_EQUIV;
111212          eExtraOp = WO_EQUIV;
111213        }
111214      }else{
111215        pDup = pExpr;
111216        pNew = pTerm;
111217      }
111218      exprCommute(pParse, pDup);
111219      pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
111220      pNew->leftCursor = pLeft->iTable;
111221      pNew->u.leftColumn = pLeft->iColumn;
111222      testcase( (prereqLeft | extraRight) != prereqLeft );
111223      pNew->prereqRight = prereqLeft | extraRight;
111224      pNew->prereqAll = prereqAll;
111225      pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
111226    }
111227  }
111228
111229#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
111230  /* If a term is the BETWEEN operator, create two new virtual terms
111231  ** that define the range that the BETWEEN implements.  For example:
111232  **
111233  **      a BETWEEN b AND c
111234  **
111235  ** is converted into:
111236  **
111237  **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
111238  **
111239  ** The two new terms are added onto the end of the WhereClause object.
111240  ** The new terms are "dynamic" and are children of the original BETWEEN
111241  ** term.  That means that if the BETWEEN term is coded, the children are
111242  ** skipped.  Or, if the children are satisfied by an index, the original
111243  ** BETWEEN term is skipped.
111244  */
111245  else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
111246    ExprList *pList = pExpr->x.pList;
111247    int i;
111248    static const u8 ops[] = {TK_GE, TK_LE};
111249    assert( pList!=0 );
111250    assert( pList->nExpr==2 );
111251    for(i=0; i<2; i++){
111252      Expr *pNewExpr;
111253      int idxNew;
111254      pNewExpr = sqlite3PExpr(pParse, ops[i],
111255                             sqlite3ExprDup(db, pExpr->pLeft, 0),
111256                             sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
111257      transferJoinMarkings(pNewExpr, pExpr);
111258      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
111259      testcase( idxNew==0 );
111260      exprAnalyze(pSrc, pWC, idxNew);
111261      pTerm = &pWC->a[idxTerm];
111262      pWC->a[idxNew].iParent = idxTerm;
111263    }
111264    pTerm->nChild = 2;
111265  }
111266#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
111267
111268#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
111269  /* Analyze a term that is composed of two or more subterms connected by
111270  ** an OR operator.
111271  */
111272  else if( pExpr->op==TK_OR ){
111273    assert( pWC->op==TK_AND );
111274    exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
111275    pTerm = &pWC->a[idxTerm];
111276  }
111277#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
111278
111279#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
111280  /* Add constraints to reduce the search space on a LIKE or GLOB
111281  ** operator.
111282  **
111283  ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
111284  **
111285  **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
111286  **
111287  ** The last character of the prefix "abc" is incremented to form the
111288  ** termination condition "abd".
111289  */
111290  if( pWC->op==TK_AND
111291   && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
111292  ){
111293    Expr *pLeft;       /* LHS of LIKE/GLOB operator */
111294    Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
111295    Expr *pNewExpr1;
111296    Expr *pNewExpr2;
111297    int idxNew1;
111298    int idxNew2;
111299    Token sCollSeqName;  /* Name of collating sequence */
111300
111301    pLeft = pExpr->x.pList->a[1].pExpr;
111302    pStr2 = sqlite3ExprDup(db, pStr1, 0);
111303    if( !db->mallocFailed ){
111304      u8 c, *pC;       /* Last character before the first wildcard */
111305      pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
111306      c = *pC;
111307      if( noCase ){
111308        /* The point is to increment the last character before the first
111309        ** wildcard.  But if we increment '@', that will push it into the
111310        ** alphabetic range where case conversions will mess up the
111311        ** inequality.  To avoid this, make sure to also run the full
111312        ** LIKE on all candidate expressions by clearing the isComplete flag
111313        */
111314        if( c=='A'-1 ) isComplete = 0;
111315        c = sqlite3UpperToLower[c];
111316      }
111317      *pC = c + 1;
111318    }
111319    sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
111320    sCollSeqName.n = 6;
111321    pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
111322    pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
111323           sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
111324           pStr1, 0);
111325    transferJoinMarkings(pNewExpr1, pExpr);
111326    idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
111327    testcase( idxNew1==0 );
111328    exprAnalyze(pSrc, pWC, idxNew1);
111329    pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
111330    pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
111331           sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
111332           pStr2, 0);
111333    transferJoinMarkings(pNewExpr2, pExpr);
111334    idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
111335    testcase( idxNew2==0 );
111336    exprAnalyze(pSrc, pWC, idxNew2);
111337    pTerm = &pWC->a[idxTerm];
111338    if( isComplete ){
111339      pWC->a[idxNew1].iParent = idxTerm;
111340      pWC->a[idxNew2].iParent = idxTerm;
111341      pTerm->nChild = 2;
111342    }
111343  }
111344#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
111345
111346#ifndef SQLITE_OMIT_VIRTUALTABLE
111347  /* Add a WO_MATCH auxiliary term to the constraint set if the
111348  ** current expression is of the form:  column MATCH expr.
111349  ** This information is used by the xBestIndex methods of
111350  ** virtual tables.  The native query optimizer does not attempt
111351  ** to do anything with MATCH functions.
111352  */
111353  if( isMatchOfColumn(pExpr) ){
111354    int idxNew;
111355    Expr *pRight, *pLeft;
111356    WhereTerm *pNewTerm;
111357    Bitmask prereqColumn, prereqExpr;
111358
111359    pRight = pExpr->x.pList->a[0].pExpr;
111360    pLeft = pExpr->x.pList->a[1].pExpr;
111361    prereqExpr = exprTableUsage(pMaskSet, pRight);
111362    prereqColumn = exprTableUsage(pMaskSet, pLeft);
111363    if( (prereqExpr & prereqColumn)==0 ){
111364      Expr *pNewExpr;
111365      pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
111366                              0, sqlite3ExprDup(db, pRight, 0), 0);
111367      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
111368      testcase( idxNew==0 );
111369      pNewTerm = &pWC->a[idxNew];
111370      pNewTerm->prereqRight = prereqExpr;
111371      pNewTerm->leftCursor = pLeft->iTable;
111372      pNewTerm->u.leftColumn = pLeft->iColumn;
111373      pNewTerm->eOperator = WO_MATCH;
111374      pNewTerm->iParent = idxTerm;
111375      pTerm = &pWC->a[idxTerm];
111376      pTerm->nChild = 1;
111377      pTerm->wtFlags |= TERM_COPIED;
111378      pNewTerm->prereqAll = pTerm->prereqAll;
111379    }
111380  }
111381#endif /* SQLITE_OMIT_VIRTUALTABLE */
111382
111383#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
111384  /* When sqlite_stat3 histogram data is available an operator of the
111385  ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
111386  ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
111387  ** virtual term of that form.
111388  **
111389  ** Note that the virtual term must be tagged with TERM_VNULL.  This
111390  ** TERM_VNULL tag will suppress the not-null check at the beginning
111391  ** of the loop.  Without the TERM_VNULL flag, the not-null check at
111392  ** the start of the loop will prevent any results from being returned.
111393  */
111394  if( pExpr->op==TK_NOTNULL
111395   && pExpr->pLeft->op==TK_COLUMN
111396   && pExpr->pLeft->iColumn>=0
111397   && OptimizationEnabled(db, SQLITE_Stat3)
111398  ){
111399    Expr *pNewExpr;
111400    Expr *pLeft = pExpr->pLeft;
111401    int idxNew;
111402    WhereTerm *pNewTerm;
111403
111404    pNewExpr = sqlite3PExpr(pParse, TK_GT,
111405                            sqlite3ExprDup(db, pLeft, 0),
111406                            sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
111407
111408    idxNew = whereClauseInsert(pWC, pNewExpr,
111409                              TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
111410    if( idxNew ){
111411      pNewTerm = &pWC->a[idxNew];
111412      pNewTerm->prereqRight = 0;
111413      pNewTerm->leftCursor = pLeft->iTable;
111414      pNewTerm->u.leftColumn = pLeft->iColumn;
111415      pNewTerm->eOperator = WO_GT;
111416      pNewTerm->iParent = idxTerm;
111417      pTerm = &pWC->a[idxTerm];
111418      pTerm->nChild = 1;
111419      pTerm->wtFlags |= TERM_COPIED;
111420      pNewTerm->prereqAll = pTerm->prereqAll;
111421    }
111422  }
111423#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
111424
111425  /* Prevent ON clause terms of a LEFT JOIN from being used to drive
111426  ** an index for tables to the left of the join.
111427  */
111428  pTerm->prereqRight |= extraRight;
111429}
111430
111431/*
111432** This function searches pList for a entry that matches the iCol-th column
111433** of index pIdx.
111434**
111435** If such an expression is found, its index in pList->a[] is returned. If
111436** no expression is found, -1 is returned.
111437*/
111438static int findIndexCol(
111439  Parse *pParse,                  /* Parse context */
111440  ExprList *pList,                /* Expression list to search */
111441  int iBase,                      /* Cursor for table associated with pIdx */
111442  Index *pIdx,                    /* Index to match column of */
111443  int iCol                        /* Column of index to match */
111444){
111445  int i;
111446  const char *zColl = pIdx->azColl[iCol];
111447
111448  for(i=0; i<pList->nExpr; i++){
111449    Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
111450    if( p->op==TK_COLUMN
111451     && p->iColumn==pIdx->aiColumn[iCol]
111452     && p->iTable==iBase
111453    ){
111454      CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
111455      if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
111456        return i;
111457      }
111458    }
111459  }
111460
111461  return -1;
111462}
111463
111464/*
111465** Return true if the DISTINCT expression-list passed as the third argument
111466** is redundant.
111467**
111468** A DISTINCT list is redundant if the database contains some subset of
111469** columns that are unique and non-null.
111470*/
111471static int isDistinctRedundant(
111472  Parse *pParse,            /* Parsing context */
111473  SrcList *pTabList,        /* The FROM clause */
111474  WhereClause *pWC,         /* The WHERE clause */
111475  ExprList *pDistinct       /* The result set that needs to be DISTINCT */
111476){
111477  Table *pTab;
111478  Index *pIdx;
111479  int i;
111480  int iBase;
111481
111482  /* If there is more than one table or sub-select in the FROM clause of
111483  ** this query, then it will not be possible to show that the DISTINCT
111484  ** clause is redundant. */
111485  if( pTabList->nSrc!=1 ) return 0;
111486  iBase = pTabList->a[0].iCursor;
111487  pTab = pTabList->a[0].pTab;
111488
111489  /* If any of the expressions is an IPK column on table iBase, then return
111490  ** true. Note: The (p->iTable==iBase) part of this test may be false if the
111491  ** current SELECT is a correlated sub-query.
111492  */
111493  for(i=0; i<pDistinct->nExpr; i++){
111494    Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
111495    if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
111496  }
111497
111498  /* Loop through all indices on the table, checking each to see if it makes
111499  ** the DISTINCT qualifier redundant. It does so if:
111500  **
111501  **   1. The index is itself UNIQUE, and
111502  **
111503  **   2. All of the columns in the index are either part of the pDistinct
111504  **      list, or else the WHERE clause contains a term of the form "col=X",
111505  **      where X is a constant value. The collation sequences of the
111506  **      comparison and select-list expressions must match those of the index.
111507  **
111508  **   3. All of those index columns for which the WHERE clause does not
111509  **      contain a "col=X" term are subject to a NOT NULL constraint.
111510  */
111511  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
111512    if( pIdx->onError==OE_None ) continue;
111513    for(i=0; i<pIdx->nKeyCol; i++){
111514      i16 iCol = pIdx->aiColumn[i];
111515      if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
111516        int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
111517        if( iIdxCol<0 || pTab->aCol[iCol].notNull==0 ){
111518          break;
111519        }
111520      }
111521    }
111522    if( i==pIdx->nKeyCol ){
111523      /* This index implies that the DISTINCT qualifier is redundant. */
111524      return 1;
111525    }
111526  }
111527
111528  return 0;
111529}
111530
111531
111532/*
111533** Estimate the logarithm of the input value to base 2.
111534*/
111535static LogEst estLog(LogEst N){
111536  LogEst x = sqlite3LogEst(N);
111537  return x>33 ? x - 33 : 0;
111538}
111539
111540/*
111541** Two routines for printing the content of an sqlite3_index_info
111542** structure.  Used for testing and debugging only.  If neither
111543** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
111544** are no-ops.
111545*/
111546#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
111547static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
111548  int i;
111549  if( !sqlite3WhereTrace ) return;
111550  for(i=0; i<p->nConstraint; i++){
111551    sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
111552       i,
111553       p->aConstraint[i].iColumn,
111554       p->aConstraint[i].iTermOffset,
111555       p->aConstraint[i].op,
111556       p->aConstraint[i].usable);
111557  }
111558  for(i=0; i<p->nOrderBy; i++){
111559    sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
111560       i,
111561       p->aOrderBy[i].iColumn,
111562       p->aOrderBy[i].desc);
111563  }
111564}
111565static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
111566  int i;
111567  if( !sqlite3WhereTrace ) return;
111568  for(i=0; i<p->nConstraint; i++){
111569    sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
111570       i,
111571       p->aConstraintUsage[i].argvIndex,
111572       p->aConstraintUsage[i].omit);
111573  }
111574  sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
111575  sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
111576  sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
111577  sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
111578  sqlite3DebugPrintf("  estimatedRows=%lld\n", p->estimatedRows);
111579}
111580#else
111581#define TRACE_IDX_INPUTS(A)
111582#define TRACE_IDX_OUTPUTS(A)
111583#endif
111584
111585#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
111586/*
111587** Return TRUE if the WHERE clause term pTerm is of a form where it
111588** could be used with an index to access pSrc, assuming an appropriate
111589** index existed.
111590*/
111591static int termCanDriveIndex(
111592  WhereTerm *pTerm,              /* WHERE clause term to check */
111593  struct SrcList_item *pSrc,     /* Table we are trying to access */
111594  Bitmask notReady               /* Tables in outer loops of the join */
111595){
111596  char aff;
111597  if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
111598  if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
111599  if( (pTerm->prereqRight & notReady)!=0 ) return 0;
111600  if( pTerm->u.leftColumn<0 ) return 0;
111601  aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
111602  if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
111603  return 1;
111604}
111605#endif
111606
111607
111608#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
111609/*
111610** Generate code to construct the Index object for an automatic index
111611** and to set up the WhereLevel object pLevel so that the code generator
111612** makes use of the automatic index.
111613*/
111614static void constructAutomaticIndex(
111615  Parse *pParse,              /* The parsing context */
111616  WhereClause *pWC,           /* The WHERE clause */
111617  struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
111618  Bitmask notReady,           /* Mask of cursors that are not available */
111619  WhereLevel *pLevel          /* Write new index here */
111620){
111621  int nKeyCol;                /* Number of columns in the constructed index */
111622  WhereTerm *pTerm;           /* A single term of the WHERE clause */
111623  WhereTerm *pWCEnd;          /* End of pWC->a[] */
111624  Index *pIdx;                /* Object describing the transient index */
111625  Vdbe *v;                    /* Prepared statement under construction */
111626  int addrInit;               /* Address of the initialization bypass jump */
111627  Table *pTable;              /* The table being indexed */
111628  int addrTop;                /* Top of the index fill loop */
111629  int regRecord;              /* Register holding an index record */
111630  int n;                      /* Column counter */
111631  int i;                      /* Loop counter */
111632  int mxBitCol;               /* Maximum column in pSrc->colUsed */
111633  CollSeq *pColl;             /* Collating sequence to on a column */
111634  WhereLoop *pLoop;           /* The Loop object */
111635  char *zNotUsed;             /* Extra space on the end of pIdx */
111636  Bitmask idxCols;            /* Bitmap of columns used for indexing */
111637  Bitmask extraCols;          /* Bitmap of additional columns */
111638  u8 sentWarning = 0;         /* True if a warnning has been issued */
111639
111640  /* Generate code to skip over the creation and initialization of the
111641  ** transient index on 2nd and subsequent iterations of the loop. */
111642  v = pParse->pVdbe;
111643  assert( v!=0 );
111644  addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v);
111645
111646  /* Count the number of columns that will be added to the index
111647  ** and used to match WHERE clause constraints */
111648  nKeyCol = 0;
111649  pTable = pSrc->pTab;
111650  pWCEnd = &pWC->a[pWC->nTerm];
111651  pLoop = pLevel->pWLoop;
111652  idxCols = 0;
111653  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
111654    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
111655      int iCol = pTerm->u.leftColumn;
111656      Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
111657      testcase( iCol==BMS );
111658      testcase( iCol==BMS-1 );
111659      if( !sentWarning ){
111660        sqlite3_log(SQLITE_WARNING_AUTOINDEX,
111661            "automatic index on %s(%s)", pTable->zName,
111662            pTable->aCol[iCol].zName);
111663        sentWarning = 1;
111664      }
111665      if( (idxCols & cMask)==0 ){
111666        if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ) return;
111667        pLoop->aLTerm[nKeyCol++] = pTerm;
111668        idxCols |= cMask;
111669      }
111670    }
111671  }
111672  assert( nKeyCol>0 );
111673  pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
111674  pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
111675                     | WHERE_AUTO_INDEX;
111676
111677  /* Count the number of additional columns needed to create a
111678  ** covering index.  A "covering index" is an index that contains all
111679  ** columns that are needed by the query.  With a covering index, the
111680  ** original table never needs to be accessed.  Automatic indices must
111681  ** be a covering index because the index will not be updated if the
111682  ** original table changes and the index and table cannot both be used
111683  ** if they go out of sync.
111684  */
111685  extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
111686  mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
111687  testcase( pTable->nCol==BMS-1 );
111688  testcase( pTable->nCol==BMS-2 );
111689  for(i=0; i<mxBitCol; i++){
111690    if( extraCols & MASKBIT(i) ) nKeyCol++;
111691  }
111692  if( pSrc->colUsed & MASKBIT(BMS-1) ){
111693    nKeyCol += pTable->nCol - BMS + 1;
111694  }
111695  pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY;
111696
111697  /* Construct the Index object to describe this index */
111698  pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
111699  if( pIdx==0 ) return;
111700  pLoop->u.btree.pIndex = pIdx;
111701  pIdx->zName = "auto-index";
111702  pIdx->pTable = pTable;
111703  n = 0;
111704  idxCols = 0;
111705  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
111706    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
111707      int iCol = pTerm->u.leftColumn;
111708      Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
111709      testcase( iCol==BMS-1 );
111710      testcase( iCol==BMS );
111711      if( (idxCols & cMask)==0 ){
111712        Expr *pX = pTerm->pExpr;
111713        idxCols |= cMask;
111714        pIdx->aiColumn[n] = pTerm->u.leftColumn;
111715        pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
111716        pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
111717        n++;
111718      }
111719    }
111720  }
111721  assert( (u32)n==pLoop->u.btree.nEq );
111722
111723  /* Add additional columns needed to make the automatic index into
111724  ** a covering index */
111725  for(i=0; i<mxBitCol; i++){
111726    if( extraCols & MASKBIT(i) ){
111727      pIdx->aiColumn[n] = i;
111728      pIdx->azColl[n] = "BINARY";
111729      n++;
111730    }
111731  }
111732  if( pSrc->colUsed & MASKBIT(BMS-1) ){
111733    for(i=BMS-1; i<pTable->nCol; i++){
111734      pIdx->aiColumn[n] = i;
111735      pIdx->azColl[n] = "BINARY";
111736      n++;
111737    }
111738  }
111739  assert( n==nKeyCol );
111740  pIdx->aiColumn[n] = -1;
111741  pIdx->azColl[n] = "BINARY";
111742
111743  /* Create the automatic index */
111744  assert( pLevel->iIdxCur>=0 );
111745  pLevel->iIdxCur = pParse->nTab++;
111746  sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
111747  sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
111748  VdbeComment((v, "for %s", pTable->zName));
111749
111750  /* Fill the automatic index with content */
111751  addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
111752  regRecord = sqlite3GetTempReg(pParse);
111753  sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0);
111754  sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
111755  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
111756  sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
111757  sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
111758  sqlite3VdbeJumpHere(v, addrTop);
111759  sqlite3ReleaseTempReg(pParse, regRecord);
111760
111761  /* Jump here when skipping the initialization */
111762  sqlite3VdbeJumpHere(v, addrInit);
111763}
111764#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
111765
111766#ifndef SQLITE_OMIT_VIRTUALTABLE
111767/*
111768** Allocate and populate an sqlite3_index_info structure. It is the
111769** responsibility of the caller to eventually release the structure
111770** by passing the pointer returned by this function to sqlite3_free().
111771*/
111772static sqlite3_index_info *allocateIndexInfo(
111773  Parse *pParse,
111774  WhereClause *pWC,
111775  struct SrcList_item *pSrc,
111776  ExprList *pOrderBy
111777){
111778  int i, j;
111779  int nTerm;
111780  struct sqlite3_index_constraint *pIdxCons;
111781  struct sqlite3_index_orderby *pIdxOrderBy;
111782  struct sqlite3_index_constraint_usage *pUsage;
111783  WhereTerm *pTerm;
111784  int nOrderBy;
111785  sqlite3_index_info *pIdxInfo;
111786
111787  /* Count the number of possible WHERE clause constraints referring
111788  ** to this virtual table */
111789  for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
111790    if( pTerm->leftCursor != pSrc->iCursor ) continue;
111791    assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
111792    testcase( pTerm->eOperator & WO_IN );
111793    testcase( pTerm->eOperator & WO_ISNULL );
111794    testcase( pTerm->eOperator & WO_ALL );
111795    if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
111796    if( pTerm->wtFlags & TERM_VNULL ) continue;
111797    nTerm++;
111798  }
111799
111800  /* If the ORDER BY clause contains only columns in the current
111801  ** virtual table then allocate space for the aOrderBy part of
111802  ** the sqlite3_index_info structure.
111803  */
111804  nOrderBy = 0;
111805  if( pOrderBy ){
111806    int n = pOrderBy->nExpr;
111807    for(i=0; i<n; i++){
111808      Expr *pExpr = pOrderBy->a[i].pExpr;
111809      if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
111810    }
111811    if( i==n){
111812      nOrderBy = n;
111813    }
111814  }
111815
111816  /* Allocate the sqlite3_index_info structure
111817  */
111818  pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
111819                           + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
111820                           + sizeof(*pIdxOrderBy)*nOrderBy );
111821  if( pIdxInfo==0 ){
111822    sqlite3ErrorMsg(pParse, "out of memory");
111823    return 0;
111824  }
111825
111826  /* Initialize the structure.  The sqlite3_index_info structure contains
111827  ** many fields that are declared "const" to prevent xBestIndex from
111828  ** changing them.  We have to do some funky casting in order to
111829  ** initialize those fields.
111830  */
111831  pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
111832  pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
111833  pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
111834  *(int*)&pIdxInfo->nConstraint = nTerm;
111835  *(int*)&pIdxInfo->nOrderBy = nOrderBy;
111836  *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
111837  *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
111838  *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
111839                                                                   pUsage;
111840
111841  for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
111842    u8 op;
111843    if( pTerm->leftCursor != pSrc->iCursor ) continue;
111844    assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
111845    testcase( pTerm->eOperator & WO_IN );
111846    testcase( pTerm->eOperator & WO_ISNULL );
111847    testcase( pTerm->eOperator & WO_ALL );
111848    if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
111849    if( pTerm->wtFlags & TERM_VNULL ) continue;
111850    pIdxCons[j].iColumn = pTerm->u.leftColumn;
111851    pIdxCons[j].iTermOffset = i;
111852    op = (u8)pTerm->eOperator & WO_ALL;
111853    if( op==WO_IN ) op = WO_EQ;
111854    pIdxCons[j].op = op;
111855    /* The direct assignment in the previous line is possible only because
111856    ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
111857    ** following asserts verify this fact. */
111858    assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
111859    assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
111860    assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
111861    assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
111862    assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
111863    assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
111864    assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
111865    j++;
111866  }
111867  for(i=0; i<nOrderBy; i++){
111868    Expr *pExpr = pOrderBy->a[i].pExpr;
111869    pIdxOrderBy[i].iColumn = pExpr->iColumn;
111870    pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
111871  }
111872
111873  return pIdxInfo;
111874}
111875
111876/*
111877** The table object reference passed as the second argument to this function
111878** must represent a virtual table. This function invokes the xBestIndex()
111879** method of the virtual table with the sqlite3_index_info object that
111880** comes in as the 3rd argument to this function.
111881**
111882** If an error occurs, pParse is populated with an error message and a
111883** non-zero value is returned. Otherwise, 0 is returned and the output
111884** part of the sqlite3_index_info structure is left populated.
111885**
111886** Whether or not an error is returned, it is the responsibility of the
111887** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
111888** that this is required.
111889*/
111890static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
111891  sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
111892  int i;
111893  int rc;
111894
111895  TRACE_IDX_INPUTS(p);
111896  rc = pVtab->pModule->xBestIndex(pVtab, p);
111897  TRACE_IDX_OUTPUTS(p);
111898
111899  if( rc!=SQLITE_OK ){
111900    if( rc==SQLITE_NOMEM ){
111901      pParse->db->mallocFailed = 1;
111902    }else if( !pVtab->zErrMsg ){
111903      sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
111904    }else{
111905      sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
111906    }
111907  }
111908  sqlite3_free(pVtab->zErrMsg);
111909  pVtab->zErrMsg = 0;
111910
111911  for(i=0; i<p->nConstraint; i++){
111912    if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
111913      sqlite3ErrorMsg(pParse,
111914          "table %s: xBestIndex returned an invalid plan", pTab->zName);
111915    }
111916  }
111917
111918  return pParse->nErr;
111919}
111920#endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
111921
111922
111923#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
111924/*
111925** Estimate the location of a particular key among all keys in an
111926** index.  Store the results in aStat as follows:
111927**
111928**    aStat[0]      Est. number of rows less than pVal
111929**    aStat[1]      Est. number of rows equal to pVal
111930**
111931** Return SQLITE_OK on success.
111932*/
111933static void whereKeyStats(
111934  Parse *pParse,              /* Database connection */
111935  Index *pIdx,                /* Index to consider domain of */
111936  UnpackedRecord *pRec,       /* Vector of values to consider */
111937  int roundUp,                /* Round up if true.  Round down if false */
111938  tRowcnt *aStat              /* OUT: stats written here */
111939){
111940  IndexSample *aSample = pIdx->aSample;
111941  int iCol;                   /* Index of required stats in anEq[] etc. */
111942  int iMin = 0;               /* Smallest sample not yet tested */
111943  int i = pIdx->nSample;      /* Smallest sample larger than or equal to pRec */
111944  int iTest;                  /* Next sample to test */
111945  int res;                    /* Result of comparison operation */
111946
111947#ifndef SQLITE_DEBUG
111948  UNUSED_PARAMETER( pParse );
111949#endif
111950  assert( pRec!=0 );
111951  iCol = pRec->nField - 1;
111952  assert( pIdx->nSample>0 );
111953  assert( pRec->nField>0 && iCol<pIdx->nSampleCol );
111954  do{
111955    iTest = (iMin+i)/2;
111956    res = sqlite3VdbeRecordCompare(aSample[iTest].n, aSample[iTest].p, pRec, 0);
111957    if( res<0 ){
111958      iMin = iTest+1;
111959    }else{
111960      i = iTest;
111961    }
111962  }while( res && iMin<i );
111963
111964#ifdef SQLITE_DEBUG
111965  /* The following assert statements check that the binary search code
111966  ** above found the right answer. This block serves no purpose other
111967  ** than to invoke the asserts.  */
111968  if( res==0 ){
111969    /* If (res==0) is true, then sample $i must be equal to pRec */
111970    assert( i<pIdx->nSample );
111971    assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec, 0)
111972         || pParse->db->mallocFailed );
111973  }else{
111974    /* Otherwise, pRec must be smaller than sample $i and larger than
111975    ** sample ($i-1).  */
111976    assert( i==pIdx->nSample
111977         || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec, 0)>0
111978         || pParse->db->mallocFailed );
111979    assert( i==0
111980         || sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec, 0)<0
111981         || pParse->db->mallocFailed );
111982  }
111983#endif /* ifdef SQLITE_DEBUG */
111984
111985  /* At this point, aSample[i] is the first sample that is greater than
111986  ** or equal to pVal.  Or if i==pIdx->nSample, then all samples are less
111987  ** than pVal.  If aSample[i]==pVal, then res==0.
111988  */
111989  if( res==0 ){
111990    aStat[0] = aSample[i].anLt[iCol];
111991    aStat[1] = aSample[i].anEq[iCol];
111992  }else{
111993    tRowcnt iLower, iUpper, iGap;
111994    if( i==0 ){
111995      iLower = 0;
111996      iUpper = aSample[0].anLt[iCol];
111997    }else{
111998      i64 nRow0 = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
111999      iUpper = i>=pIdx->nSample ? nRow0 : aSample[i].anLt[iCol];
112000      iLower = aSample[i-1].anEq[iCol] + aSample[i-1].anLt[iCol];
112001    }
112002    aStat[1] = (pIdx->nKeyCol>iCol ? pIdx->aAvgEq[iCol] : 1);
112003    if( iLower>=iUpper ){
112004      iGap = 0;
112005    }else{
112006      iGap = iUpper - iLower;
112007    }
112008    if( roundUp ){
112009      iGap = (iGap*2)/3;
112010    }else{
112011      iGap = iGap/3;
112012    }
112013    aStat[0] = iLower + iGap;
112014  }
112015}
112016#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
112017
112018/*
112019** If it is not NULL, pTerm is a term that provides an upper or lower
112020** bound on a range scan. Without considering pTerm, it is estimated
112021** that the scan will visit nNew rows. This function returns the number
112022** estimated to be visited after taking pTerm into account.
112023**
112024** If the user explicitly specified a likelihood() value for this term,
112025** then the return value is the likelihood multiplied by the number of
112026** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
112027** has a likelihood of 0.50, and any other term a likelihood of 0.25.
112028*/
112029static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
112030  LogEst nRet = nNew;
112031  if( pTerm ){
112032    if( pTerm->truthProb<=0 ){
112033      nRet += pTerm->truthProb;
112034    }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
112035      nRet -= 20;        assert( 20==sqlite3LogEst(4) );
112036    }
112037  }
112038  return nRet;
112039}
112040
112041/*
112042** This function is used to estimate the number of rows that will be visited
112043** by scanning an index for a range of values. The range may have an upper
112044** bound, a lower bound, or both. The WHERE clause terms that set the upper
112045** and lower bounds are represented by pLower and pUpper respectively. For
112046** example, assuming that index p is on t1(a):
112047**
112048**   ... FROM t1 WHERE a > ? AND a < ? ...
112049**                    |_____|   |_____|
112050**                       |         |
112051**                     pLower    pUpper
112052**
112053** If either of the upper or lower bound is not present, then NULL is passed in
112054** place of the corresponding WhereTerm.
112055**
112056** The value in (pBuilder->pNew->u.btree.nEq) is the index of the index
112057** column subject to the range constraint. Or, equivalently, the number of
112058** equality constraints optimized by the proposed index scan. For example,
112059** assuming index p is on t1(a, b), and the SQL query is:
112060**
112061**   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
112062**
112063** then nEq is set to 1 (as the range restricted column, b, is the second
112064** left-most column of the index). Or, if the query is:
112065**
112066**   ... FROM t1 WHERE a > ? AND a < ? ...
112067**
112068** then nEq is set to 0.
112069**
112070** When this function is called, *pnOut is set to the sqlite3LogEst() of the
112071** number of rows that the index scan is expected to visit without
112072** considering the range constraints. If nEq is 0, this is the number of
112073** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
112074** to account for the range contraints pLower and pUpper.
112075**
112076** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
112077** used, each range inequality reduces the search space by a factor of 4.
112078** Hence a pair of constraints (x>? AND x<?) reduces the expected number of
112079** rows visited by a factor of 16.
112080*/
112081static int whereRangeScanEst(
112082  Parse *pParse,       /* Parsing & code generating context */
112083  WhereLoopBuilder *pBuilder,
112084  WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
112085  WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
112086  WhereLoop *pLoop     /* Modify the .nOut and maybe .rRun fields */
112087){
112088  int rc = SQLITE_OK;
112089  int nOut = pLoop->nOut;
112090  LogEst nNew;
112091
112092#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
112093  Index *p = pLoop->u.btree.pIndex;
112094  int nEq = pLoop->u.btree.nEq;
112095
112096  if( p->nSample>0
112097   && nEq==pBuilder->nRecValid
112098   && nEq<p->nSampleCol
112099   && OptimizationEnabled(pParse->db, SQLITE_Stat3)
112100  ){
112101    UnpackedRecord *pRec = pBuilder->pRec;
112102    tRowcnt a[2];
112103    u8 aff;
112104
112105    /* Variable iLower will be set to the estimate of the number of rows in
112106    ** the index that are less than the lower bound of the range query. The
112107    ** lower bound being the concatenation of $P and $L, where $P is the
112108    ** key-prefix formed by the nEq values matched against the nEq left-most
112109    ** columns of the index, and $L is the value in pLower.
112110    **
112111    ** Or, if pLower is NULL or $L cannot be extracted from it (because it
112112    ** is not a simple variable or literal value), the lower bound of the
112113    ** range is $P. Due to a quirk in the way whereKeyStats() works, even
112114    ** if $L is available, whereKeyStats() is called for both ($P) and
112115    ** ($P:$L) and the larger of the two returned values used.
112116    **
112117    ** Similarly, iUpper is to be set to the estimate of the number of rows
112118    ** less than the upper bound of the range query. Where the upper bound
112119    ** is either ($P) or ($P:$U). Again, even if $U is available, both values
112120    ** of iUpper are requested of whereKeyStats() and the smaller used.
112121    */
112122    tRowcnt iLower;
112123    tRowcnt iUpper;
112124
112125    if( nEq==p->nKeyCol ){
112126      aff = SQLITE_AFF_INTEGER;
112127    }else{
112128      aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
112129    }
112130    /* Determine iLower and iUpper using ($P) only. */
112131    if( nEq==0 ){
112132      iLower = 0;
112133      iUpper = sqlite3LogEstToInt(p->aiRowLogEst[0]);
112134    }else{
112135      /* Note: this call could be optimized away - since the same values must
112136      ** have been requested when testing key $P in whereEqualScanEst().  */
112137      whereKeyStats(pParse, p, pRec, 0, a);
112138      iLower = a[0];
112139      iUpper = a[0] + a[1];
112140    }
112141
112142    /* If possible, improve on the iLower estimate using ($P:$L). */
112143    if( pLower ){
112144      int bOk;                    /* True if value is extracted from pExpr */
112145      Expr *pExpr = pLower->pExpr->pRight;
112146      assert( (pLower->eOperator & (WO_GT|WO_GE))!=0 );
112147      rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
112148      if( rc==SQLITE_OK && bOk ){
112149        tRowcnt iNew;
112150        whereKeyStats(pParse, p, pRec, 0, a);
112151        iNew = a[0] + ((pLower->eOperator & WO_GT) ? a[1] : 0);
112152        if( iNew>iLower ) iLower = iNew;
112153        nOut--;
112154      }
112155    }
112156
112157    /* If possible, improve on the iUpper estimate using ($P:$U). */
112158    if( pUpper ){
112159      int bOk;                    /* True if value is extracted from pExpr */
112160      Expr *pExpr = pUpper->pExpr->pRight;
112161      assert( (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
112162      rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
112163      if( rc==SQLITE_OK && bOk ){
112164        tRowcnt iNew;
112165        whereKeyStats(pParse, p, pRec, 1, a);
112166        iNew = a[0] + ((pUpper->eOperator & WO_LE) ? a[1] : 0);
112167        if( iNew<iUpper ) iUpper = iNew;
112168        nOut--;
112169      }
112170    }
112171
112172    pBuilder->pRec = pRec;
112173    if( rc==SQLITE_OK ){
112174      if( iUpper>iLower ){
112175        nNew = sqlite3LogEst(iUpper - iLower);
112176      }else{
112177        nNew = 10;        assert( 10==sqlite3LogEst(2) );
112178      }
112179      if( nNew<nOut ){
112180        nOut = nNew;
112181      }
112182      pLoop->nOut = (LogEst)nOut;
112183      WHERETRACE(0x10, ("range scan regions: %u..%u  est=%d\n",
112184                         (u32)iLower, (u32)iUpper, nOut));
112185      return SQLITE_OK;
112186    }
112187  }
112188#else
112189  UNUSED_PARAMETER(pParse);
112190  UNUSED_PARAMETER(pBuilder);
112191#endif
112192  assert( pLower || pUpper );
112193  assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
112194  nNew = whereRangeAdjust(pLower, nOut);
112195  nNew = whereRangeAdjust(pUpper, nNew);
112196
112197  /* TUNING: If there is both an upper and lower limit, assume the range is
112198  ** reduced by an additional 75%. This means that, by default, an open-ended
112199  ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
112200  ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
112201  ** match 1/64 of the index. */
112202  if( pLower && pUpper ) nNew -= 20;
112203
112204  nOut -= (pLower!=0) + (pUpper!=0);
112205  if( nNew<10 ) nNew = 10;
112206  if( nNew<nOut ) nOut = nNew;
112207  pLoop->nOut = (LogEst)nOut;
112208  return rc;
112209}
112210
112211#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
112212/*
112213** Estimate the number of rows that will be returned based on
112214** an equality constraint x=VALUE and where that VALUE occurs in
112215** the histogram data.  This only works when x is the left-most
112216** column of an index and sqlite_stat3 histogram data is available
112217** for that index.  When pExpr==NULL that means the constraint is
112218** "x IS NULL" instead of "x=VALUE".
112219**
112220** Write the estimated row count into *pnRow and return SQLITE_OK.
112221** If unable to make an estimate, leave *pnRow unchanged and return
112222** non-zero.
112223**
112224** This routine can fail if it is unable to load a collating sequence
112225** required for string comparison, or if unable to allocate memory
112226** for a UTF conversion required for comparison.  The error is stored
112227** in the pParse structure.
112228*/
112229static int whereEqualScanEst(
112230  Parse *pParse,       /* Parsing & code generating context */
112231  WhereLoopBuilder *pBuilder,
112232  Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
112233  tRowcnt *pnRow       /* Write the revised row estimate here */
112234){
112235  Index *p = pBuilder->pNew->u.btree.pIndex;
112236  int nEq = pBuilder->pNew->u.btree.nEq;
112237  UnpackedRecord *pRec = pBuilder->pRec;
112238  u8 aff;                   /* Column affinity */
112239  int rc;                   /* Subfunction return code */
112240  tRowcnt a[2];             /* Statistics */
112241  int bOk;
112242
112243  assert( nEq>=1 );
112244  assert( nEq<=(p->nKeyCol+1) );
112245  assert( p->aSample!=0 );
112246  assert( p->nSample>0 );
112247  assert( pBuilder->nRecValid<nEq );
112248
112249  /* If values are not available for all fields of the index to the left
112250  ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
112251  if( pBuilder->nRecValid<(nEq-1) ){
112252    return SQLITE_NOTFOUND;
112253  }
112254
112255  /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
112256  ** below would return the same value.  */
112257  if( nEq>p->nKeyCol ){
112258    *pnRow = 1;
112259    return SQLITE_OK;
112260  }
112261
112262  aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
112263  rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
112264  pBuilder->pRec = pRec;
112265  if( rc!=SQLITE_OK ) return rc;
112266  if( bOk==0 ) return SQLITE_NOTFOUND;
112267  pBuilder->nRecValid = nEq;
112268
112269  whereKeyStats(pParse, p, pRec, 0, a);
112270  WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1]));
112271  *pnRow = a[1];
112272
112273  return rc;
112274}
112275#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
112276
112277#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
112278/*
112279** Estimate the number of rows that will be returned based on
112280** an IN constraint where the right-hand side of the IN operator
112281** is a list of values.  Example:
112282**
112283**        WHERE x IN (1,2,3,4)
112284**
112285** Write the estimated row count into *pnRow and return SQLITE_OK.
112286** If unable to make an estimate, leave *pnRow unchanged and return
112287** non-zero.
112288**
112289** This routine can fail if it is unable to load a collating sequence
112290** required for string comparison, or if unable to allocate memory
112291** for a UTF conversion required for comparison.  The error is stored
112292** in the pParse structure.
112293*/
112294static int whereInScanEst(
112295  Parse *pParse,       /* Parsing & code generating context */
112296  WhereLoopBuilder *pBuilder,
112297  ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
112298  tRowcnt *pnRow       /* Write the revised row estimate here */
112299){
112300  Index *p = pBuilder->pNew->u.btree.pIndex;
112301  i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
112302  int nRecValid = pBuilder->nRecValid;
112303  int rc = SQLITE_OK;     /* Subfunction return code */
112304  tRowcnt nEst;           /* Number of rows for a single term */
112305  tRowcnt nRowEst = 0;    /* New estimate of the number of rows */
112306  int i;                  /* Loop counter */
112307
112308  assert( p->aSample!=0 );
112309  for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
112310    nEst = nRow0;
112311    rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
112312    nRowEst += nEst;
112313    pBuilder->nRecValid = nRecValid;
112314  }
112315
112316  if( rc==SQLITE_OK ){
112317    if( nRowEst > nRow0 ) nRowEst = nRow0;
112318    *pnRow = nRowEst;
112319    WHERETRACE(0x10,("IN row estimate: est=%g\n", nRowEst));
112320  }
112321  assert( pBuilder->nRecValid==nRecValid );
112322  return rc;
112323}
112324#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
112325
112326/*
112327** Disable a term in the WHERE clause.  Except, do not disable the term
112328** if it controls a LEFT OUTER JOIN and it did not originate in the ON
112329** or USING clause of that join.
112330**
112331** Consider the term t2.z='ok' in the following queries:
112332**
112333**   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
112334**   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
112335**   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
112336**
112337** The t2.z='ok' is disabled in the in (2) because it originates
112338** in the ON clause.  The term is disabled in (3) because it is not part
112339** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
112340**
112341** Disabling a term causes that term to not be tested in the inner loop
112342** of the join.  Disabling is an optimization.  When terms are satisfied
112343** by indices, we disable them to prevent redundant tests in the inner
112344** loop.  We would get the correct results if nothing were ever disabled,
112345** but joins might run a little slower.  The trick is to disable as much
112346** as we can without disabling too much.  If we disabled in (1), we'd get
112347** the wrong answer.  See ticket #813.
112348*/
112349static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
112350  if( pTerm
112351      && (pTerm->wtFlags & TERM_CODED)==0
112352      && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
112353      && (pLevel->notReady & pTerm->prereqAll)==0
112354  ){
112355    pTerm->wtFlags |= TERM_CODED;
112356    if( pTerm->iParent>=0 ){
112357      WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
112358      if( (--pOther->nChild)==0 ){
112359        disableTerm(pLevel, pOther);
112360      }
112361    }
112362  }
112363}
112364
112365/*
112366** Code an OP_Affinity opcode to apply the column affinity string zAff
112367** to the n registers starting at base.
112368**
112369** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
112370** beginning and end of zAff are ignored.  If all entries in zAff are
112371** SQLITE_AFF_NONE, then no code gets generated.
112372**
112373** This routine makes its own copy of zAff so that the caller is free
112374** to modify zAff after this routine returns.
112375*/
112376static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
112377  Vdbe *v = pParse->pVdbe;
112378  if( zAff==0 ){
112379    assert( pParse->db->mallocFailed );
112380    return;
112381  }
112382  assert( v!=0 );
112383
112384  /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
112385  ** and end of the affinity string.
112386  */
112387  while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
112388    n--;
112389    base++;
112390    zAff++;
112391  }
112392  while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
112393    n--;
112394  }
112395
112396  /* Code the OP_Affinity opcode if there is anything left to do. */
112397  if( n>0 ){
112398    sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
112399    sqlite3VdbeChangeP4(v, -1, zAff, n);
112400    sqlite3ExprCacheAffinityChange(pParse, base, n);
112401  }
112402}
112403
112404
112405/*
112406** Generate code for a single equality term of the WHERE clause.  An equality
112407** term can be either X=expr or X IN (...).   pTerm is the term to be
112408** coded.
112409**
112410** The current value for the constraint is left in register iReg.
112411**
112412** For a constraint of the form X=expr, the expression is evaluated and its
112413** result is left on the stack.  For constraints of the form X IN (...)
112414** this routine sets up a loop that will iterate over all values of X.
112415*/
112416static int codeEqualityTerm(
112417  Parse *pParse,      /* The parsing context */
112418  WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
112419  WhereLevel *pLevel, /* The level of the FROM clause we are working on */
112420  int iEq,            /* Index of the equality term within this level */
112421  int bRev,           /* True for reverse-order IN operations */
112422  int iTarget         /* Attempt to leave results in this register */
112423){
112424  Expr *pX = pTerm->pExpr;
112425  Vdbe *v = pParse->pVdbe;
112426  int iReg;                  /* Register holding results */
112427
112428  assert( iTarget>0 );
112429  if( pX->op==TK_EQ ){
112430    iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
112431  }else if( pX->op==TK_ISNULL ){
112432    iReg = iTarget;
112433    sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
112434#ifndef SQLITE_OMIT_SUBQUERY
112435  }else{
112436    int eType;
112437    int iTab;
112438    struct InLoop *pIn;
112439    WhereLoop *pLoop = pLevel->pWLoop;
112440
112441    if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
112442      && pLoop->u.btree.pIndex!=0
112443      && pLoop->u.btree.pIndex->aSortOrder[iEq]
112444    ){
112445      testcase( iEq==0 );
112446      testcase( bRev );
112447      bRev = !bRev;
112448    }
112449    assert( pX->op==TK_IN );
112450    iReg = iTarget;
112451    eType = sqlite3FindInIndex(pParse, pX, 0);
112452    if( eType==IN_INDEX_INDEX_DESC ){
112453      testcase( bRev );
112454      bRev = !bRev;
112455    }
112456    iTab = pX->iTable;
112457    sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
112458    VdbeCoverageIf(v, bRev);
112459    VdbeCoverageIf(v, !bRev);
112460    assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
112461    pLoop->wsFlags |= WHERE_IN_ABLE;
112462    if( pLevel->u.in.nIn==0 ){
112463      pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
112464    }
112465    pLevel->u.in.nIn++;
112466    pLevel->u.in.aInLoop =
112467       sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
112468                              sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
112469    pIn = pLevel->u.in.aInLoop;
112470    if( pIn ){
112471      pIn += pLevel->u.in.nIn - 1;
112472      pIn->iCur = iTab;
112473      if( eType==IN_INDEX_ROWID ){
112474        pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
112475      }else{
112476        pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
112477      }
112478      pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
112479      sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
112480    }else{
112481      pLevel->u.in.nIn = 0;
112482    }
112483#endif
112484  }
112485  disableTerm(pLevel, pTerm);
112486  return iReg;
112487}
112488
112489/*
112490** Generate code that will evaluate all == and IN constraints for an
112491** index scan.
112492**
112493** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
112494** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
112495** The index has as many as three equality constraints, but in this
112496** example, the third "c" value is an inequality.  So only two
112497** constraints are coded.  This routine will generate code to evaluate
112498** a==5 and b IN (1,2,3).  The current values for a and b will be stored
112499** in consecutive registers and the index of the first register is returned.
112500**
112501** In the example above nEq==2.  But this subroutine works for any value
112502** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
112503** The only thing it does is allocate the pLevel->iMem memory cell and
112504** compute the affinity string.
112505**
112506** The nExtraReg parameter is 0 or 1.  It is 0 if all WHERE clause constraints
112507** are == or IN and are covered by the nEq.  nExtraReg is 1 if there is
112508** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
112509** occurs after the nEq quality constraints.
112510**
112511** This routine allocates a range of nEq+nExtraReg memory cells and returns
112512** the index of the first memory cell in that range. The code that
112513** calls this routine will use that memory range to store keys for
112514** start and termination conditions of the loop.
112515** key value of the loop.  If one or more IN operators appear, then
112516** this routine allocates an additional nEq memory cells for internal
112517** use.
112518**
112519** Before returning, *pzAff is set to point to a buffer containing a
112520** copy of the column affinity string of the index allocated using
112521** sqlite3DbMalloc(). Except, entries in the copy of the string associated
112522** with equality constraints that use NONE affinity are set to
112523** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
112524**
112525**   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
112526**   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
112527**
112528** In the example above, the index on t1(a) has TEXT affinity. But since
112529** the right hand side of the equality constraint (t2.b) has NONE affinity,
112530** no conversion should be attempted before using a t2.b value as part of
112531** a key to search the index. Hence the first byte in the returned affinity
112532** string in this example would be set to SQLITE_AFF_NONE.
112533*/
112534static int codeAllEqualityTerms(
112535  Parse *pParse,        /* Parsing context */
112536  WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
112537  int bRev,             /* Reverse the order of IN operators */
112538  int nExtraReg,        /* Number of extra registers to allocate */
112539  char **pzAff          /* OUT: Set to point to affinity string */
112540){
112541  u16 nEq;                      /* The number of == or IN constraints to code */
112542  u16 nSkip;                    /* Number of left-most columns to skip */
112543  Vdbe *v = pParse->pVdbe;      /* The vm under construction */
112544  Index *pIdx;                  /* The index being used for this loop */
112545  WhereTerm *pTerm;             /* A single constraint term */
112546  WhereLoop *pLoop;             /* The WhereLoop object */
112547  int j;                        /* Loop counter */
112548  int regBase;                  /* Base register */
112549  int nReg;                     /* Number of registers to allocate */
112550  char *zAff;                   /* Affinity string to return */
112551
112552  /* This module is only called on query plans that use an index. */
112553  pLoop = pLevel->pWLoop;
112554  assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
112555  nEq = pLoop->u.btree.nEq;
112556  nSkip = pLoop->u.btree.nSkip;
112557  pIdx = pLoop->u.btree.pIndex;
112558  assert( pIdx!=0 );
112559
112560  /* Figure out how many memory cells we will need then allocate them.
112561  */
112562  regBase = pParse->nMem + 1;
112563  nReg = pLoop->u.btree.nEq + nExtraReg;
112564  pParse->nMem += nReg;
112565
112566  zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
112567  if( !zAff ){
112568    pParse->db->mallocFailed = 1;
112569  }
112570
112571  if( nSkip ){
112572    int iIdxCur = pLevel->iIdxCur;
112573    sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
112574    VdbeCoverageIf(v, bRev==0);
112575    VdbeCoverageIf(v, bRev!=0);
112576    VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
112577    j = sqlite3VdbeAddOp0(v, OP_Goto);
112578    pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
112579                            iIdxCur, 0, regBase, nSkip);
112580    VdbeCoverageIf(v, bRev==0);
112581    VdbeCoverageIf(v, bRev!=0);
112582    sqlite3VdbeJumpHere(v, j);
112583    for(j=0; j<nSkip; j++){
112584      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
112585      assert( pIdx->aiColumn[j]>=0 );
112586      VdbeComment((v, "%s", pIdx->pTable->aCol[pIdx->aiColumn[j]].zName));
112587    }
112588  }
112589
112590  /* Evaluate the equality constraints
112591  */
112592  assert( zAff==0 || (int)strlen(zAff)>=nEq );
112593  for(j=nSkip; j<nEq; j++){
112594    int r1;
112595    pTerm = pLoop->aLTerm[j];
112596    assert( pTerm!=0 );
112597    /* The following testcase is true for indices with redundant columns.
112598    ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
112599    testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
112600    testcase( pTerm->wtFlags & TERM_VIRTUAL );
112601    r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
112602    if( r1!=regBase+j ){
112603      if( nReg==1 ){
112604        sqlite3ReleaseTempReg(pParse, regBase);
112605        regBase = r1;
112606      }else{
112607        sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
112608      }
112609    }
112610    testcase( pTerm->eOperator & WO_ISNULL );
112611    testcase( pTerm->eOperator & WO_IN );
112612    if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
112613      Expr *pRight = pTerm->pExpr->pRight;
112614      if( sqlite3ExprCanBeNull(pRight) ){
112615        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
112616        VdbeCoverage(v);
112617      }
112618      if( zAff ){
112619        if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
112620          zAff[j] = SQLITE_AFF_NONE;
112621        }
112622        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
112623          zAff[j] = SQLITE_AFF_NONE;
112624        }
112625      }
112626    }
112627  }
112628  *pzAff = zAff;
112629  return regBase;
112630}
112631
112632#ifndef SQLITE_OMIT_EXPLAIN
112633/*
112634** This routine is a helper for explainIndexRange() below
112635**
112636** pStr holds the text of an expression that we are building up one term
112637** at a time.  This routine adds a new term to the end of the expression.
112638** Terms are separated by AND so add the "AND" text for second and subsequent
112639** terms only.
112640*/
112641static void explainAppendTerm(
112642  StrAccum *pStr,             /* The text expression being built */
112643  int iTerm,                  /* Index of this term.  First is zero */
112644  const char *zColumn,        /* Name of the column */
112645  const char *zOp             /* Name of the operator */
112646){
112647  if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
112648  sqlite3StrAccumAppendAll(pStr, zColumn);
112649  sqlite3StrAccumAppend(pStr, zOp, 1);
112650  sqlite3StrAccumAppend(pStr, "?", 1);
112651}
112652
112653/*
112654** Argument pLevel describes a strategy for scanning table pTab. This
112655** function returns a pointer to a string buffer containing a description
112656** of the subset of table rows scanned by the strategy in the form of an
112657** SQL expression. Or, if all rows are scanned, NULL is returned.
112658**
112659** For example, if the query:
112660**
112661**   SELECT * FROM t1 WHERE a=1 AND b>2;
112662**
112663** is run and there is an index on (a, b), then this function returns a
112664** string similar to:
112665**
112666**   "a=? AND b>?"
112667**
112668** The returned pointer points to memory obtained from sqlite3DbMalloc().
112669** It is the responsibility of the caller to free the buffer when it is
112670** no longer required.
112671*/
112672static char *explainIndexRange(sqlite3 *db, WhereLoop *pLoop, Table *pTab){
112673  Index *pIndex = pLoop->u.btree.pIndex;
112674  u16 nEq = pLoop->u.btree.nEq;
112675  u16 nSkip = pLoop->u.btree.nSkip;
112676  int i, j;
112677  Column *aCol = pTab->aCol;
112678  i16 *aiColumn = pIndex->aiColumn;
112679  StrAccum txt;
112680
112681  if( nEq==0 && (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
112682    return 0;
112683  }
112684  sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
112685  txt.db = db;
112686  sqlite3StrAccumAppend(&txt, " (", 2);
112687  for(i=0; i<nEq; i++){
112688    char *z = (i==pIndex->nKeyCol ) ? "rowid" : aCol[aiColumn[i]].zName;
112689    if( i>=nSkip ){
112690      explainAppendTerm(&txt, i, z, "=");
112691    }else{
112692      if( i ) sqlite3StrAccumAppend(&txt, " AND ", 5);
112693      sqlite3StrAccumAppend(&txt, "ANY(", 4);
112694      sqlite3StrAccumAppendAll(&txt, z);
112695      sqlite3StrAccumAppend(&txt, ")", 1);
112696    }
112697  }
112698
112699  j = i;
112700  if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
112701    char *z = (j==pIndex->nKeyCol ) ? "rowid" : aCol[aiColumn[j]].zName;
112702    explainAppendTerm(&txt, i++, z, ">");
112703  }
112704  if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
112705    char *z = (j==pIndex->nKeyCol ) ? "rowid" : aCol[aiColumn[j]].zName;
112706    explainAppendTerm(&txt, i, z, "<");
112707  }
112708  sqlite3StrAccumAppend(&txt, ")", 1);
112709  return sqlite3StrAccumFinish(&txt);
112710}
112711
112712/*
112713** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
112714** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
112715** record is added to the output to describe the table scan strategy in
112716** pLevel.
112717*/
112718static void explainOneScan(
112719  Parse *pParse,                  /* Parse context */
112720  SrcList *pTabList,              /* Table list this loop refers to */
112721  WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
112722  int iLevel,                     /* Value for "level" column of output */
112723  int iFrom,                      /* Value for "from" column of output */
112724  u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
112725){
112726#ifndef SQLITE_DEBUG
112727  if( pParse->explain==2 )
112728#endif
112729  {
112730    struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
112731    Vdbe *v = pParse->pVdbe;      /* VM being constructed */
112732    sqlite3 *db = pParse->db;     /* Database handle */
112733    char *zMsg;                   /* Text to add to EQP output */
112734    int iId = pParse->iSelectId;  /* Select id (left-most output column) */
112735    int isSearch;                 /* True for a SEARCH. False for SCAN. */
112736    WhereLoop *pLoop;             /* The controlling WhereLoop object */
112737    u32 flags;                    /* Flags that describe this loop */
112738
112739    pLoop = pLevel->pWLoop;
112740    flags = pLoop->wsFlags;
112741    if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
112742
112743    isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
112744            || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
112745            || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
112746
112747    zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
112748    if( pItem->pSelect ){
112749      zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
112750    }else{
112751      zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
112752    }
112753
112754    if( pItem->zAlias ){
112755      zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
112756    }
112757    if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0
112758     && ALWAYS(pLoop->u.btree.pIndex!=0)
112759    ){
112760      const char *zFmt;
112761      Index *pIdx = pLoop->u.btree.pIndex;
112762      char *zWhere = explainIndexRange(db, pLoop, pItem->pTab);
112763      assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
112764      if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
112765        zFmt = zWhere ? "%s USING PRIMARY KEY%.0s%s" : "%s%.0s%s";
112766      }else if( flags & WHERE_AUTO_INDEX ){
112767        zFmt = "%s USING AUTOMATIC COVERING INDEX%.0s%s";
112768      }else if( flags & WHERE_IDX_ONLY ){
112769        zFmt = "%s USING COVERING INDEX %s%s";
112770      }else{
112771        zFmt = "%s USING INDEX %s%s";
112772      }
112773      zMsg = sqlite3MAppendf(db, zMsg, zFmt, zMsg, pIdx->zName, zWhere);
112774      sqlite3DbFree(db, zWhere);
112775    }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
112776      zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
112777
112778      if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
112779        zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
112780      }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
112781        zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
112782      }else if( flags&WHERE_BTM_LIMIT ){
112783        zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
112784      }else if( ALWAYS(flags&WHERE_TOP_LIMIT) ){
112785        zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
112786      }
112787    }
112788#ifndef SQLITE_OMIT_VIRTUALTABLE
112789    else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
112790      zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
112791                  pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
112792    }
112793#endif
112794    zMsg = sqlite3MAppendf(db, zMsg, "%s", zMsg);
112795    sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
112796  }
112797}
112798#else
112799# define explainOneScan(u,v,w,x,y,z)
112800#endif /* SQLITE_OMIT_EXPLAIN */
112801
112802
112803/*
112804** Generate code for the start of the iLevel-th loop in the WHERE clause
112805** implementation described by pWInfo.
112806*/
112807static Bitmask codeOneLoopStart(
112808  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
112809  int iLevel,          /* Which level of pWInfo->a[] should be coded */
112810  Bitmask notReady     /* Which tables are currently available */
112811){
112812  int j, k;            /* Loop counters */
112813  int iCur;            /* The VDBE cursor for the table */
112814  int addrNxt;         /* Where to jump to continue with the next IN case */
112815  int omitTable;       /* True if we use the index only */
112816  int bRev;            /* True if we need to scan in reverse order */
112817  WhereLevel *pLevel;  /* The where level to be coded */
112818  WhereLoop *pLoop;    /* The WhereLoop object being coded */
112819  WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
112820  WhereTerm *pTerm;               /* A WHERE clause term */
112821  Parse *pParse;                  /* Parsing context */
112822  sqlite3 *db;                    /* Database connection */
112823  Vdbe *v;                        /* The prepared stmt under constructions */
112824  struct SrcList_item *pTabItem;  /* FROM clause term being coded */
112825  int addrBrk;                    /* Jump here to break out of the loop */
112826  int addrCont;                   /* Jump here to continue with next cycle */
112827  int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
112828  int iReleaseReg = 0;      /* Temp register to free before returning */
112829
112830  pParse = pWInfo->pParse;
112831  v = pParse->pVdbe;
112832  pWC = &pWInfo->sWC;
112833  db = pParse->db;
112834  pLevel = &pWInfo->a[iLevel];
112835  pLoop = pLevel->pWLoop;
112836  pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
112837  iCur = pTabItem->iCursor;
112838  pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
112839  bRev = (pWInfo->revMask>>iLevel)&1;
112840  omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
112841           && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
112842  VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
112843
112844  /* Create labels for the "break" and "continue" instructions
112845  ** for the current loop.  Jump to addrBrk to break out of a loop.
112846  ** Jump to cont to go immediately to the next iteration of the
112847  ** loop.
112848  **
112849  ** When there is an IN operator, we also have a "addrNxt" label that
112850  ** means to continue with the next IN value combination.  When
112851  ** there are no IN operators in the constraints, the "addrNxt" label
112852  ** is the same as "addrBrk".
112853  */
112854  addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
112855  addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
112856
112857  /* If this is the right table of a LEFT OUTER JOIN, allocate and
112858  ** initialize a memory cell that records if this table matches any
112859  ** row of the left table of the join.
112860  */
112861  if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
112862    pLevel->iLeftJoin = ++pParse->nMem;
112863    sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
112864    VdbeComment((v, "init LEFT JOIN no-match flag"));
112865  }
112866
112867  /* Special case of a FROM clause subquery implemented as a co-routine */
112868  if( pTabItem->viaCoroutine ){
112869    int regYield = pTabItem->regReturn;
112870    sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
112871    pLevel->p2 =  sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
112872    VdbeCoverage(v);
112873    VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
112874    pLevel->op = OP_Goto;
112875  }else
112876
112877#ifndef SQLITE_OMIT_VIRTUALTABLE
112878  if(  (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
112879    /* Case 1:  The table is a virtual-table.  Use the VFilter and VNext
112880    **          to access the data.
112881    */
112882    int iReg;   /* P3 Value for OP_VFilter */
112883    int addrNotFound;
112884    int nConstraint = pLoop->nLTerm;
112885
112886    sqlite3ExprCachePush(pParse);
112887    iReg = sqlite3GetTempRange(pParse, nConstraint+2);
112888    addrNotFound = pLevel->addrBrk;
112889    for(j=0; j<nConstraint; j++){
112890      int iTarget = iReg+j+2;
112891      pTerm = pLoop->aLTerm[j];
112892      if( pTerm==0 ) continue;
112893      if( pTerm->eOperator & WO_IN ){
112894        codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
112895        addrNotFound = pLevel->addrNxt;
112896      }else{
112897        sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
112898      }
112899    }
112900    sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
112901    sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
112902    sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
112903                      pLoop->u.vtab.idxStr,
112904                      pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
112905    VdbeCoverage(v);
112906    pLoop->u.vtab.needFree = 0;
112907    for(j=0; j<nConstraint && j<16; j++){
112908      if( (pLoop->u.vtab.omitMask>>j)&1 ){
112909        disableTerm(pLevel, pLoop->aLTerm[j]);
112910      }
112911    }
112912    pLevel->op = OP_VNext;
112913    pLevel->p1 = iCur;
112914    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
112915    sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
112916    sqlite3ExprCachePop(pParse);
112917  }else
112918#endif /* SQLITE_OMIT_VIRTUALTABLE */
112919
112920  if( (pLoop->wsFlags & WHERE_IPK)!=0
112921   && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
112922  ){
112923    /* Case 2:  We can directly reference a single row using an
112924    **          equality comparison against the ROWID field.  Or
112925    **          we reference multiple rows using a "rowid IN (...)"
112926    **          construct.
112927    */
112928    assert( pLoop->u.btree.nEq==1 );
112929    pTerm = pLoop->aLTerm[0];
112930    assert( pTerm!=0 );
112931    assert( pTerm->pExpr!=0 );
112932    assert( omitTable==0 );
112933    testcase( pTerm->wtFlags & TERM_VIRTUAL );
112934    iReleaseReg = ++pParse->nMem;
112935    iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
112936    if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
112937    addrNxt = pLevel->addrNxt;
112938    sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
112939    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
112940    VdbeCoverage(v);
112941    sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
112942    sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
112943    VdbeComment((v, "pk"));
112944    pLevel->op = OP_Noop;
112945  }else if( (pLoop->wsFlags & WHERE_IPK)!=0
112946         && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
112947  ){
112948    /* Case 3:  We have an inequality comparison against the ROWID field.
112949    */
112950    int testOp = OP_Noop;
112951    int start;
112952    int memEndValue = 0;
112953    WhereTerm *pStart, *pEnd;
112954
112955    assert( omitTable==0 );
112956    j = 0;
112957    pStart = pEnd = 0;
112958    if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
112959    if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
112960    assert( pStart!=0 || pEnd!=0 );
112961    if( bRev ){
112962      pTerm = pStart;
112963      pStart = pEnd;
112964      pEnd = pTerm;
112965    }
112966    if( pStart ){
112967      Expr *pX;             /* The expression that defines the start bound */
112968      int r1, rTemp;        /* Registers for holding the start boundary */
112969
112970      /* The following constant maps TK_xx codes into corresponding
112971      ** seek opcodes.  It depends on a particular ordering of TK_xx
112972      */
112973      const u8 aMoveOp[] = {
112974           /* TK_GT */  OP_SeekGT,
112975           /* TK_LE */  OP_SeekLE,
112976           /* TK_LT */  OP_SeekLT,
112977           /* TK_GE */  OP_SeekGE
112978      };
112979      assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
112980      assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
112981      assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
112982
112983      assert( (pStart->wtFlags & TERM_VNULL)==0 );
112984      testcase( pStart->wtFlags & TERM_VIRTUAL );
112985      pX = pStart->pExpr;
112986      assert( pX!=0 );
112987      testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
112988      r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
112989      sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
112990      VdbeComment((v, "pk"));
112991      VdbeCoverageIf(v, pX->op==TK_GT);
112992      VdbeCoverageIf(v, pX->op==TK_LE);
112993      VdbeCoverageIf(v, pX->op==TK_LT);
112994      VdbeCoverageIf(v, pX->op==TK_GE);
112995      sqlite3ExprCacheAffinityChange(pParse, r1, 1);
112996      sqlite3ReleaseTempReg(pParse, rTemp);
112997      disableTerm(pLevel, pStart);
112998    }else{
112999      sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
113000      VdbeCoverageIf(v, bRev==0);
113001      VdbeCoverageIf(v, bRev!=0);
113002    }
113003    if( pEnd ){
113004      Expr *pX;
113005      pX = pEnd->pExpr;
113006      assert( pX!=0 );
113007      assert( (pEnd->wtFlags & TERM_VNULL)==0 );
113008      testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
113009      testcase( pEnd->wtFlags & TERM_VIRTUAL );
113010      memEndValue = ++pParse->nMem;
113011      sqlite3ExprCode(pParse, pX->pRight, memEndValue);
113012      if( pX->op==TK_LT || pX->op==TK_GT ){
113013        testOp = bRev ? OP_Le : OP_Ge;
113014      }else{
113015        testOp = bRev ? OP_Lt : OP_Gt;
113016      }
113017      disableTerm(pLevel, pEnd);
113018    }
113019    start = sqlite3VdbeCurrentAddr(v);
113020    pLevel->op = bRev ? OP_Prev : OP_Next;
113021    pLevel->p1 = iCur;
113022    pLevel->p2 = start;
113023    assert( pLevel->p5==0 );
113024    if( testOp!=OP_Noop ){
113025      iRowidReg = ++pParse->nMem;
113026      sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
113027      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
113028      sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
113029      VdbeCoverageIf(v, testOp==OP_Le);
113030      VdbeCoverageIf(v, testOp==OP_Lt);
113031      VdbeCoverageIf(v, testOp==OP_Ge);
113032      VdbeCoverageIf(v, testOp==OP_Gt);
113033      sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
113034    }
113035  }else if( pLoop->wsFlags & WHERE_INDEXED ){
113036    /* Case 4: A scan using an index.
113037    **
113038    **         The WHERE clause may contain zero or more equality
113039    **         terms ("==" or "IN" operators) that refer to the N
113040    **         left-most columns of the index. It may also contain
113041    **         inequality constraints (>, <, >= or <=) on the indexed
113042    **         column that immediately follows the N equalities. Only
113043    **         the right-most column can be an inequality - the rest must
113044    **         use the "==" and "IN" operators. For example, if the
113045    **         index is on (x,y,z), then the following clauses are all
113046    **         optimized:
113047    **
113048    **            x=5
113049    **            x=5 AND y=10
113050    **            x=5 AND y<10
113051    **            x=5 AND y>5 AND y<10
113052    **            x=5 AND y=5 AND z<=10
113053    **
113054    **         The z<10 term of the following cannot be used, only
113055    **         the x=5 term:
113056    **
113057    **            x=5 AND z<10
113058    **
113059    **         N may be zero if there are inequality constraints.
113060    **         If there are no inequality constraints, then N is at
113061    **         least one.
113062    **
113063    **         This case is also used when there are no WHERE clause
113064    **         constraints but an index is selected anyway, in order
113065    **         to force the output order to conform to an ORDER BY.
113066    */
113067    static const u8 aStartOp[] = {
113068      0,
113069      0,
113070      OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
113071      OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
113072      OP_SeekGT,           /* 4: (start_constraints  && !startEq && !bRev) */
113073      OP_SeekLT,           /* 5: (start_constraints  && !startEq &&  bRev) */
113074      OP_SeekGE,           /* 6: (start_constraints  &&  startEq && !bRev) */
113075      OP_SeekLE            /* 7: (start_constraints  &&  startEq &&  bRev) */
113076    };
113077    static const u8 aEndOp[] = {
113078      OP_IdxGE,            /* 0: (end_constraints && !bRev && !endEq) */
113079      OP_IdxGT,            /* 1: (end_constraints && !bRev &&  endEq) */
113080      OP_IdxLE,            /* 2: (end_constraints &&  bRev && !endEq) */
113081      OP_IdxLT,            /* 3: (end_constraints &&  bRev &&  endEq) */
113082    };
113083    u16 nEq = pLoop->u.btree.nEq;     /* Number of == or IN terms */
113084    int regBase;                 /* Base register holding constraint values */
113085    WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
113086    WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
113087    int startEq;                 /* True if range start uses ==, >= or <= */
113088    int endEq;                   /* True if range end uses ==, >= or <= */
113089    int start_constraints;       /* Start of range is constrained */
113090    int nConstraint;             /* Number of constraint terms */
113091    Index *pIdx;                 /* The index we will be using */
113092    int iIdxCur;                 /* The VDBE cursor for the index */
113093    int nExtraReg = 0;           /* Number of extra registers needed */
113094    int op;                      /* Instruction opcode */
113095    char *zStartAff;             /* Affinity for start of range constraint */
113096    char cEndAff = 0;            /* Affinity for end of range constraint */
113097    u8 bSeekPastNull = 0;        /* True to seek past initial nulls */
113098    u8 bStopAtNull = 0;          /* Add condition to terminate at NULLs */
113099
113100    pIdx = pLoop->u.btree.pIndex;
113101    iIdxCur = pLevel->iIdxCur;
113102    assert( nEq>=pLoop->u.btree.nSkip );
113103
113104    /* If this loop satisfies a sort order (pOrderBy) request that
113105    ** was passed to this function to implement a "SELECT min(x) ..."
113106    ** query, then the caller will only allow the loop to run for
113107    ** a single iteration. This means that the first row returned
113108    ** should not have a NULL value stored in 'x'. If column 'x' is
113109    ** the first one after the nEq equality constraints in the index,
113110    ** this requires some special handling.
113111    */
113112    assert( pWInfo->pOrderBy==0
113113         || pWInfo->pOrderBy->nExpr==1
113114         || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
113115    if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
113116     && pWInfo->nOBSat>0
113117     && (pIdx->nKeyCol>nEq)
113118    ){
113119      assert( pLoop->u.btree.nSkip==0 );
113120      bSeekPastNull = 1;
113121      nExtraReg = 1;
113122    }
113123
113124    /* Find any inequality constraint terms for the start and end
113125    ** of the range.
113126    */
113127    j = nEq;
113128    if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
113129      pRangeStart = pLoop->aLTerm[j++];
113130      nExtraReg = 1;
113131    }
113132    if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
113133      pRangeEnd = pLoop->aLTerm[j++];
113134      nExtraReg = 1;
113135      if( pRangeStart==0
113136       && (j = pIdx->aiColumn[nEq])>=0
113137       && pIdx->pTable->aCol[j].notNull==0
113138      ){
113139        bSeekPastNull = 1;
113140      }
113141    }
113142    assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
113143
113144    /* Generate code to evaluate all constraint terms using == or IN
113145    ** and store the values of those terms in an array of registers
113146    ** starting at regBase.
113147    */
113148    regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
113149    assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
113150    if( zStartAff ) cEndAff = zStartAff[nEq];
113151    addrNxt = pLevel->addrNxt;
113152
113153    /* If we are doing a reverse order scan on an ascending index, or
113154    ** a forward order scan on a descending index, interchange the
113155    ** start and end terms (pRangeStart and pRangeEnd).
113156    */
113157    if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
113158     || (bRev && pIdx->nKeyCol==nEq)
113159    ){
113160      SWAP(WhereTerm *, pRangeEnd, pRangeStart);
113161      SWAP(u8, bSeekPastNull, bStopAtNull);
113162    }
113163
113164    testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
113165    testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
113166    testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
113167    testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
113168    startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
113169    endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
113170    start_constraints = pRangeStart || nEq>0;
113171
113172    /* Seek the index cursor to the start of the range. */
113173    nConstraint = nEq;
113174    if( pRangeStart ){
113175      Expr *pRight = pRangeStart->pExpr->pRight;
113176      sqlite3ExprCode(pParse, pRight, regBase+nEq);
113177      if( (pRangeStart->wtFlags & TERM_VNULL)==0
113178       && sqlite3ExprCanBeNull(pRight)
113179      ){
113180        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
113181        VdbeCoverage(v);
113182      }
113183      if( zStartAff ){
113184        if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
113185          /* Since the comparison is to be performed with no conversions
113186          ** applied to the operands, set the affinity to apply to pRight to
113187          ** SQLITE_AFF_NONE.  */
113188          zStartAff[nEq] = SQLITE_AFF_NONE;
113189        }
113190        if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
113191          zStartAff[nEq] = SQLITE_AFF_NONE;
113192        }
113193      }
113194      nConstraint++;
113195      testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
113196    }else if( bSeekPastNull ){
113197      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
113198      nConstraint++;
113199      startEq = 0;
113200      start_constraints = 1;
113201    }
113202    codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
113203    op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
113204    assert( op!=0 );
113205    sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
113206    VdbeCoverage(v);
113207    VdbeCoverageIf(v, op==OP_Rewind);  testcase( op==OP_Rewind );
113208    VdbeCoverageIf(v, op==OP_Last);    testcase( op==OP_Last );
113209    VdbeCoverageIf(v, op==OP_SeekGT);  testcase( op==OP_SeekGT );
113210    VdbeCoverageIf(v, op==OP_SeekGE);  testcase( op==OP_SeekGE );
113211    VdbeCoverageIf(v, op==OP_SeekLE);  testcase( op==OP_SeekLE );
113212    VdbeCoverageIf(v, op==OP_SeekLT);  testcase( op==OP_SeekLT );
113213
113214    /* Load the value for the inequality constraint at the end of the
113215    ** range (if any).
113216    */
113217    nConstraint = nEq;
113218    if( pRangeEnd ){
113219      Expr *pRight = pRangeEnd->pExpr->pRight;
113220      sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
113221      sqlite3ExprCode(pParse, pRight, regBase+nEq);
113222      if( (pRangeEnd->wtFlags & TERM_VNULL)==0
113223       && sqlite3ExprCanBeNull(pRight)
113224      ){
113225        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
113226        VdbeCoverage(v);
113227      }
113228      if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_NONE
113229       && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
113230      ){
113231        codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
113232      }
113233      nConstraint++;
113234      testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
113235    }else if( bStopAtNull ){
113236      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
113237      endEq = 0;
113238      nConstraint++;
113239    }
113240    sqlite3DbFree(db, zStartAff);
113241
113242    /* Top of the loop body */
113243    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
113244
113245    /* Check if the index cursor is past the end of the range. */
113246    if( nConstraint ){
113247      op = aEndOp[bRev*2 + endEq];
113248      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
113249      testcase( op==OP_IdxGT );  VdbeCoverageIf(v, op==OP_IdxGT );
113250      testcase( op==OP_IdxGE );  VdbeCoverageIf(v, op==OP_IdxGE );
113251      testcase( op==OP_IdxLT );  VdbeCoverageIf(v, op==OP_IdxLT );
113252      testcase( op==OP_IdxLE );  VdbeCoverageIf(v, op==OP_IdxLE );
113253    }
113254
113255    /* Seek the table cursor, if required */
113256    disableTerm(pLevel, pRangeStart);
113257    disableTerm(pLevel, pRangeEnd);
113258    if( omitTable ){
113259      /* pIdx is a covering index.  No need to access the main table. */
113260    }else if( HasRowid(pIdx->pTable) ){
113261      iRowidReg = ++pParse->nMem;
113262      sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
113263      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
113264      sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
113265    }else if( iCur!=iIdxCur ){
113266      Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
113267      iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
113268      for(j=0; j<pPk->nKeyCol; j++){
113269        k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
113270        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
113271      }
113272      sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
113273                           iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
113274    }
113275
113276    /* Record the instruction used to terminate the loop. Disable
113277    ** WHERE clause terms made redundant by the index range scan.
113278    */
113279    if( pLoop->wsFlags & WHERE_ONEROW ){
113280      pLevel->op = OP_Noop;
113281    }else if( bRev ){
113282      pLevel->op = OP_Prev;
113283    }else{
113284      pLevel->op = OP_Next;
113285    }
113286    pLevel->p1 = iIdxCur;
113287    pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
113288    if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
113289      pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
113290    }else{
113291      assert( pLevel->p5==0 );
113292    }
113293  }else
113294
113295#ifndef SQLITE_OMIT_OR_OPTIMIZATION
113296  if( pLoop->wsFlags & WHERE_MULTI_OR ){
113297    /* Case 5:  Two or more separately indexed terms connected by OR
113298    **
113299    ** Example:
113300    **
113301    **   CREATE TABLE t1(a,b,c,d);
113302    **   CREATE INDEX i1 ON t1(a);
113303    **   CREATE INDEX i2 ON t1(b);
113304    **   CREATE INDEX i3 ON t1(c);
113305    **
113306    **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
113307    **
113308    ** In the example, there are three indexed terms connected by OR.
113309    ** The top of the loop looks like this:
113310    **
113311    **          Null       1                # Zero the rowset in reg 1
113312    **
113313    ** Then, for each indexed term, the following. The arguments to
113314    ** RowSetTest are such that the rowid of the current row is inserted
113315    ** into the RowSet. If it is already present, control skips the
113316    ** Gosub opcode and jumps straight to the code generated by WhereEnd().
113317    **
113318    **        sqlite3WhereBegin(<term>)
113319    **          RowSetTest                  # Insert rowid into rowset
113320    **          Gosub      2 A
113321    **        sqlite3WhereEnd()
113322    **
113323    ** Following the above, code to terminate the loop. Label A, the target
113324    ** of the Gosub above, jumps to the instruction right after the Goto.
113325    **
113326    **          Null       1                # Zero the rowset in reg 1
113327    **          Goto       B                # The loop is finished.
113328    **
113329    **       A: <loop body>                 # Return data, whatever.
113330    **
113331    **          Return     2                # Jump back to the Gosub
113332    **
113333    **       B: <after the loop>
113334    **
113335    ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
113336    ** use an ephermeral index instead of a RowSet to record the primary
113337    ** keys of the rows we have already seen.
113338    **
113339    */
113340    WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
113341    SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
113342    Index *pCov = 0;             /* Potential covering index (or NULL) */
113343    int iCovCur = pParse->nTab++;  /* Cursor used for index scans (if any) */
113344
113345    int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
113346    int regRowset = 0;                        /* Register for RowSet object */
113347    int regRowid = 0;                         /* Register holding rowid */
113348    int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
113349    int iRetInit;                             /* Address of regReturn init */
113350    int untestedTerms = 0;             /* Some terms not completely tested */
113351    int ii;                            /* Loop counter */
113352    Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
113353    Table *pTab = pTabItem->pTab;
113354
113355    pTerm = pLoop->aLTerm[0];
113356    assert( pTerm!=0 );
113357    assert( pTerm->eOperator & WO_OR );
113358    assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
113359    pOrWc = &pTerm->u.pOrInfo->wc;
113360    pLevel->op = OP_Return;
113361    pLevel->p1 = regReturn;
113362
113363    /* Set up a new SrcList in pOrTab containing the table being scanned
113364    ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
113365    ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
113366    */
113367    if( pWInfo->nLevel>1 ){
113368      int nNotReady;                 /* The number of notReady tables */
113369      struct SrcList_item *origSrc;     /* Original list of tables */
113370      nNotReady = pWInfo->nLevel - iLevel - 1;
113371      pOrTab = sqlite3StackAllocRaw(db,
113372                            sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
113373      if( pOrTab==0 ) return notReady;
113374      pOrTab->nAlloc = (u8)(nNotReady + 1);
113375      pOrTab->nSrc = pOrTab->nAlloc;
113376      memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
113377      origSrc = pWInfo->pTabList->a;
113378      for(k=1; k<=nNotReady; k++){
113379        memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
113380      }
113381    }else{
113382      pOrTab = pWInfo->pTabList;
113383    }
113384
113385    /* Initialize the rowset register to contain NULL. An SQL NULL is
113386    ** equivalent to an empty rowset.  Or, create an ephermeral index
113387    ** capable of holding primary keys in the case of a WITHOUT ROWID.
113388    **
113389    ** Also initialize regReturn to contain the address of the instruction
113390    ** immediately following the OP_Return at the bottom of the loop. This
113391    ** is required in a few obscure LEFT JOIN cases where control jumps
113392    ** over the top of the loop into the body of it. In this case the
113393    ** correct response for the end-of-loop code (the OP_Return) is to
113394    ** fall through to the next instruction, just as an OP_Next does if
113395    ** called on an uninitialized cursor.
113396    */
113397    if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
113398      if( HasRowid(pTab) ){
113399        regRowset = ++pParse->nMem;
113400        sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
113401      }else{
113402        Index *pPk = sqlite3PrimaryKeyIndex(pTab);
113403        regRowset = pParse->nTab++;
113404        sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
113405        sqlite3VdbeSetP4KeyInfo(pParse, pPk);
113406      }
113407      regRowid = ++pParse->nMem;
113408    }
113409    iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
113410
113411    /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
113412    ** Then for every term xN, evaluate as the subexpression: xN AND z
113413    ** That way, terms in y that are factored into the disjunction will
113414    ** be picked up by the recursive calls to sqlite3WhereBegin() below.
113415    **
113416    ** Actually, each subexpression is converted to "xN AND w" where w is
113417    ** the "interesting" terms of z - terms that did not originate in the
113418    ** ON or USING clause of a LEFT JOIN, and terms that are usable as
113419    ** indices.
113420    **
113421    ** This optimization also only applies if the (x1 OR x2 OR ...) term
113422    ** is not contained in the ON clause of a LEFT JOIN.
113423    ** See ticket http://www.sqlite.org/src/info/f2369304e4
113424    */
113425    if( pWC->nTerm>1 ){
113426      int iTerm;
113427      for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
113428        Expr *pExpr = pWC->a[iTerm].pExpr;
113429        if( &pWC->a[iTerm] == pTerm ) continue;
113430        if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
113431        testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
113432        testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
113433        if( pWC->a[iTerm].wtFlags & (TERM_ORINFO|TERM_VIRTUAL) ) continue;
113434        if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
113435        pExpr = sqlite3ExprDup(db, pExpr, 0);
113436        pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
113437      }
113438      if( pAndExpr ){
113439        pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
113440      }
113441    }
113442
113443    /* Run a separate WHERE clause for each term of the OR clause.  After
113444    ** eliminating duplicates from other WHERE clauses, the action for each
113445    ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
113446    */
113447    for(ii=0; ii<pOrWc->nTerm; ii++){
113448      WhereTerm *pOrTerm = &pOrWc->a[ii];
113449      if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
113450        WhereInfo *pSubWInfo;           /* Info for single OR-term scan */
113451        Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
113452        int j1 = 0;                     /* Address of jump operation */
113453        if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
113454          pAndExpr->pLeft = pOrExpr;
113455          pOrExpr = pAndExpr;
113456        }
113457        /* Loop through table entries that match term pOrTerm. */
113458        pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
113459                        WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
113460                        WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
113461        assert( pSubWInfo || pParse->nErr || db->mallocFailed );
113462        if( pSubWInfo ){
113463          WhereLoop *pSubLoop;
113464          explainOneScan(
113465              pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
113466          );
113467          /* This is the sub-WHERE clause body.  First skip over
113468          ** duplicate rows from prior sub-WHERE clauses, and record the
113469          ** rowid (or PRIMARY KEY) for the current row so that the same
113470          ** row will be skipped in subsequent sub-WHERE clauses.
113471          */
113472          if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
113473            int r;
113474            int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
113475            if( HasRowid(pTab) ){
113476              r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
113477              j1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, r,iSet);
113478              VdbeCoverage(v);
113479            }else{
113480              Index *pPk = sqlite3PrimaryKeyIndex(pTab);
113481              int nPk = pPk->nKeyCol;
113482              int iPk;
113483
113484              /* Read the PK into an array of temp registers. */
113485              r = sqlite3GetTempRange(pParse, nPk);
113486              for(iPk=0; iPk<nPk; iPk++){
113487                int iCol = pPk->aiColumn[iPk];
113488                sqlite3ExprCodeGetColumn(pParse, pTab, iCol, iCur, r+iPk, 0);
113489              }
113490
113491              /* Check if the temp table already contains this key. If so,
113492              ** the row has already been included in the result set and
113493              ** can be ignored (by jumping past the Gosub below). Otherwise,
113494              ** insert the key into the temp table and proceed with processing
113495              ** the row.
113496              **
113497              ** Use some of the same optimizations as OP_RowSetTest: If iSet
113498              ** is zero, assume that the key cannot already be present in
113499              ** the temp table. And if iSet is -1, assume that there is no
113500              ** need to insert the key into the temp table, as it will never
113501              ** be tested for.  */
113502              if( iSet ){
113503                j1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
113504                VdbeCoverage(v);
113505              }
113506              if( iSet>=0 ){
113507                sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
113508                sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
113509                if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
113510              }
113511
113512              /* Release the array of temp registers */
113513              sqlite3ReleaseTempRange(pParse, r, nPk);
113514            }
113515          }
113516
113517          /* Invoke the main loop body as a subroutine */
113518          sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
113519
113520          /* Jump here (skipping the main loop body subroutine) if the
113521          ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
113522          if( j1 ) sqlite3VdbeJumpHere(v, j1);
113523
113524          /* The pSubWInfo->untestedTerms flag means that this OR term
113525          ** contained one or more AND term from a notReady table.  The
113526          ** terms from the notReady table could not be tested and will
113527          ** need to be tested later.
113528          */
113529          if( pSubWInfo->untestedTerms ) untestedTerms = 1;
113530
113531          /* If all of the OR-connected terms are optimized using the same
113532          ** index, and the index is opened using the same cursor number
113533          ** by each call to sqlite3WhereBegin() made by this loop, it may
113534          ** be possible to use that index as a covering index.
113535          **
113536          ** If the call to sqlite3WhereBegin() above resulted in a scan that
113537          ** uses an index, and this is either the first OR-connected term
113538          ** processed or the index is the same as that used by all previous
113539          ** terms, set pCov to the candidate covering index. Otherwise, set
113540          ** pCov to NULL to indicate that no candidate covering index will
113541          ** be available.
113542          */
113543          pSubLoop = pSubWInfo->a[0].pWLoop;
113544          assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
113545          if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
113546           && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
113547           && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
113548          ){
113549            assert( pSubWInfo->a[0].iIdxCur==iCovCur );
113550            pCov = pSubLoop->u.btree.pIndex;
113551          }else{
113552            pCov = 0;
113553          }
113554
113555          /* Finish the loop through table entries that match term pOrTerm. */
113556          sqlite3WhereEnd(pSubWInfo);
113557        }
113558      }
113559    }
113560    pLevel->u.pCovidx = pCov;
113561    if( pCov ) pLevel->iIdxCur = iCovCur;
113562    if( pAndExpr ){
113563      pAndExpr->pLeft = 0;
113564      sqlite3ExprDelete(db, pAndExpr);
113565    }
113566    sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
113567    sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
113568    sqlite3VdbeResolveLabel(v, iLoopBody);
113569
113570    if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
113571    if( !untestedTerms ) disableTerm(pLevel, pTerm);
113572  }else
113573#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
113574
113575  {
113576    /* Case 6:  There is no usable index.  We must do a complete
113577    **          scan of the entire table.
113578    */
113579    static const u8 aStep[] = { OP_Next, OP_Prev };
113580    static const u8 aStart[] = { OP_Rewind, OP_Last };
113581    assert( bRev==0 || bRev==1 );
113582    if( pTabItem->isRecursive ){
113583      /* Tables marked isRecursive have only a single row that is stored in
113584      ** a pseudo-cursor.  No need to Rewind or Next such cursors. */
113585      pLevel->op = OP_Noop;
113586    }else{
113587      pLevel->op = aStep[bRev];
113588      pLevel->p1 = iCur;
113589      pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
113590      VdbeCoverageIf(v, bRev==0);
113591      VdbeCoverageIf(v, bRev!=0);
113592      pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
113593    }
113594  }
113595
113596  /* Insert code to test every subexpression that can be completely
113597  ** computed using the current set of tables.
113598  */
113599  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
113600    Expr *pE;
113601    testcase( pTerm->wtFlags & TERM_VIRTUAL );
113602    testcase( pTerm->wtFlags & TERM_CODED );
113603    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
113604    if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
113605      testcase( pWInfo->untestedTerms==0
113606               && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
113607      pWInfo->untestedTerms = 1;
113608      continue;
113609    }
113610    pE = pTerm->pExpr;
113611    assert( pE!=0 );
113612    if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
113613      continue;
113614    }
113615    sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
113616    pTerm->wtFlags |= TERM_CODED;
113617  }
113618
113619  /* Insert code to test for implied constraints based on transitivity
113620  ** of the "==" operator.
113621  **
113622  ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
113623  ** and we are coding the t1 loop and the t2 loop has not yet coded,
113624  ** then we cannot use the "t1.a=t2.b" constraint, but we can code
113625  ** the implied "t1.a=123" constraint.
113626  */
113627  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
113628    Expr *pE, *pEAlt;
113629    WhereTerm *pAlt;
113630    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
113631    if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
113632    if( pTerm->leftCursor!=iCur ) continue;
113633    if( pLevel->iLeftJoin ) continue;
113634    pE = pTerm->pExpr;
113635    assert( !ExprHasProperty(pE, EP_FromJoin) );
113636    assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
113637    pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
113638    if( pAlt==0 ) continue;
113639    if( pAlt->wtFlags & (TERM_CODED) ) continue;
113640    testcase( pAlt->eOperator & WO_EQ );
113641    testcase( pAlt->eOperator & WO_IN );
113642    VdbeModuleComment((v, "begin transitive constraint"));
113643    pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
113644    if( pEAlt ){
113645      *pEAlt = *pAlt->pExpr;
113646      pEAlt->pLeft = pE->pLeft;
113647      sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
113648      sqlite3StackFree(db, pEAlt);
113649    }
113650  }
113651
113652  /* For a LEFT OUTER JOIN, generate code that will record the fact that
113653  ** at least one row of the right table has matched the left table.
113654  */
113655  if( pLevel->iLeftJoin ){
113656    pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
113657    sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
113658    VdbeComment((v, "record LEFT JOIN hit"));
113659    sqlite3ExprCacheClear(pParse);
113660    for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
113661      testcase( pTerm->wtFlags & TERM_VIRTUAL );
113662      testcase( pTerm->wtFlags & TERM_CODED );
113663      if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
113664      if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
113665        assert( pWInfo->untestedTerms );
113666        continue;
113667      }
113668      assert( pTerm->pExpr );
113669      sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
113670      pTerm->wtFlags |= TERM_CODED;
113671    }
113672  }
113673
113674  return pLevel->notReady;
113675}
113676
113677#if defined(WHERETRACE_ENABLED) && defined(SQLITE_ENABLE_TREE_EXPLAIN)
113678/*
113679** Generate "Explanation" text for a WhereTerm.
113680*/
113681static void whereExplainTerm(Vdbe *v, WhereTerm *pTerm){
113682  char zType[4];
113683  memcpy(zType, "...", 4);
113684  if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
113685  if( pTerm->eOperator & WO_EQUIV  ) zType[1] = 'E';
113686  if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
113687  sqlite3ExplainPrintf(v, "%s ", zType);
113688  sqlite3ExplainExpr(v, pTerm->pExpr);
113689}
113690#endif /* WHERETRACE_ENABLED && SQLITE_ENABLE_TREE_EXPLAIN */
113691
113692
113693#ifdef WHERETRACE_ENABLED
113694/*
113695** Print a WhereLoop object for debugging purposes
113696*/
113697static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
113698  WhereInfo *pWInfo = pWC->pWInfo;
113699  int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
113700  struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
113701  Table *pTab = pItem->pTab;
113702  sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
113703                     p->iTab, nb, p->maskSelf, nb, p->prereq);
113704  sqlite3DebugPrintf(" %12s",
113705                     pItem->zAlias ? pItem->zAlias : pTab->zName);
113706  if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
113707     const char *zName;
113708     if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
113709      if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
113710        int i = sqlite3Strlen30(zName) - 1;
113711        while( zName[i]!='_' ) i--;
113712        zName += i;
113713      }
113714      sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
113715    }else{
113716      sqlite3DebugPrintf("%20s","");
113717    }
113718  }else{
113719    char *z;
113720    if( p->u.vtab.idxStr ){
113721      z = sqlite3_mprintf("(%d,\"%s\",%x)",
113722                p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
113723    }else{
113724      z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
113725    }
113726    sqlite3DebugPrintf(" %-19s", z);
113727    sqlite3_free(z);
113728  }
113729  sqlite3DebugPrintf(" f %04x N %d", p->wsFlags, p->nLTerm);
113730  sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
113731#ifdef SQLITE_ENABLE_TREE_EXPLAIN
113732  /* If the 0x100 bit of wheretracing is set, then show all of the constraint
113733  ** expressions in the WhereLoop.aLTerm[] array.
113734  */
113735  if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){  /* WHERETRACE 0x100 */
113736    int i;
113737    Vdbe *v = pWInfo->pParse->pVdbe;
113738    sqlite3ExplainBegin(v);
113739    for(i=0; i<p->nLTerm; i++){
113740      WhereTerm *pTerm = p->aLTerm[i];
113741      if( pTerm==0 ) continue;
113742      sqlite3ExplainPrintf(v, "  (%d) #%-2d ", i+1, (int)(pTerm-pWC->a));
113743      sqlite3ExplainPush(v);
113744      whereExplainTerm(v, pTerm);
113745      sqlite3ExplainPop(v);
113746      sqlite3ExplainNL(v);
113747    }
113748    sqlite3ExplainFinish(v);
113749    sqlite3DebugPrintf("%s", sqlite3VdbeExplanation(v));
113750  }
113751#endif
113752}
113753#endif
113754
113755/*
113756** Convert bulk memory into a valid WhereLoop that can be passed
113757** to whereLoopClear harmlessly.
113758*/
113759static void whereLoopInit(WhereLoop *p){
113760  p->aLTerm = p->aLTermSpace;
113761  p->nLTerm = 0;
113762  p->nLSlot = ArraySize(p->aLTermSpace);
113763  p->wsFlags = 0;
113764}
113765
113766/*
113767** Clear the WhereLoop.u union.  Leave WhereLoop.pLTerm intact.
113768*/
113769static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
113770  if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
113771    if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
113772      sqlite3_free(p->u.vtab.idxStr);
113773      p->u.vtab.needFree = 0;
113774      p->u.vtab.idxStr = 0;
113775    }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
113776      sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
113777      sqlite3KeyInfoUnref(p->u.btree.pIndex->pKeyInfo);
113778      sqlite3DbFree(db, p->u.btree.pIndex);
113779      p->u.btree.pIndex = 0;
113780    }
113781  }
113782}
113783
113784/*
113785** Deallocate internal memory used by a WhereLoop object
113786*/
113787static void whereLoopClear(sqlite3 *db, WhereLoop *p){
113788  if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
113789  whereLoopClearUnion(db, p);
113790  whereLoopInit(p);
113791}
113792
113793/*
113794** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
113795*/
113796static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
113797  WhereTerm **paNew;
113798  if( p->nLSlot>=n ) return SQLITE_OK;
113799  n = (n+7)&~7;
113800  paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
113801  if( paNew==0 ) return SQLITE_NOMEM;
113802  memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
113803  if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
113804  p->aLTerm = paNew;
113805  p->nLSlot = n;
113806  return SQLITE_OK;
113807}
113808
113809/*
113810** Transfer content from the second pLoop into the first.
113811*/
113812static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
113813  whereLoopClearUnion(db, pTo);
113814  if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
113815    memset(&pTo->u, 0, sizeof(pTo->u));
113816    return SQLITE_NOMEM;
113817  }
113818  memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
113819  memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
113820  if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
113821    pFrom->u.vtab.needFree = 0;
113822  }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
113823    pFrom->u.btree.pIndex = 0;
113824  }
113825  return SQLITE_OK;
113826}
113827
113828/*
113829** Delete a WhereLoop object
113830*/
113831static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
113832  whereLoopClear(db, p);
113833  sqlite3DbFree(db, p);
113834}
113835
113836/*
113837** Free a WhereInfo structure
113838*/
113839static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
113840  if( ALWAYS(pWInfo) ){
113841    whereClauseClear(&pWInfo->sWC);
113842    while( pWInfo->pLoops ){
113843      WhereLoop *p = pWInfo->pLoops;
113844      pWInfo->pLoops = p->pNextLoop;
113845      whereLoopDelete(db, p);
113846    }
113847    sqlite3DbFree(db, pWInfo);
113848  }
113849}
113850
113851/*
113852** Return TRUE if both of the following are true:
113853**
113854**   (1)  X has the same or lower cost that Y
113855**   (2)  X is a proper subset of Y
113856**
113857** By "proper subset" we mean that X uses fewer WHERE clause terms
113858** than Y and that every WHERE clause term used by X is also used
113859** by Y.
113860**
113861** If X is a proper subset of Y then Y is a better choice and ought
113862** to have a lower cost.  This routine returns TRUE when that cost
113863** relationship is inverted and needs to be adjusted.
113864*/
113865static int whereLoopCheaperProperSubset(
113866  const WhereLoop *pX,       /* First WhereLoop to compare */
113867  const WhereLoop *pY        /* Compare against this WhereLoop */
113868){
113869  int i, j;
113870  if( pX->nLTerm >= pY->nLTerm ) return 0; /* X is not a subset of Y */
113871  if( pX->rRun >= pY->rRun ){
113872    if( pX->rRun > pY->rRun ) return 0;    /* X costs more than Y */
113873    if( pX->nOut > pY->nOut ) return 0;    /* X costs more than Y */
113874  }
113875  for(i=pX->nLTerm-1; i>=0; i--){
113876    for(j=pY->nLTerm-1; j>=0; j--){
113877      if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
113878    }
113879    if( j<0 ) return 0;  /* X not a subset of Y since term X[i] not used by Y */
113880  }
113881  return 1;  /* All conditions meet */
113882}
113883
113884/*
113885** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
113886** that:
113887**
113888**   (1) pTemplate costs less than any other WhereLoops that are a proper
113889**       subset of pTemplate
113890**
113891**   (2) pTemplate costs more than any other WhereLoops for which pTemplate
113892**       is a proper subset.
113893**
113894** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
113895** WHERE clause terms than Y and that every WHERE clause term used by X is
113896** also used by Y.
113897**
113898** This adjustment is omitted for SKIPSCAN loops.  In a SKIPSCAN loop, the
113899** WhereLoop.nLTerm field is not an accurate measure of the number of WHERE
113900** clause terms covered, since some of the first nLTerm entries in aLTerm[]
113901** will be NULL (because they are skipped).  That makes it more difficult
113902** to compare the loops.  We could add extra code to do the comparison, and
113903** perhaps we will someday.  But SKIPSCAN is sufficiently uncommon, and this
113904** adjustment is sufficient minor, that it is very difficult to construct
113905** a test case where the extra code would improve the query plan.  Better
113906** to avoid the added complexity and just omit cost adjustments to SKIPSCAN
113907** loops.
113908*/
113909static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
113910  if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
113911  if( (pTemplate->wsFlags & WHERE_SKIPSCAN)!=0 ) return;
113912  for(; p; p=p->pNextLoop){
113913    if( p->iTab!=pTemplate->iTab ) continue;
113914    if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
113915    if( (p->wsFlags & WHERE_SKIPSCAN)!=0 ) continue;
113916    if( whereLoopCheaperProperSubset(p, pTemplate) ){
113917      /* Adjust pTemplate cost downward so that it is cheaper than its
113918      ** subset p */
113919      pTemplate->rRun = p->rRun;
113920      pTemplate->nOut = p->nOut - 1;
113921    }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
113922      /* Adjust pTemplate cost upward so that it is costlier than p since
113923      ** pTemplate is a proper subset of p */
113924      pTemplate->rRun = p->rRun;
113925      pTemplate->nOut = p->nOut + 1;
113926    }
113927  }
113928}
113929
113930/*
113931** Search the list of WhereLoops in *ppPrev looking for one that can be
113932** supplanted by pTemplate.
113933**
113934** Return NULL if the WhereLoop list contains an entry that can supplant
113935** pTemplate, in other words if pTemplate does not belong on the list.
113936**
113937** If pX is a WhereLoop that pTemplate can supplant, then return the
113938** link that points to pX.
113939**
113940** If pTemplate cannot supplant any existing element of the list but needs
113941** to be added to the list, then return a pointer to the tail of the list.
113942*/
113943static WhereLoop **whereLoopFindLesser(
113944  WhereLoop **ppPrev,
113945  const WhereLoop *pTemplate
113946){
113947  WhereLoop *p;
113948  for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
113949    if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
113950      /* If either the iTab or iSortIdx values for two WhereLoop are different
113951      ** then those WhereLoops need to be considered separately.  Neither is
113952      ** a candidate to replace the other. */
113953      continue;
113954    }
113955    /* In the current implementation, the rSetup value is either zero
113956    ** or the cost of building an automatic index (NlogN) and the NlogN
113957    ** is the same for compatible WhereLoops. */
113958    assert( p->rSetup==0 || pTemplate->rSetup==0
113959                 || p->rSetup==pTemplate->rSetup );
113960
113961    /* whereLoopAddBtree() always generates and inserts the automatic index
113962    ** case first.  Hence compatible candidate WhereLoops never have a larger
113963    ** rSetup. Call this SETUP-INVARIANT */
113964    assert( p->rSetup>=pTemplate->rSetup );
113965
113966    /* If existing WhereLoop p is better than pTemplate, pTemplate can be
113967    ** discarded.  WhereLoop p is better if:
113968    **   (1)  p has no more dependencies than pTemplate, and
113969    **   (2)  p has an equal or lower cost than pTemplate
113970    */
113971    if( (p->prereq & pTemplate->prereq)==p->prereq    /* (1)  */
113972     && p->rSetup<=pTemplate->rSetup                  /* (2a) */
113973     && p->rRun<=pTemplate->rRun                      /* (2b) */
113974     && p->nOut<=pTemplate->nOut                      /* (2c) */
113975    ){
113976      return 0;  /* Discard pTemplate */
113977    }
113978
113979    /* If pTemplate is always better than p, then cause p to be overwritten
113980    ** with pTemplate.  pTemplate is better than p if:
113981    **   (1)  pTemplate has no more dependences than p, and
113982    **   (2)  pTemplate has an equal or lower cost than p.
113983    */
113984    if( (p->prereq & pTemplate->prereq)==pTemplate->prereq   /* (1)  */
113985     && p->rRun>=pTemplate->rRun                             /* (2a) */
113986     && p->nOut>=pTemplate->nOut                             /* (2b) */
113987    ){
113988      assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
113989      break;   /* Cause p to be overwritten by pTemplate */
113990    }
113991  }
113992  return ppPrev;
113993}
113994
113995/*
113996** Insert or replace a WhereLoop entry using the template supplied.
113997**
113998** An existing WhereLoop entry might be overwritten if the new template
113999** is better and has fewer dependencies.  Or the template will be ignored
114000** and no insert will occur if an existing WhereLoop is faster and has
114001** fewer dependencies than the template.  Otherwise a new WhereLoop is
114002** added based on the template.
114003**
114004** If pBuilder->pOrSet is not NULL then we care about only the
114005** prerequisites and rRun and nOut costs of the N best loops.  That
114006** information is gathered in the pBuilder->pOrSet object.  This special
114007** processing mode is used only for OR clause processing.
114008**
114009** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
114010** still might overwrite similar loops with the new template if the
114011** new template is better.  Loops may be overwritten if the following
114012** conditions are met:
114013**
114014**    (1)  They have the same iTab.
114015**    (2)  They have the same iSortIdx.
114016**    (3)  The template has same or fewer dependencies than the current loop
114017**    (4)  The template has the same or lower cost than the current loop
114018*/
114019static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
114020  WhereLoop **ppPrev, *p;
114021  WhereInfo *pWInfo = pBuilder->pWInfo;
114022  sqlite3 *db = pWInfo->pParse->db;
114023
114024  /* If pBuilder->pOrSet is defined, then only keep track of the costs
114025  ** and prereqs.
114026  */
114027  if( pBuilder->pOrSet!=0 ){
114028#if WHERETRACE_ENABLED
114029    u16 n = pBuilder->pOrSet->n;
114030    int x =
114031#endif
114032    whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
114033                                    pTemplate->nOut);
114034#if WHERETRACE_ENABLED /* 0x8 */
114035    if( sqlite3WhereTrace & 0x8 ){
114036      sqlite3DebugPrintf(x?"   or-%d:  ":"   or-X:  ", n);
114037      whereLoopPrint(pTemplate, pBuilder->pWC);
114038    }
114039#endif
114040    return SQLITE_OK;
114041  }
114042
114043  /* Look for an existing WhereLoop to replace with pTemplate
114044  */
114045  whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
114046  ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
114047
114048  if( ppPrev==0 ){
114049    /* There already exists a WhereLoop on the list that is better
114050    ** than pTemplate, so just ignore pTemplate */
114051#if WHERETRACE_ENABLED /* 0x8 */
114052    if( sqlite3WhereTrace & 0x8 ){
114053      sqlite3DebugPrintf("ins-noop: ");
114054      whereLoopPrint(pTemplate, pBuilder->pWC);
114055    }
114056#endif
114057    return SQLITE_OK;
114058  }else{
114059    p = *ppPrev;
114060  }
114061
114062  /* If we reach this point it means that either p[] should be overwritten
114063  ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
114064  ** WhereLoop and insert it.
114065  */
114066#if WHERETRACE_ENABLED /* 0x8 */
114067  if( sqlite3WhereTrace & 0x8 ){
114068    if( p!=0 ){
114069      sqlite3DebugPrintf("ins-del:  ");
114070      whereLoopPrint(p, pBuilder->pWC);
114071    }
114072    sqlite3DebugPrintf("ins-new:  ");
114073    whereLoopPrint(pTemplate, pBuilder->pWC);
114074  }
114075#endif
114076  if( p==0 ){
114077    /* Allocate a new WhereLoop to add to the end of the list */
114078    *ppPrev = p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
114079    if( p==0 ) return SQLITE_NOMEM;
114080    whereLoopInit(p);
114081    p->pNextLoop = 0;
114082  }else{
114083    /* We will be overwriting WhereLoop p[].  But before we do, first
114084    ** go through the rest of the list and delete any other entries besides
114085    ** p[] that are also supplated by pTemplate */
114086    WhereLoop **ppTail = &p->pNextLoop;
114087    WhereLoop *pToDel;
114088    while( *ppTail ){
114089      ppTail = whereLoopFindLesser(ppTail, pTemplate);
114090      if( NEVER(ppTail==0) ) break;
114091      pToDel = *ppTail;
114092      if( pToDel==0 ) break;
114093      *ppTail = pToDel->pNextLoop;
114094#if WHERETRACE_ENABLED /* 0x8 */
114095      if( sqlite3WhereTrace & 0x8 ){
114096        sqlite3DebugPrintf("ins-del: ");
114097        whereLoopPrint(pToDel, pBuilder->pWC);
114098      }
114099#endif
114100      whereLoopDelete(db, pToDel);
114101    }
114102  }
114103  whereLoopXfer(db, p, pTemplate);
114104  if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
114105    Index *pIndex = p->u.btree.pIndex;
114106    if( pIndex && pIndex->tnum==0 ){
114107      p->u.btree.pIndex = 0;
114108    }
114109  }
114110  return SQLITE_OK;
114111}
114112
114113/*
114114** Adjust the WhereLoop.nOut value downward to account for terms of the
114115** WHERE clause that reference the loop but which are not used by an
114116** index.
114117**
114118** In the current implementation, the first extra WHERE clause term reduces
114119** the number of output rows by a factor of 10 and each additional term
114120** reduces the number of output rows by sqrt(2).
114121*/
114122static void whereLoopOutputAdjust(WhereClause *pWC, WhereLoop *pLoop){
114123  WhereTerm *pTerm, *pX;
114124  Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
114125  int i, j;
114126
114127  if( !OptimizationEnabled(pWC->pWInfo->pParse->db, SQLITE_AdjustOutEst) ){
114128    return;
114129  }
114130  for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
114131    if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
114132    if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
114133    if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
114134    for(j=pLoop->nLTerm-1; j>=0; j--){
114135      pX = pLoop->aLTerm[j];
114136      if( pX==0 ) continue;
114137      if( pX==pTerm ) break;
114138      if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
114139    }
114140    if( j<0 ){
114141      pLoop->nOut += (pTerm->truthProb<=0 ? pTerm->truthProb : -1);
114142    }
114143  }
114144}
114145
114146/*
114147** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
114148** index pIndex. Try to match one more.
114149**
114150** When this function is called, pBuilder->pNew->nOut contains the
114151** number of rows expected to be visited by filtering using the nEq
114152** terms only. If it is modified, this value is restored before this
114153** function returns.
114154**
114155** If pProbe->tnum==0, that means pIndex is a fake index used for the
114156** INTEGER PRIMARY KEY.
114157*/
114158static int whereLoopAddBtreeIndex(
114159  WhereLoopBuilder *pBuilder,     /* The WhereLoop factory */
114160  struct SrcList_item *pSrc,      /* FROM clause term being analyzed */
114161  Index *pProbe,                  /* An index on pSrc */
114162  LogEst nInMul                   /* log(Number of iterations due to IN) */
114163){
114164  WhereInfo *pWInfo = pBuilder->pWInfo;  /* WHERE analyse context */
114165  Parse *pParse = pWInfo->pParse;        /* Parsing context */
114166  sqlite3 *db = pParse->db;       /* Database connection malloc context */
114167  WhereLoop *pNew;                /* Template WhereLoop under construction */
114168  WhereTerm *pTerm;               /* A WhereTerm under consideration */
114169  int opMask;                     /* Valid operators for constraints */
114170  WhereScan scan;                 /* Iterator for WHERE terms */
114171  Bitmask saved_prereq;           /* Original value of pNew->prereq */
114172  u16 saved_nLTerm;               /* Original value of pNew->nLTerm */
114173  u16 saved_nEq;                  /* Original value of pNew->u.btree.nEq */
114174  u16 saved_nSkip;                /* Original value of pNew->u.btree.nSkip */
114175  u32 saved_wsFlags;              /* Original value of pNew->wsFlags */
114176  LogEst saved_nOut;              /* Original value of pNew->nOut */
114177  int iCol;                       /* Index of the column in the table */
114178  int rc = SQLITE_OK;             /* Return code */
114179  LogEst rLogSize;                /* Logarithm of table size */
114180  WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
114181
114182  pNew = pBuilder->pNew;
114183  if( db->mallocFailed ) return SQLITE_NOMEM;
114184
114185  assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
114186  assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
114187  if( pNew->wsFlags & WHERE_BTM_LIMIT ){
114188    opMask = WO_LT|WO_LE;
114189  }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
114190    opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
114191  }else{
114192    opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
114193  }
114194  if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
114195
114196  assert( pNew->u.btree.nEq<=pProbe->nKeyCol );
114197  if( pNew->u.btree.nEq < pProbe->nKeyCol ){
114198    iCol = pProbe->aiColumn[pNew->u.btree.nEq];
114199  }else{
114200    iCol = -1;
114201  }
114202  pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
114203                        opMask, pProbe);
114204  saved_nEq = pNew->u.btree.nEq;
114205  saved_nSkip = pNew->u.btree.nSkip;
114206  saved_nLTerm = pNew->nLTerm;
114207  saved_wsFlags = pNew->wsFlags;
114208  saved_prereq = pNew->prereq;
114209  saved_nOut = pNew->nOut;
114210  pNew->rSetup = 0;
114211  rLogSize = estLog(pProbe->aiRowLogEst[0]);
114212
114213  /* Consider using a skip-scan if there are no WHERE clause constraints
114214  ** available for the left-most terms of the index, and if the average
114215  ** number of repeats in the left-most terms is at least 18.
114216  **
114217  ** The magic number 18 is selected on the basis that scanning 17 rows
114218  ** is almost always quicker than an index seek (even though if the index
114219  ** contains fewer than 2^17 rows we assume otherwise in other parts of
114220  ** the code). And, even if it is not, it should not be too much slower.
114221  ** On the other hand, the extra seeks could end up being significantly
114222  ** more expensive.  */
114223  assert( 42==sqlite3LogEst(18) );
114224  if( pTerm==0
114225   && saved_nEq==saved_nSkip
114226   && saved_nEq+1<pProbe->nKeyCol
114227   && pProbe->aiRowLogEst[saved_nEq+1]>=42  /* TUNING: Minimum for skip-scan */
114228   && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
114229  ){
114230    LogEst nIter;
114231    pNew->u.btree.nEq++;
114232    pNew->u.btree.nSkip++;
114233    pNew->aLTerm[pNew->nLTerm++] = 0;
114234    pNew->wsFlags |= WHERE_SKIPSCAN;
114235    nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
114236    pNew->nOut -= nIter;
114237    whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
114238    pNew->nOut = saved_nOut;
114239  }
114240  for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
114241    u16 eOp = pTerm->eOperator;   /* Shorthand for pTerm->eOperator */
114242    LogEst rCostIdx;
114243    LogEst nOutUnadjusted;        /* nOut before IN() and WHERE adjustments */
114244    int nIn = 0;
114245#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
114246    int nRecValid = pBuilder->nRecValid;
114247#endif
114248    if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
114249     && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
114250    ){
114251      continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
114252    }
114253    if( pTerm->prereqRight & pNew->maskSelf ) continue;
114254
114255    pNew->wsFlags = saved_wsFlags;
114256    pNew->u.btree.nEq = saved_nEq;
114257    pNew->nLTerm = saved_nLTerm;
114258    if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
114259    pNew->aLTerm[pNew->nLTerm++] = pTerm;
114260    pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
114261
114262    assert( nInMul==0
114263        || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
114264        || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
114265        || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
114266    );
114267
114268    if( eOp & WO_IN ){
114269      Expr *pExpr = pTerm->pExpr;
114270      pNew->wsFlags |= WHERE_COLUMN_IN;
114271      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
114272        /* "x IN (SELECT ...)":  TUNING: the SELECT returns 25 rows */
114273        nIn = 46;  assert( 46==sqlite3LogEst(25) );
114274      }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
114275        /* "x IN (value, value, ...)" */
114276        nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
114277      }
114278      assert( nIn>0 );  /* RHS always has 2 or more terms...  The parser
114279                        ** changes "x IN (?)" into "x=?". */
114280
114281    }else if( eOp & (WO_EQ) ){
114282      pNew->wsFlags |= WHERE_COLUMN_EQ;
114283      if( iCol<0 || (nInMul==0 && pNew->u.btree.nEq==pProbe->nKeyCol-1) ){
114284        if( iCol>=0 && pProbe->onError==OE_None ){
114285          pNew->wsFlags |= WHERE_UNQ_WANTED;
114286        }else{
114287          pNew->wsFlags |= WHERE_ONEROW;
114288        }
114289      }
114290    }else if( eOp & WO_ISNULL ){
114291      pNew->wsFlags |= WHERE_COLUMN_NULL;
114292    }else if( eOp & (WO_GT|WO_GE) ){
114293      testcase( eOp & WO_GT );
114294      testcase( eOp & WO_GE );
114295      pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
114296      pBtm = pTerm;
114297      pTop = 0;
114298    }else{
114299      assert( eOp & (WO_LT|WO_LE) );
114300      testcase( eOp & WO_LT );
114301      testcase( eOp & WO_LE );
114302      pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
114303      pTop = pTerm;
114304      pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
114305                     pNew->aLTerm[pNew->nLTerm-2] : 0;
114306    }
114307
114308    /* At this point pNew->nOut is set to the number of rows expected to
114309    ** be visited by the index scan before considering term pTerm, or the
114310    ** values of nIn and nInMul. In other words, assuming that all
114311    ** "x IN(...)" terms are replaced with "x = ?". This block updates
114312    ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul).  */
114313    assert( pNew->nOut==saved_nOut );
114314    if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
114315      /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
114316      ** data, using some other estimate.  */
114317      whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
114318    }else{
114319      int nEq = ++pNew->u.btree.nEq;
114320      assert( eOp & (WO_ISNULL|WO_EQ|WO_IN) );
114321
114322      assert( pNew->nOut==saved_nOut );
114323      if( pTerm->truthProb<=0 && iCol>=0 ){
114324        assert( (eOp & WO_IN) || nIn==0 );
114325        testcase( eOp & WO_IN );
114326        pNew->nOut += pTerm->truthProb;
114327        pNew->nOut -= nIn;
114328      }else{
114329#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
114330        tRowcnt nOut = 0;
114331        if( nInMul==0
114332         && pProbe->nSample
114333         && pNew->u.btree.nEq<=pProbe->nSampleCol
114334         && OptimizationEnabled(db, SQLITE_Stat3)
114335         && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
114336        ){
114337          Expr *pExpr = pTerm->pExpr;
114338          if( (eOp & (WO_EQ|WO_ISNULL))!=0 ){
114339            testcase( eOp & WO_EQ );
114340            testcase( eOp & WO_ISNULL );
114341            rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
114342          }else{
114343            rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
114344          }
114345          assert( rc!=SQLITE_OK || nOut>0 );
114346          if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
114347          if( rc!=SQLITE_OK ) break;          /* Jump out of the pTerm loop */
114348          if( nOut ){
114349            pNew->nOut = sqlite3LogEst(nOut);
114350            if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
114351            pNew->nOut -= nIn;
114352          }
114353        }
114354        if( nOut==0 )
114355#endif
114356        {
114357          pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
114358          if( eOp & WO_ISNULL ){
114359            /* TUNING: If there is no likelihood() value, assume that a
114360            ** "col IS NULL" expression matches twice as many rows
114361            ** as (col=?). */
114362            pNew->nOut += 10;
114363          }
114364        }
114365      }
114366    }
114367
114368    /* Set rCostIdx to the cost of visiting selected rows in index. Add
114369    ** it to pNew->rRun, which is currently set to the cost of the index
114370    ** seek only. Then, if this is a non-covering index, add the cost of
114371    ** visiting the rows in the main table.  */
114372    rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
114373    pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
114374    if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
114375      pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
114376    }
114377
114378    nOutUnadjusted = pNew->nOut;
114379    pNew->rRun += nInMul + nIn;
114380    pNew->nOut += nInMul + nIn;
114381    whereLoopOutputAdjust(pBuilder->pWC, pNew);
114382    rc = whereLoopInsert(pBuilder, pNew);
114383
114384    if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
114385      pNew->nOut = saved_nOut;
114386    }else{
114387      pNew->nOut = nOutUnadjusted;
114388    }
114389
114390    if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
114391     && pNew->u.btree.nEq<(pProbe->nKeyCol + (pProbe->zName!=0))
114392    ){
114393      whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
114394    }
114395    pNew->nOut = saved_nOut;
114396#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
114397    pBuilder->nRecValid = nRecValid;
114398#endif
114399  }
114400  pNew->prereq = saved_prereq;
114401  pNew->u.btree.nEq = saved_nEq;
114402  pNew->u.btree.nSkip = saved_nSkip;
114403  pNew->wsFlags = saved_wsFlags;
114404  pNew->nOut = saved_nOut;
114405  pNew->nLTerm = saved_nLTerm;
114406  return rc;
114407}
114408
114409/*
114410** Return True if it is possible that pIndex might be useful in
114411** implementing the ORDER BY clause in pBuilder.
114412**
114413** Return False if pBuilder does not contain an ORDER BY clause or
114414** if there is no way for pIndex to be useful in implementing that
114415** ORDER BY clause.
114416*/
114417static int indexMightHelpWithOrderBy(
114418  WhereLoopBuilder *pBuilder,
114419  Index *pIndex,
114420  int iCursor
114421){
114422  ExprList *pOB;
114423  int ii, jj;
114424
114425  if( pIndex->bUnordered ) return 0;
114426  if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
114427  for(ii=0; ii<pOB->nExpr; ii++){
114428    Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
114429    if( pExpr->op!=TK_COLUMN ) return 0;
114430    if( pExpr->iTable==iCursor ){
114431      for(jj=0; jj<pIndex->nKeyCol; jj++){
114432        if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
114433      }
114434    }
114435  }
114436  return 0;
114437}
114438
114439/*
114440** Return a bitmask where 1s indicate that the corresponding column of
114441** the table is used by an index.  Only the first 63 columns are considered.
114442*/
114443static Bitmask columnsInIndex(Index *pIdx){
114444  Bitmask m = 0;
114445  int j;
114446  for(j=pIdx->nColumn-1; j>=0; j--){
114447    int x = pIdx->aiColumn[j];
114448    if( x>=0 ){
114449      testcase( x==BMS-1 );
114450      testcase( x==BMS-2 );
114451      if( x<BMS-1 ) m |= MASKBIT(x);
114452    }
114453  }
114454  return m;
114455}
114456
114457/* Check to see if a partial index with pPartIndexWhere can be used
114458** in the current query.  Return true if it can be and false if not.
114459*/
114460static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
114461  int i;
114462  WhereTerm *pTerm;
114463  for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
114464    if( sqlite3ExprImpliesExpr(pTerm->pExpr, pWhere, iTab) ) return 1;
114465  }
114466  return 0;
114467}
114468
114469/*
114470** Add all WhereLoop objects for a single table of the join where the table
114471** is idenfied by pBuilder->pNew->iTab.  That table is guaranteed to be
114472** a b-tree table, not a virtual table.
114473**
114474** The costs (WhereLoop.rRun) of the b-tree loops added by this function
114475** are calculated as follows:
114476**
114477** For a full scan, assuming the table (or index) contains nRow rows:
114478**
114479**     cost = nRow * 3.0                    // full-table scan
114480**     cost = nRow * K                      // scan of covering index
114481**     cost = nRow * (K+3.0)                // scan of non-covering index
114482**
114483** where K is a value between 1.1 and 3.0 set based on the relative
114484** estimated average size of the index and table records.
114485**
114486** For an index scan, where nVisit is the number of index rows visited
114487** by the scan, and nSeek is the number of seek operations required on
114488** the index b-tree:
114489**
114490**     cost = nSeek * (log(nRow) + K * nVisit)          // covering index
114491**     cost = nSeek * (log(nRow) + (K+3.0) * nVisit)    // non-covering index
114492**
114493** Normally, nSeek is 1. nSeek values greater than 1 come about if the
114494** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
114495** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
114496*/
114497static int whereLoopAddBtree(
114498  WhereLoopBuilder *pBuilder, /* WHERE clause information */
114499  Bitmask mExtra              /* Extra prerequesites for using this table */
114500){
114501  WhereInfo *pWInfo;          /* WHERE analysis context */
114502  Index *pProbe;              /* An index we are evaluating */
114503  Index sPk;                  /* A fake index object for the primary key */
114504  LogEst aiRowEstPk[2];       /* The aiRowLogEst[] value for the sPk index */
114505  i16 aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
114506  SrcList *pTabList;          /* The FROM clause */
114507  struct SrcList_item *pSrc;  /* The FROM clause btree term to add */
114508  WhereLoop *pNew;            /* Template WhereLoop object */
114509  int rc = SQLITE_OK;         /* Return code */
114510  int iSortIdx = 1;           /* Index number */
114511  int b;                      /* A boolean value */
114512  LogEst rSize;               /* number of rows in the table */
114513  LogEst rLogSize;            /* Logarithm of the number of rows in the table */
114514  WhereClause *pWC;           /* The parsed WHERE clause */
114515  Table *pTab;                /* Table being queried */
114516
114517  pNew = pBuilder->pNew;
114518  pWInfo = pBuilder->pWInfo;
114519  pTabList = pWInfo->pTabList;
114520  pSrc = pTabList->a + pNew->iTab;
114521  pTab = pSrc->pTab;
114522  pWC = pBuilder->pWC;
114523  assert( !IsVirtual(pSrc->pTab) );
114524
114525  if( pSrc->pIndex ){
114526    /* An INDEXED BY clause specifies a particular index to use */
114527    pProbe = pSrc->pIndex;
114528  }else if( !HasRowid(pTab) ){
114529    pProbe = pTab->pIndex;
114530  }else{
114531    /* There is no INDEXED BY clause.  Create a fake Index object in local
114532    ** variable sPk to represent the rowid primary key index.  Make this
114533    ** fake index the first in a chain of Index objects with all of the real
114534    ** indices to follow */
114535    Index *pFirst;                  /* First of real indices on the table */
114536    memset(&sPk, 0, sizeof(Index));
114537    sPk.nKeyCol = 1;
114538    sPk.aiColumn = &aiColumnPk;
114539    sPk.aiRowLogEst = aiRowEstPk;
114540    sPk.onError = OE_Replace;
114541    sPk.pTable = pTab;
114542    sPk.szIdxRow = pTab->szTabRow;
114543    aiRowEstPk[0] = pTab->nRowLogEst;
114544    aiRowEstPk[1] = 0;
114545    pFirst = pSrc->pTab->pIndex;
114546    if( pSrc->notIndexed==0 ){
114547      /* The real indices of the table are only considered if the
114548      ** NOT INDEXED qualifier is omitted from the FROM clause */
114549      sPk.pNext = pFirst;
114550    }
114551    pProbe = &sPk;
114552  }
114553  rSize = pTab->nRowLogEst;
114554  rLogSize = estLog(rSize);
114555
114556#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
114557  /* Automatic indexes */
114558  if( !pBuilder->pOrSet
114559   && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
114560   && pSrc->pIndex==0
114561   && !pSrc->viaCoroutine
114562   && !pSrc->notIndexed
114563   && HasRowid(pTab)
114564   && !pSrc->isCorrelated
114565   && !pSrc->isRecursive
114566  ){
114567    /* Generate auto-index WhereLoops */
114568    WhereTerm *pTerm;
114569    WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
114570    for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
114571      if( pTerm->prereqRight & pNew->maskSelf ) continue;
114572      if( termCanDriveIndex(pTerm, pSrc, 0) ){
114573        pNew->u.btree.nEq = 1;
114574        pNew->u.btree.nSkip = 0;
114575        pNew->u.btree.pIndex = 0;
114576        pNew->nLTerm = 1;
114577        pNew->aLTerm[0] = pTerm;
114578        /* TUNING: One-time cost for computing the automatic index is
114579        ** approximately 7*N*log2(N) where N is the number of rows in
114580        ** the table being indexed. */
114581        pNew->rSetup = rLogSize + rSize + 28;  assert( 28==sqlite3LogEst(7) );
114582        /* TUNING: Each index lookup yields 20 rows in the table.  This
114583        ** is more than the usual guess of 10 rows, since we have no way
114584        ** of knowning how selective the index will ultimately be.  It would
114585        ** not be unreasonable to make this value much larger. */
114586        pNew->nOut = 43;  assert( 43==sqlite3LogEst(20) );
114587        pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
114588        pNew->wsFlags = WHERE_AUTO_INDEX;
114589        pNew->prereq = mExtra | pTerm->prereqRight;
114590        rc = whereLoopInsert(pBuilder, pNew);
114591      }
114592    }
114593  }
114594#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
114595
114596  /* Loop over all indices
114597  */
114598  for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
114599    if( pProbe->pPartIdxWhere!=0
114600     && !whereUsablePartialIndex(pNew->iTab, pWC, pProbe->pPartIdxWhere) ){
114601      continue;  /* Partial index inappropriate for this query */
114602    }
114603    rSize = pProbe->aiRowLogEst[0];
114604    pNew->u.btree.nEq = 0;
114605    pNew->u.btree.nSkip = 0;
114606    pNew->nLTerm = 0;
114607    pNew->iSortIdx = 0;
114608    pNew->rSetup = 0;
114609    pNew->prereq = mExtra;
114610    pNew->nOut = rSize;
114611    pNew->u.btree.pIndex = pProbe;
114612    b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
114613    /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
114614    assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
114615    if( pProbe->tnum<=0 ){
114616      /* Integer primary key index */
114617      pNew->wsFlags = WHERE_IPK;
114618
114619      /* Full table scan */
114620      pNew->iSortIdx = b ? iSortIdx : 0;
114621      /* TUNING: Cost of full table scan is (N*3.0). */
114622      pNew->rRun = rSize + 16;
114623      whereLoopOutputAdjust(pWC, pNew);
114624      rc = whereLoopInsert(pBuilder, pNew);
114625      pNew->nOut = rSize;
114626      if( rc ) break;
114627    }else{
114628      Bitmask m;
114629      if( pProbe->isCovering ){
114630        pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
114631        m = 0;
114632      }else{
114633        m = pSrc->colUsed & ~columnsInIndex(pProbe);
114634        pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
114635      }
114636
114637      /* Full scan via index */
114638      if( b
114639       || !HasRowid(pTab)
114640       || ( m==0
114641         && pProbe->bUnordered==0
114642         && (pProbe->szIdxRow<pTab->szTabRow)
114643         && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
114644         && sqlite3GlobalConfig.bUseCis
114645         && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
114646          )
114647      ){
114648        pNew->iSortIdx = b ? iSortIdx : 0;
114649
114650        /* The cost of visiting the index rows is N*K, where K is
114651        ** between 1.1 and 3.0, depending on the relative sizes of the
114652        ** index and table rows. If this is a non-covering index scan,
114653        ** also add the cost of visiting table rows (N*3.0).  */
114654        pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
114655        if( m!=0 ){
114656          pNew->rRun = sqlite3LogEstAdd(pNew->rRun, rSize+16);
114657        }
114658
114659        whereLoopOutputAdjust(pWC, pNew);
114660        rc = whereLoopInsert(pBuilder, pNew);
114661        pNew->nOut = rSize;
114662        if( rc ) break;
114663      }
114664    }
114665
114666    rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
114667#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
114668    sqlite3Stat4ProbeFree(pBuilder->pRec);
114669    pBuilder->nRecValid = 0;
114670    pBuilder->pRec = 0;
114671#endif
114672
114673    /* If there was an INDEXED BY clause, then only that one index is
114674    ** considered. */
114675    if( pSrc->pIndex ) break;
114676  }
114677  return rc;
114678}
114679
114680#ifndef SQLITE_OMIT_VIRTUALTABLE
114681/*
114682** Add all WhereLoop objects for a table of the join identified by
114683** pBuilder->pNew->iTab.  That table is guaranteed to be a virtual table.
114684*/
114685static int whereLoopAddVirtual(
114686  WhereLoopBuilder *pBuilder,  /* WHERE clause information */
114687  Bitmask mExtra
114688){
114689  WhereInfo *pWInfo;           /* WHERE analysis context */
114690  Parse *pParse;               /* The parsing context */
114691  WhereClause *pWC;            /* The WHERE clause */
114692  struct SrcList_item *pSrc;   /* The FROM clause term to search */
114693  Table *pTab;
114694  sqlite3 *db;
114695  sqlite3_index_info *pIdxInfo;
114696  struct sqlite3_index_constraint *pIdxCons;
114697  struct sqlite3_index_constraint_usage *pUsage;
114698  WhereTerm *pTerm;
114699  int i, j;
114700  int iTerm, mxTerm;
114701  int nConstraint;
114702  int seenIn = 0;              /* True if an IN operator is seen */
114703  int seenVar = 0;             /* True if a non-constant constraint is seen */
114704  int iPhase;                  /* 0: const w/o IN, 1: const, 2: no IN,  2: IN */
114705  WhereLoop *pNew;
114706  int rc = SQLITE_OK;
114707
114708  pWInfo = pBuilder->pWInfo;
114709  pParse = pWInfo->pParse;
114710  db = pParse->db;
114711  pWC = pBuilder->pWC;
114712  pNew = pBuilder->pNew;
114713  pSrc = &pWInfo->pTabList->a[pNew->iTab];
114714  pTab = pSrc->pTab;
114715  assert( IsVirtual(pTab) );
114716  pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
114717  if( pIdxInfo==0 ) return SQLITE_NOMEM;
114718  pNew->prereq = 0;
114719  pNew->rSetup = 0;
114720  pNew->wsFlags = WHERE_VIRTUALTABLE;
114721  pNew->nLTerm = 0;
114722  pNew->u.vtab.needFree = 0;
114723  pUsage = pIdxInfo->aConstraintUsage;
114724  nConstraint = pIdxInfo->nConstraint;
114725  if( whereLoopResize(db, pNew, nConstraint) ){
114726    sqlite3DbFree(db, pIdxInfo);
114727    return SQLITE_NOMEM;
114728  }
114729
114730  for(iPhase=0; iPhase<=3; iPhase++){
114731    if( !seenIn && (iPhase&1)!=0 ){
114732      iPhase++;
114733      if( iPhase>3 ) break;
114734    }
114735    if( !seenVar && iPhase>1 ) break;
114736    pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
114737    for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
114738      j = pIdxCons->iTermOffset;
114739      pTerm = &pWC->a[j];
114740      switch( iPhase ){
114741        case 0:    /* Constants without IN operator */
114742          pIdxCons->usable = 0;
114743          if( (pTerm->eOperator & WO_IN)!=0 ){
114744            seenIn = 1;
114745          }
114746          if( pTerm->prereqRight!=0 ){
114747            seenVar = 1;
114748          }else if( (pTerm->eOperator & WO_IN)==0 ){
114749            pIdxCons->usable = 1;
114750          }
114751          break;
114752        case 1:    /* Constants with IN operators */
114753          assert( seenIn );
114754          pIdxCons->usable = (pTerm->prereqRight==0);
114755          break;
114756        case 2:    /* Variables without IN */
114757          assert( seenVar );
114758          pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
114759          break;
114760        default:   /* Variables with IN */
114761          assert( seenVar && seenIn );
114762          pIdxCons->usable = 1;
114763          break;
114764      }
114765    }
114766    memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
114767    if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
114768    pIdxInfo->idxStr = 0;
114769    pIdxInfo->idxNum = 0;
114770    pIdxInfo->needToFreeIdxStr = 0;
114771    pIdxInfo->orderByConsumed = 0;
114772    pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
114773    pIdxInfo->estimatedRows = 25;
114774    rc = vtabBestIndex(pParse, pTab, pIdxInfo);
114775    if( rc ) goto whereLoopAddVtab_exit;
114776    pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
114777    pNew->prereq = mExtra;
114778    mxTerm = -1;
114779    assert( pNew->nLSlot>=nConstraint );
114780    for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
114781    pNew->u.vtab.omitMask = 0;
114782    for(i=0; i<nConstraint; i++, pIdxCons++){
114783      if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
114784        j = pIdxCons->iTermOffset;
114785        if( iTerm>=nConstraint
114786         || j<0
114787         || j>=pWC->nTerm
114788         || pNew->aLTerm[iTerm]!=0
114789        ){
114790          rc = SQLITE_ERROR;
114791          sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
114792          goto whereLoopAddVtab_exit;
114793        }
114794        testcase( iTerm==nConstraint-1 );
114795        testcase( j==0 );
114796        testcase( j==pWC->nTerm-1 );
114797        pTerm = &pWC->a[j];
114798        pNew->prereq |= pTerm->prereqRight;
114799        assert( iTerm<pNew->nLSlot );
114800        pNew->aLTerm[iTerm] = pTerm;
114801        if( iTerm>mxTerm ) mxTerm = iTerm;
114802        testcase( iTerm==15 );
114803        testcase( iTerm==16 );
114804        if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
114805        if( (pTerm->eOperator & WO_IN)!=0 ){
114806          if( pUsage[i].omit==0 ){
114807            /* Do not attempt to use an IN constraint if the virtual table
114808            ** says that the equivalent EQ constraint cannot be safely omitted.
114809            ** If we do attempt to use such a constraint, some rows might be
114810            ** repeated in the output. */
114811            break;
114812          }
114813          /* A virtual table that is constrained by an IN clause may not
114814          ** consume the ORDER BY clause because (1) the order of IN terms
114815          ** is not necessarily related to the order of output terms and
114816          ** (2) Multiple outputs from a single IN value will not merge
114817          ** together.  */
114818          pIdxInfo->orderByConsumed = 0;
114819        }
114820      }
114821    }
114822    if( i>=nConstraint ){
114823      pNew->nLTerm = mxTerm+1;
114824      assert( pNew->nLTerm<=pNew->nLSlot );
114825      pNew->u.vtab.idxNum = pIdxInfo->idxNum;
114826      pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
114827      pIdxInfo->needToFreeIdxStr = 0;
114828      pNew->u.vtab.idxStr = pIdxInfo->idxStr;
114829      pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
114830                                      pIdxInfo->nOrderBy : 0);
114831      pNew->rSetup = 0;
114832      pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
114833      pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
114834      whereLoopInsert(pBuilder, pNew);
114835      if( pNew->u.vtab.needFree ){
114836        sqlite3_free(pNew->u.vtab.idxStr);
114837        pNew->u.vtab.needFree = 0;
114838      }
114839    }
114840  }
114841
114842whereLoopAddVtab_exit:
114843  if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
114844  sqlite3DbFree(db, pIdxInfo);
114845  return rc;
114846}
114847#endif /* SQLITE_OMIT_VIRTUALTABLE */
114848
114849/*
114850** Add WhereLoop entries to handle OR terms.  This works for either
114851** btrees or virtual tables.
114852*/
114853static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
114854  WhereInfo *pWInfo = pBuilder->pWInfo;
114855  WhereClause *pWC;
114856  WhereLoop *pNew;
114857  WhereTerm *pTerm, *pWCEnd;
114858  int rc = SQLITE_OK;
114859  int iCur;
114860  WhereClause tempWC;
114861  WhereLoopBuilder sSubBuild;
114862  WhereOrSet sSum, sCur;
114863  struct SrcList_item *pItem;
114864
114865  pWC = pBuilder->pWC;
114866  if( pWInfo->wctrlFlags & WHERE_AND_ONLY ) return SQLITE_OK;
114867  pWCEnd = pWC->a + pWC->nTerm;
114868  pNew = pBuilder->pNew;
114869  memset(&sSum, 0, sizeof(sSum));
114870  pItem = pWInfo->pTabList->a + pNew->iTab;
114871  iCur = pItem->iCursor;
114872
114873  for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
114874    if( (pTerm->eOperator & WO_OR)!=0
114875     && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
114876    ){
114877      WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
114878      WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
114879      WhereTerm *pOrTerm;
114880      int once = 1;
114881      int i, j;
114882
114883      sSubBuild = *pBuilder;
114884      sSubBuild.pOrderBy = 0;
114885      sSubBuild.pOrSet = &sCur;
114886
114887      for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
114888        if( (pOrTerm->eOperator & WO_AND)!=0 ){
114889          sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
114890        }else if( pOrTerm->leftCursor==iCur ){
114891          tempWC.pWInfo = pWC->pWInfo;
114892          tempWC.pOuter = pWC;
114893          tempWC.op = TK_AND;
114894          tempWC.nTerm = 1;
114895          tempWC.a = pOrTerm;
114896          sSubBuild.pWC = &tempWC;
114897        }else{
114898          continue;
114899        }
114900        sCur.n = 0;
114901#ifndef SQLITE_OMIT_VIRTUALTABLE
114902        if( IsVirtual(pItem->pTab) ){
114903          rc = whereLoopAddVirtual(&sSubBuild, mExtra);
114904        }else
114905#endif
114906        {
114907          rc = whereLoopAddBtree(&sSubBuild, mExtra);
114908        }
114909        assert( rc==SQLITE_OK || sCur.n==0 );
114910        if( sCur.n==0 ){
114911          sSum.n = 0;
114912          break;
114913        }else if( once ){
114914          whereOrMove(&sSum, &sCur);
114915          once = 0;
114916        }else{
114917          WhereOrSet sPrev;
114918          whereOrMove(&sPrev, &sSum);
114919          sSum.n = 0;
114920          for(i=0; i<sPrev.n; i++){
114921            for(j=0; j<sCur.n; j++){
114922              whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
114923                            sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
114924                            sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
114925            }
114926          }
114927        }
114928      }
114929      pNew->nLTerm = 1;
114930      pNew->aLTerm[0] = pTerm;
114931      pNew->wsFlags = WHERE_MULTI_OR;
114932      pNew->rSetup = 0;
114933      pNew->iSortIdx = 0;
114934      memset(&pNew->u, 0, sizeof(pNew->u));
114935      for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
114936        /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
114937        ** of all sub-scans required by the OR-scan. However, due to rounding
114938        ** errors, it may be that the cost of the OR-scan is equal to its
114939        ** most expensive sub-scan. Add the smallest possible penalty
114940        ** (equivalent to multiplying the cost by 1.07) to ensure that
114941        ** this does not happen. Otherwise, for WHERE clauses such as the
114942        ** following where there is an index on "y":
114943        **
114944        **     WHERE likelihood(x=?, 0.99) OR y=?
114945        **
114946        ** the planner may elect to "OR" together a full-table scan and an
114947        ** index lookup. And other similarly odd results.  */
114948        pNew->rRun = sSum.a[i].rRun + 1;
114949        pNew->nOut = sSum.a[i].nOut;
114950        pNew->prereq = sSum.a[i].prereq;
114951        rc = whereLoopInsert(pBuilder, pNew);
114952      }
114953    }
114954  }
114955  return rc;
114956}
114957
114958/*
114959** Add all WhereLoop objects for all tables
114960*/
114961static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
114962  WhereInfo *pWInfo = pBuilder->pWInfo;
114963  Bitmask mExtra = 0;
114964  Bitmask mPrior = 0;
114965  int iTab;
114966  SrcList *pTabList = pWInfo->pTabList;
114967  struct SrcList_item *pItem;
114968  sqlite3 *db = pWInfo->pParse->db;
114969  int nTabList = pWInfo->nLevel;
114970  int rc = SQLITE_OK;
114971  u8 priorJoinType = 0;
114972  WhereLoop *pNew;
114973
114974  /* Loop over the tables in the join, from left to right */
114975  pNew = pBuilder->pNew;
114976  whereLoopInit(pNew);
114977  for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
114978    pNew->iTab = iTab;
114979    pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
114980    if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
114981      mExtra = mPrior;
114982    }
114983    priorJoinType = pItem->jointype;
114984    if( IsVirtual(pItem->pTab) ){
114985      rc = whereLoopAddVirtual(pBuilder, mExtra);
114986    }else{
114987      rc = whereLoopAddBtree(pBuilder, mExtra);
114988    }
114989    if( rc==SQLITE_OK ){
114990      rc = whereLoopAddOr(pBuilder, mExtra);
114991    }
114992    mPrior |= pNew->maskSelf;
114993    if( rc || db->mallocFailed ) break;
114994  }
114995  whereLoopClear(db, pNew);
114996  return rc;
114997}
114998
114999/*
115000** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
115001** parameters) to see if it outputs rows in the requested ORDER BY
115002** (or GROUP BY) without requiring a separate sort operation.  Return N:
115003**
115004**   N>0:   N terms of the ORDER BY clause are satisfied
115005**   N==0:  No terms of the ORDER BY clause are satisfied
115006**   N<0:   Unknown yet how many terms of ORDER BY might be satisfied.
115007**
115008** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
115009** strict.  With GROUP BY and DISTINCT the only requirement is that
115010** equivalent rows appear immediately adjacent to one another.  GROUP BY
115011** and DISTINCT do not require rows to appear in any particular order as long
115012** as equivelent rows are grouped together.  Thus for GROUP BY and DISTINCT
115013** the pOrderBy terms can be matched in any order.  With ORDER BY, the
115014** pOrderBy terms must be matched in strict left-to-right order.
115015*/
115016static i8 wherePathSatisfiesOrderBy(
115017  WhereInfo *pWInfo,    /* The WHERE clause */
115018  ExprList *pOrderBy,   /* ORDER BY or GROUP BY or DISTINCT clause to check */
115019  WherePath *pPath,     /* The WherePath to check */
115020  u16 wctrlFlags,       /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
115021  u16 nLoop,            /* Number of entries in pPath->aLoop[] */
115022  WhereLoop *pLast,     /* Add this WhereLoop to the end of pPath->aLoop[] */
115023  Bitmask *pRevMask     /* OUT: Mask of WhereLoops to run in reverse order */
115024){
115025  u8 revSet;            /* True if rev is known */
115026  u8 rev;               /* Composite sort order */
115027  u8 revIdx;            /* Index sort order */
115028  u8 isOrderDistinct;   /* All prior WhereLoops are order-distinct */
115029  u8 distinctColumns;   /* True if the loop has UNIQUE NOT NULL columns */
115030  u8 isMatch;           /* iColumn matches a term of the ORDER BY clause */
115031  u16 nKeyCol;          /* Number of key columns in pIndex */
115032  u16 nColumn;          /* Total number of ordered columns in the index */
115033  u16 nOrderBy;         /* Number terms in the ORDER BY clause */
115034  int iLoop;            /* Index of WhereLoop in pPath being processed */
115035  int i, j;             /* Loop counters */
115036  int iCur;             /* Cursor number for current WhereLoop */
115037  int iColumn;          /* A column number within table iCur */
115038  WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
115039  WhereTerm *pTerm;     /* A single term of the WHERE clause */
115040  Expr *pOBExpr;        /* An expression from the ORDER BY clause */
115041  CollSeq *pColl;       /* COLLATE function from an ORDER BY clause term */
115042  Index *pIndex;        /* The index associated with pLoop */
115043  sqlite3 *db = pWInfo->pParse->db;  /* Database connection */
115044  Bitmask obSat = 0;    /* Mask of ORDER BY terms satisfied so far */
115045  Bitmask obDone;       /* Mask of all ORDER BY terms */
115046  Bitmask orderDistinctMask;  /* Mask of all well-ordered loops */
115047  Bitmask ready;              /* Mask of inner loops */
115048
115049  /*
115050  ** We say the WhereLoop is "one-row" if it generates no more than one
115051  ** row of output.  A WhereLoop is one-row if all of the following are true:
115052  **  (a) All index columns match with WHERE_COLUMN_EQ.
115053  **  (b) The index is unique
115054  ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
115055  ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
115056  **
115057  ** We say the WhereLoop is "order-distinct" if the set of columns from
115058  ** that WhereLoop that are in the ORDER BY clause are different for every
115059  ** row of the WhereLoop.  Every one-row WhereLoop is automatically
115060  ** order-distinct.   A WhereLoop that has no columns in the ORDER BY clause
115061  ** is not order-distinct. To be order-distinct is not quite the same as being
115062  ** UNIQUE since a UNIQUE column or index can have multiple rows that
115063  ** are NULL and NULL values are equivalent for the purpose of order-distinct.
115064  ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
115065  **
115066  ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
115067  ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
115068  ** automatically order-distinct.
115069  */
115070
115071  assert( pOrderBy!=0 );
115072  if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
115073
115074  nOrderBy = pOrderBy->nExpr;
115075  testcase( nOrderBy==BMS-1 );
115076  if( nOrderBy>BMS-1 ) return 0;  /* Cannot optimize overly large ORDER BYs */
115077  isOrderDistinct = 1;
115078  obDone = MASKBIT(nOrderBy)-1;
115079  orderDistinctMask = 0;
115080  ready = 0;
115081  for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
115082    if( iLoop>0 ) ready |= pLoop->maskSelf;
115083    pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
115084    if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
115085      if( pLoop->u.vtab.isOrdered ) obSat = obDone;
115086      break;
115087    }
115088    iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
115089
115090    /* Mark off any ORDER BY term X that is a column in the table of
115091    ** the current loop for which there is term in the WHERE
115092    ** clause of the form X IS NULL or X=? that reference only outer
115093    ** loops.
115094    */
115095    for(i=0; i<nOrderBy; i++){
115096      if( MASKBIT(i) & obSat ) continue;
115097      pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
115098      if( pOBExpr->op!=TK_COLUMN ) continue;
115099      if( pOBExpr->iTable!=iCur ) continue;
115100      pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
115101                       ~ready, WO_EQ|WO_ISNULL, 0);
115102      if( pTerm==0 ) continue;
115103      if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
115104        const char *z1, *z2;
115105        pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
115106        if( !pColl ) pColl = db->pDfltColl;
115107        z1 = pColl->zName;
115108        pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
115109        if( !pColl ) pColl = db->pDfltColl;
115110        z2 = pColl->zName;
115111        if( sqlite3StrICmp(z1, z2)!=0 ) continue;
115112      }
115113      obSat |= MASKBIT(i);
115114    }
115115
115116    if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
115117      if( pLoop->wsFlags & WHERE_IPK ){
115118        pIndex = 0;
115119        nKeyCol = 0;
115120        nColumn = 1;
115121      }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
115122        return 0;
115123      }else{
115124        nKeyCol = pIndex->nKeyCol;
115125        nColumn = pIndex->nColumn;
115126        assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
115127        assert( pIndex->aiColumn[nColumn-1]==(-1) || !HasRowid(pIndex->pTable));
115128        isOrderDistinct = pIndex->onError!=OE_None;
115129      }
115130
115131      /* Loop through all columns of the index and deal with the ones
115132      ** that are not constrained by == or IN.
115133      */
115134      rev = revSet = 0;
115135      distinctColumns = 0;
115136      for(j=0; j<nColumn; j++){
115137        u8 bOnce;   /* True to run the ORDER BY search loop */
115138
115139        /* Skip over == and IS NULL terms */
115140        if( j<pLoop->u.btree.nEq
115141         && pLoop->u.btree.nSkip==0
115142         && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
115143        ){
115144          if( i & WO_ISNULL ){
115145            testcase( isOrderDistinct );
115146            isOrderDistinct = 0;
115147          }
115148          continue;
115149        }
115150
115151        /* Get the column number in the table (iColumn) and sort order
115152        ** (revIdx) for the j-th column of the index.
115153        */
115154        if( pIndex ){
115155          iColumn = pIndex->aiColumn[j];
115156          revIdx = pIndex->aSortOrder[j];
115157          if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
115158        }else{
115159          iColumn = -1;
115160          revIdx = 0;
115161        }
115162
115163        /* An unconstrained column that might be NULL means that this
115164        ** WhereLoop is not well-ordered
115165        */
115166        if( isOrderDistinct
115167         && iColumn>=0
115168         && j>=pLoop->u.btree.nEq
115169         && pIndex->pTable->aCol[iColumn].notNull==0
115170        ){
115171          isOrderDistinct = 0;
115172        }
115173
115174        /* Find the ORDER BY term that corresponds to the j-th column
115175        ** of the index and mark that ORDER BY term off
115176        */
115177        bOnce = 1;
115178        isMatch = 0;
115179        for(i=0; bOnce && i<nOrderBy; i++){
115180          if( MASKBIT(i) & obSat ) continue;
115181          pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
115182          testcase( wctrlFlags & WHERE_GROUPBY );
115183          testcase( wctrlFlags & WHERE_DISTINCTBY );
115184          if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
115185          if( pOBExpr->op!=TK_COLUMN ) continue;
115186          if( pOBExpr->iTable!=iCur ) continue;
115187          if( pOBExpr->iColumn!=iColumn ) continue;
115188          if( iColumn>=0 ){
115189            pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
115190            if( !pColl ) pColl = db->pDfltColl;
115191            if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
115192          }
115193          isMatch = 1;
115194          break;
115195        }
115196        if( isMatch && (pWInfo->wctrlFlags & WHERE_GROUPBY)==0 ){
115197          /* Make sure the sort order is compatible in an ORDER BY clause.
115198          ** Sort order is irrelevant for a GROUP BY clause. */
115199          if( revSet ){
115200            if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
115201          }else{
115202            rev = revIdx ^ pOrderBy->a[i].sortOrder;
115203            if( rev ) *pRevMask |= MASKBIT(iLoop);
115204            revSet = 1;
115205          }
115206        }
115207        if( isMatch ){
115208          if( iColumn<0 ){
115209            testcase( distinctColumns==0 );
115210            distinctColumns = 1;
115211          }
115212          obSat |= MASKBIT(i);
115213        }else{
115214          /* No match found */
115215          if( j==0 || j<nKeyCol ){
115216            testcase( isOrderDistinct!=0 );
115217            isOrderDistinct = 0;
115218          }
115219          break;
115220        }
115221      } /* end Loop over all index columns */
115222      if( distinctColumns ){
115223        testcase( isOrderDistinct==0 );
115224        isOrderDistinct = 1;
115225      }
115226    } /* end-if not one-row */
115227
115228    /* Mark off any other ORDER BY terms that reference pLoop */
115229    if( isOrderDistinct ){
115230      orderDistinctMask |= pLoop->maskSelf;
115231      for(i=0; i<nOrderBy; i++){
115232        Expr *p;
115233        Bitmask mTerm;
115234        if( MASKBIT(i) & obSat ) continue;
115235        p = pOrderBy->a[i].pExpr;
115236        mTerm = exprTableUsage(&pWInfo->sMaskSet,p);
115237        if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
115238        if( (mTerm&~orderDistinctMask)==0 ){
115239          obSat |= MASKBIT(i);
115240        }
115241      }
115242    }
115243  } /* End the loop over all WhereLoops from outer-most down to inner-most */
115244  if( obSat==obDone ) return (i8)nOrderBy;
115245  if( !isOrderDistinct ){
115246    for(i=nOrderBy-1; i>0; i--){
115247      Bitmask m = MASKBIT(i) - 1;
115248      if( (obSat&m)==m ) return i;
115249    }
115250    return 0;
115251  }
115252  return -1;
115253}
115254
115255
115256/*
115257** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
115258** the planner assumes that the specified pOrderBy list is actually a GROUP
115259** BY clause - and so any order that groups rows as required satisfies the
115260** request.
115261**
115262** Normally, in this case it is not possible for the caller to determine
115263** whether or not the rows are really being delivered in sorted order, or
115264** just in some other order that provides the required grouping. However,
115265** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
115266** this function may be called on the returned WhereInfo object. It returns
115267** true if the rows really will be sorted in the specified order, or false
115268** otherwise.
115269**
115270** For example, assuming:
115271**
115272**   CREATE INDEX i1 ON t1(x, Y);
115273**
115274** then
115275**
115276**   SELECT * FROM t1 GROUP BY x,y ORDER BY x,y;   -- IsSorted()==1
115277**   SELECT * FROM t1 GROUP BY y,x ORDER BY y,x;   -- IsSorted()==0
115278*/
115279SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
115280  assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
115281  assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
115282  return pWInfo->sorted;
115283}
115284
115285#ifdef WHERETRACE_ENABLED
115286/* For debugging use only: */
115287static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
115288  static char zName[65];
115289  int i;
115290  for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
115291  if( pLast ) zName[i++] = pLast->cId;
115292  zName[i] = 0;
115293  return zName;
115294}
115295#endif
115296
115297/*
115298** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
115299** attempts to find the lowest cost path that visits each WhereLoop
115300** once.  This path is then loaded into the pWInfo->a[].pWLoop fields.
115301**
115302** Assume that the total number of output rows that will need to be sorted
115303** will be nRowEst (in the 10*log2 representation).  Or, ignore sorting
115304** costs if nRowEst==0.
115305**
115306** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
115307** error occurs.
115308*/
115309static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
115310  int mxChoice;             /* Maximum number of simultaneous paths tracked */
115311  int nLoop;                /* Number of terms in the join */
115312  Parse *pParse;            /* Parsing context */
115313  sqlite3 *db;              /* The database connection */
115314  int iLoop;                /* Loop counter over the terms of the join */
115315  int ii, jj;               /* Loop counters */
115316  int mxI = 0;              /* Index of next entry to replace */
115317  int nOrderBy;             /* Number of ORDER BY clause terms */
115318  LogEst rCost;             /* Cost of a path */
115319  LogEst nOut;              /* Number of outputs */
115320  LogEst mxCost = 0;        /* Maximum cost of a set of paths */
115321  LogEst mxOut = 0;         /* Maximum nOut value on the set of paths */
115322  int nTo, nFrom;           /* Number of valid entries in aTo[] and aFrom[] */
115323  WherePath *aFrom;         /* All nFrom paths at the previous level */
115324  WherePath *aTo;           /* The nTo best paths at the current level */
115325  WherePath *pFrom;         /* An element of aFrom[] that we are working on */
115326  WherePath *pTo;           /* An element of aTo[] that we are working on */
115327  WhereLoop *pWLoop;        /* One of the WhereLoop objects */
115328  WhereLoop **pX;           /* Used to divy up the pSpace memory */
115329  char *pSpace;             /* Temporary memory used by this routine */
115330
115331  pParse = pWInfo->pParse;
115332  db = pParse->db;
115333  nLoop = pWInfo->nLevel;
115334  /* TUNING: For simple queries, only the best path is tracked.
115335  ** For 2-way joins, the 5 best paths are followed.
115336  ** For joins of 3 or more tables, track the 10 best paths */
115337  mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
115338  assert( nLoop<=pWInfo->pTabList->nSrc );
115339  WHERETRACE(0x002, ("---- begin solver\n"));
115340
115341  /* Allocate and initialize space for aTo and aFrom */
115342  ii = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
115343  pSpace = sqlite3DbMallocRaw(db, ii);
115344  if( pSpace==0 ) return SQLITE_NOMEM;
115345  aTo = (WherePath*)pSpace;
115346  aFrom = aTo+mxChoice;
115347  memset(aFrom, 0, sizeof(aFrom[0]));
115348  pX = (WhereLoop**)(aFrom+mxChoice);
115349  for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
115350    pFrom->aLoop = pX;
115351  }
115352
115353  /* Seed the search with a single WherePath containing zero WhereLoops.
115354  **
115355  ** TUNING: Do not let the number of iterations go above 25.  If the cost
115356  ** of computing an automatic index is not paid back within the first 25
115357  ** rows, then do not use the automatic index. */
115358  aFrom[0].nRow = MIN(pParse->nQueryLoop, 46);  assert( 46==sqlite3LogEst(25) );
115359  nFrom = 1;
115360
115361  /* Precompute the cost of sorting the final result set, if the caller
115362  ** to sqlite3WhereBegin() was concerned about sorting */
115363  if( pWInfo->pOrderBy==0 || nRowEst==0 ){
115364    aFrom[0].isOrdered = 0;
115365    nOrderBy = 0;
115366  }else{
115367    aFrom[0].isOrdered = nLoop>0 ? -1 : 1;
115368    nOrderBy = pWInfo->pOrderBy->nExpr;
115369  }
115370
115371  /* Compute successively longer WherePaths using the previous generation
115372  ** of WherePaths as the basis for the next.  Keep track of the mxChoice
115373  ** best paths at each generation */
115374  for(iLoop=0; iLoop<nLoop; iLoop++){
115375    nTo = 0;
115376    for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
115377      for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
115378        Bitmask maskNew;
115379        Bitmask revMask = 0;
115380        i8 isOrdered = pFrom->isOrdered;
115381        if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
115382        if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
115383        /* At this point, pWLoop is a candidate to be the next loop.
115384        ** Compute its cost */
115385        rCost = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
115386        rCost = sqlite3LogEstAdd(rCost, pFrom->rCost);
115387        nOut = pFrom->nRow + pWLoop->nOut;
115388        maskNew = pFrom->maskLoop | pWLoop->maskSelf;
115389        if( isOrdered<0 ){
115390          isOrdered = wherePathSatisfiesOrderBy(pWInfo,
115391                       pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
115392                       iLoop, pWLoop, &revMask);
115393          if( isOrdered>=0 && isOrdered<nOrderBy ){
115394            /* TUNING: Estimated cost of a full external sort, where N is
115395            ** the number of rows to sort is:
115396            **
115397            **   cost = (3.0 * N * log(N)).
115398            **
115399            ** Or, if the order-by clause has X terms but only the last Y
115400            ** terms are out of order, then block-sorting will reduce the
115401            ** sorting cost to:
115402            **
115403            **   cost = (3.0 * N * log(N)) * (Y/X)
115404            **
115405            ** The (Y/X) term is implemented using stack variable rScale
115406            ** below.  */
115407            LogEst rScale, rSortCost;
115408            assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
115409            rScale = sqlite3LogEst((nOrderBy-isOrdered)*100/nOrderBy) - 66;
115410            rSortCost = nRowEst + estLog(nRowEst) + rScale + 16;
115411
115412            /* TUNING: The cost of implementing DISTINCT using a B-TREE is
115413            ** similar but with a larger constant of proportionality.
115414            ** Multiply by an additional factor of 3.0.  */
115415            if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
115416              rSortCost += 16;
115417            }
115418            WHERETRACE(0x002,
115419               ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
115420                rSortCost, (nOrderBy-isOrdered), nOrderBy, rCost,
115421                sqlite3LogEstAdd(rCost,rSortCost)));
115422            rCost = sqlite3LogEstAdd(rCost, rSortCost);
115423          }
115424        }else{
115425          revMask = pFrom->revLoop;
115426        }
115427        /* Check to see if pWLoop should be added to the mxChoice best so far */
115428        for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
115429          if( pTo->maskLoop==maskNew
115430           && ((pTo->isOrdered^isOrdered)&80)==0
115431           && ((pTo->rCost<=rCost && pTo->nRow<=nOut) ||
115432                (pTo->rCost>=rCost && pTo->nRow>=nOut))
115433          ){
115434            testcase( jj==nTo-1 );
115435            break;
115436          }
115437        }
115438        if( jj>=nTo ){
115439          if( nTo>=mxChoice && rCost>=mxCost ){
115440#ifdef WHERETRACE_ENABLED /* 0x4 */
115441            if( sqlite3WhereTrace&0x4 ){
115442              sqlite3DebugPrintf("Skip   %s cost=%-3d,%3d order=%c\n",
115443                  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
115444                  isOrdered>=0 ? isOrdered+'0' : '?');
115445            }
115446#endif
115447            continue;
115448          }
115449          /* Add a new Path to the aTo[] set */
115450          if( nTo<mxChoice ){
115451            /* Increase the size of the aTo set by one */
115452            jj = nTo++;
115453          }else{
115454            /* New path replaces the prior worst to keep count below mxChoice */
115455            jj = mxI;
115456          }
115457          pTo = &aTo[jj];
115458#ifdef WHERETRACE_ENABLED /* 0x4 */
115459          if( sqlite3WhereTrace&0x4 ){
115460            sqlite3DebugPrintf("New    %s cost=%-3d,%3d order=%c\n",
115461                wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
115462                isOrdered>=0 ? isOrdered+'0' : '?');
115463          }
115464#endif
115465        }else{
115466          if( pTo->rCost<=rCost && pTo->nRow<=nOut ){
115467#ifdef WHERETRACE_ENABLED /* 0x4 */
115468            if( sqlite3WhereTrace&0x4 ){
115469              sqlite3DebugPrintf(
115470                  "Skip   %s cost=%-3d,%3d order=%c",
115471                  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
115472                  isOrdered>=0 ? isOrdered+'0' : '?');
115473              sqlite3DebugPrintf("   vs %s cost=%-3d,%d order=%c\n",
115474                  wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
115475                  pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
115476            }
115477#endif
115478            testcase( pTo->rCost==rCost );
115479            continue;
115480          }
115481          testcase( pTo->rCost==rCost+1 );
115482          /* A new and better score for a previously created equivalent path */
115483#ifdef WHERETRACE_ENABLED /* 0x4 */
115484          if( sqlite3WhereTrace&0x4 ){
115485            sqlite3DebugPrintf(
115486                "Update %s cost=%-3d,%3d order=%c",
115487                wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
115488                isOrdered>=0 ? isOrdered+'0' : '?');
115489            sqlite3DebugPrintf("  was %s cost=%-3d,%3d order=%c\n",
115490                wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
115491                pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
115492          }
115493#endif
115494        }
115495        /* pWLoop is a winner.  Add it to the set of best so far */
115496        pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
115497        pTo->revLoop = revMask;
115498        pTo->nRow = nOut;
115499        pTo->rCost = rCost;
115500        pTo->isOrdered = isOrdered;
115501        memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
115502        pTo->aLoop[iLoop] = pWLoop;
115503        if( nTo>=mxChoice ){
115504          mxI = 0;
115505          mxCost = aTo[0].rCost;
115506          mxOut = aTo[0].nRow;
115507          for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
115508            if( pTo->rCost>mxCost || (pTo->rCost==mxCost && pTo->nRow>mxOut) ){
115509              mxCost = pTo->rCost;
115510              mxOut = pTo->nRow;
115511              mxI = jj;
115512            }
115513          }
115514        }
115515      }
115516    }
115517
115518#ifdef WHERETRACE_ENABLED  /* >=2 */
115519    if( sqlite3WhereTrace>=2 ){
115520      sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
115521      for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
115522        sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
115523           wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
115524           pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
115525        if( pTo->isOrdered>0 ){
115526          sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
115527        }else{
115528          sqlite3DebugPrintf("\n");
115529        }
115530      }
115531    }
115532#endif
115533
115534    /* Swap the roles of aFrom and aTo for the next generation */
115535    pFrom = aTo;
115536    aTo = aFrom;
115537    aFrom = pFrom;
115538    nFrom = nTo;
115539  }
115540
115541  if( nFrom==0 ){
115542    sqlite3ErrorMsg(pParse, "no query solution");
115543    sqlite3DbFree(db, pSpace);
115544    return SQLITE_ERROR;
115545  }
115546
115547  /* Find the lowest cost path.  pFrom will be left pointing to that path */
115548  pFrom = aFrom;
115549  for(ii=1; ii<nFrom; ii++){
115550    if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
115551  }
115552  assert( pWInfo->nLevel==nLoop );
115553  /* Load the lowest cost path into pWInfo */
115554  for(iLoop=0; iLoop<nLoop; iLoop++){
115555    WhereLevel *pLevel = pWInfo->a + iLoop;
115556    pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
115557    pLevel->iFrom = pWLoop->iTab;
115558    pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
115559  }
115560  if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
115561   && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
115562   && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
115563   && nRowEst
115564  ){
115565    Bitmask notUsed;
115566    int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
115567                 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
115568    if( rc==pWInfo->pResultSet->nExpr ){
115569      pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
115570    }
115571  }
115572  if( pWInfo->pOrderBy ){
115573    if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
115574      if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
115575        pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
115576      }
115577    }else{
115578      pWInfo->nOBSat = pFrom->isOrdered;
115579      if( pWInfo->nOBSat<0 ) pWInfo->nOBSat = 0;
115580      pWInfo->revMask = pFrom->revLoop;
115581    }
115582    if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
115583        && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr
115584    ){
115585      Bitmask notUsed = 0;
115586      int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
115587          pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed
115588      );
115589      assert( pWInfo->sorted==0 );
115590      pWInfo->sorted = (nOrder==pWInfo->pOrderBy->nExpr);
115591    }
115592  }
115593
115594
115595  pWInfo->nRowOut = pFrom->nRow;
115596
115597  /* Free temporary memory and return success */
115598  sqlite3DbFree(db, pSpace);
115599  return SQLITE_OK;
115600}
115601
115602/*
115603** Most queries use only a single table (they are not joins) and have
115604** simple == constraints against indexed fields.  This routine attempts
115605** to plan those simple cases using much less ceremony than the
115606** general-purpose query planner, and thereby yield faster sqlite3_prepare()
115607** times for the common case.
115608**
115609** Return non-zero on success, if this query can be handled by this
115610** no-frills query planner.  Return zero if this query needs the
115611** general-purpose query planner.
115612*/
115613static int whereShortCut(WhereLoopBuilder *pBuilder){
115614  WhereInfo *pWInfo;
115615  struct SrcList_item *pItem;
115616  WhereClause *pWC;
115617  WhereTerm *pTerm;
115618  WhereLoop *pLoop;
115619  int iCur;
115620  int j;
115621  Table *pTab;
115622  Index *pIdx;
115623
115624  pWInfo = pBuilder->pWInfo;
115625  if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
115626  assert( pWInfo->pTabList->nSrc>=1 );
115627  pItem = pWInfo->pTabList->a;
115628  pTab = pItem->pTab;
115629  if( IsVirtual(pTab) ) return 0;
115630  if( pItem->zIndex ) return 0;
115631  iCur = pItem->iCursor;
115632  pWC = &pWInfo->sWC;
115633  pLoop = pBuilder->pNew;
115634  pLoop->wsFlags = 0;
115635  pLoop->u.btree.nSkip = 0;
115636  pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
115637  if( pTerm ){
115638    pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
115639    pLoop->aLTerm[0] = pTerm;
115640    pLoop->nLTerm = 1;
115641    pLoop->u.btree.nEq = 1;
115642    /* TUNING: Cost of a rowid lookup is 10 */
115643    pLoop->rRun = 33;  /* 33==sqlite3LogEst(10) */
115644  }else{
115645    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
115646      assert( pLoop->aLTermSpace==pLoop->aLTerm );
115647      assert( ArraySize(pLoop->aLTermSpace)==4 );
115648      if( pIdx->onError==OE_None
115649       || pIdx->pPartIdxWhere!=0
115650       || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
115651      ) continue;
115652      for(j=0; j<pIdx->nKeyCol; j++){
115653        pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
115654        if( pTerm==0 ) break;
115655        pLoop->aLTerm[j] = pTerm;
115656      }
115657      if( j!=pIdx->nKeyCol ) continue;
115658      pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
115659      if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
115660        pLoop->wsFlags |= WHERE_IDX_ONLY;
115661      }
115662      pLoop->nLTerm = j;
115663      pLoop->u.btree.nEq = j;
115664      pLoop->u.btree.pIndex = pIdx;
115665      /* TUNING: Cost of a unique index lookup is 15 */
115666      pLoop->rRun = 39;  /* 39==sqlite3LogEst(15) */
115667      break;
115668    }
115669  }
115670  if( pLoop->wsFlags ){
115671    pLoop->nOut = (LogEst)1;
115672    pWInfo->a[0].pWLoop = pLoop;
115673    pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
115674    pWInfo->a[0].iTabCur = iCur;
115675    pWInfo->nRowOut = 1;
115676    if( pWInfo->pOrderBy ) pWInfo->nOBSat =  pWInfo->pOrderBy->nExpr;
115677    if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
115678      pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
115679    }
115680#ifdef SQLITE_DEBUG
115681    pLoop->cId = '0';
115682#endif
115683    return 1;
115684  }
115685  return 0;
115686}
115687
115688/*
115689** Generate the beginning of the loop used for WHERE clause processing.
115690** The return value is a pointer to an opaque structure that contains
115691** information needed to terminate the loop.  Later, the calling routine
115692** should invoke sqlite3WhereEnd() with the return value of this function
115693** in order to complete the WHERE clause processing.
115694**
115695** If an error occurs, this routine returns NULL.
115696**
115697** The basic idea is to do a nested loop, one loop for each table in
115698** the FROM clause of a select.  (INSERT and UPDATE statements are the
115699** same as a SELECT with only a single table in the FROM clause.)  For
115700** example, if the SQL is this:
115701**
115702**       SELECT * FROM t1, t2, t3 WHERE ...;
115703**
115704** Then the code generated is conceptually like the following:
115705**
115706**      foreach row1 in t1 do       \    Code generated
115707**        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
115708**          foreach row3 in t3 do   /
115709**            ...
115710**          end                     \    Code generated
115711**        end                        |-- by sqlite3WhereEnd()
115712**      end                         /
115713**
115714** Note that the loops might not be nested in the order in which they
115715** appear in the FROM clause if a different order is better able to make
115716** use of indices.  Note also that when the IN operator appears in
115717** the WHERE clause, it might result in additional nested loops for
115718** scanning through all values on the right-hand side of the IN.
115719**
115720** There are Btree cursors associated with each table.  t1 uses cursor
115721** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
115722** And so forth.  This routine generates code to open those VDBE cursors
115723** and sqlite3WhereEnd() generates the code to close them.
115724**
115725** The code that sqlite3WhereBegin() generates leaves the cursors named
115726** in pTabList pointing at their appropriate entries.  The [...] code
115727** can use OP_Column and OP_Rowid opcodes on these cursors to extract
115728** data from the various tables of the loop.
115729**
115730** If the WHERE clause is empty, the foreach loops must each scan their
115731** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
115732** the tables have indices and there are terms in the WHERE clause that
115733** refer to those indices, a complete table scan can be avoided and the
115734** code will run much faster.  Most of the work of this routine is checking
115735** to see if there are indices that can be used to speed up the loop.
115736**
115737** Terms of the WHERE clause are also used to limit which rows actually
115738** make it to the "..." in the middle of the loop.  After each "foreach",
115739** terms of the WHERE clause that use only terms in that loop and outer
115740** loops are evaluated and if false a jump is made around all subsequent
115741** inner loops (or around the "..." if the test occurs within the inner-
115742** most loop)
115743**
115744** OUTER JOINS
115745**
115746** An outer join of tables t1 and t2 is conceptally coded as follows:
115747**
115748**    foreach row1 in t1 do
115749**      flag = 0
115750**      foreach row2 in t2 do
115751**        start:
115752**          ...
115753**          flag = 1
115754**      end
115755**      if flag==0 then
115756**        move the row2 cursor to a null row
115757**        goto start
115758**      fi
115759**    end
115760**
115761** ORDER BY CLAUSE PROCESSING
115762**
115763** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
115764** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
115765** if there is one.  If there is no ORDER BY clause or if this routine
115766** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
115767**
115768** The iIdxCur parameter is the cursor number of an index.  If
115769** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index
115770** to use for OR clause processing.  The WHERE clause should use this
115771** specific cursor.  If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
115772** the first cursor in an array of cursors for all indices.  iIdxCur should
115773** be used to compute the appropriate cursor depending on which index is
115774** used.
115775*/
115776SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
115777  Parse *pParse,        /* The parser context */
115778  SrcList *pTabList,    /* FROM clause: A list of all tables to be scanned */
115779  Expr *pWhere,         /* The WHERE clause */
115780  ExprList *pOrderBy,   /* An ORDER BY (or GROUP BY) clause, or NULL */
115781  ExprList *pResultSet, /* Result set of the query */
115782  u16 wctrlFlags,       /* One of the WHERE_* flags defined in sqliteInt.h */
115783  int iIdxCur           /* If WHERE_ONETABLE_ONLY is set, index cursor number */
115784){
115785  int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
115786  int nTabList;              /* Number of elements in pTabList */
115787  WhereInfo *pWInfo;         /* Will become the return value of this function */
115788  Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
115789  Bitmask notReady;          /* Cursors that are not yet positioned */
115790  WhereLoopBuilder sWLB;     /* The WhereLoop builder */
115791  WhereMaskSet *pMaskSet;    /* The expression mask set */
115792  WhereLevel *pLevel;        /* A single level in pWInfo->a[] */
115793  WhereLoop *pLoop;          /* Pointer to a single WhereLoop object */
115794  int ii;                    /* Loop counter */
115795  sqlite3 *db;               /* Database connection */
115796  int rc;                    /* Return code */
115797
115798
115799  /* Variable initialization */
115800  db = pParse->db;
115801  memset(&sWLB, 0, sizeof(sWLB));
115802
115803  /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
115804  testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
115805  if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
115806  sWLB.pOrderBy = pOrderBy;
115807
115808  /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
115809  ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
115810  if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
115811    wctrlFlags &= ~WHERE_WANT_DISTINCT;
115812  }
115813
115814  /* The number of tables in the FROM clause is limited by the number of
115815  ** bits in a Bitmask
115816  */
115817  testcase( pTabList->nSrc==BMS );
115818  if( pTabList->nSrc>BMS ){
115819    sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
115820    return 0;
115821  }
115822
115823  /* This function normally generates a nested loop for all tables in
115824  ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
115825  ** only generate code for the first table in pTabList and assume that
115826  ** any cursors associated with subsequent tables are uninitialized.
115827  */
115828  nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
115829
115830  /* Allocate and initialize the WhereInfo structure that will become the
115831  ** return value. A single allocation is used to store the WhereInfo
115832  ** struct, the contents of WhereInfo.a[], the WhereClause structure
115833  ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
115834  ** field (type Bitmask) it must be aligned on an 8-byte boundary on
115835  ** some architectures. Hence the ROUND8() below.
115836  */
115837  nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
115838  pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
115839  if( db->mallocFailed ){
115840    sqlite3DbFree(db, pWInfo);
115841    pWInfo = 0;
115842    goto whereBeginError;
115843  }
115844  pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
115845  pWInfo->nLevel = nTabList;
115846  pWInfo->pParse = pParse;
115847  pWInfo->pTabList = pTabList;
115848  pWInfo->pOrderBy = pOrderBy;
115849  pWInfo->pResultSet = pResultSet;
115850  pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
115851  pWInfo->wctrlFlags = wctrlFlags;
115852  pWInfo->savedNQueryLoop = pParse->nQueryLoop;
115853  pMaskSet = &pWInfo->sMaskSet;
115854  sWLB.pWInfo = pWInfo;
115855  sWLB.pWC = &pWInfo->sWC;
115856  sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
115857  assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
115858  whereLoopInit(sWLB.pNew);
115859#ifdef SQLITE_DEBUG
115860  sWLB.pNew->cId = '*';
115861#endif
115862
115863  /* Split the WHERE clause into separate subexpressions where each
115864  ** subexpression is separated by an AND operator.
115865  */
115866  initMaskSet(pMaskSet);
115867  whereClauseInit(&pWInfo->sWC, pWInfo);
115868  whereSplit(&pWInfo->sWC, pWhere, TK_AND);
115869
115870  /* Special case: a WHERE clause that is constant.  Evaluate the
115871  ** expression and either jump over all of the code or fall thru.
115872  */
115873  for(ii=0; ii<sWLB.pWC->nTerm; ii++){
115874    if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
115875      sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
115876                         SQLITE_JUMPIFNULL);
115877      sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
115878    }
115879  }
115880
115881  /* Special case: No FROM clause
115882  */
115883  if( nTabList==0 ){
115884    if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
115885    if( wctrlFlags & WHERE_WANT_DISTINCT ){
115886      pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
115887    }
115888  }
115889
115890  /* Assign a bit from the bitmask to every term in the FROM clause.
115891  **
115892  ** When assigning bitmask values to FROM clause cursors, it must be
115893  ** the case that if X is the bitmask for the N-th FROM clause term then
115894  ** the bitmask for all FROM clause terms to the left of the N-th term
115895  ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
115896  ** its Expr.iRightJoinTable value to find the bitmask of the right table
115897  ** of the join.  Subtracting one from the right table bitmask gives a
115898  ** bitmask for all tables to the left of the join.  Knowing the bitmask
115899  ** for all tables to the left of a left join is important.  Ticket #3015.
115900  **
115901  ** Note that bitmasks are created for all pTabList->nSrc tables in
115902  ** pTabList, not just the first nTabList tables.  nTabList is normally
115903  ** equal to pTabList->nSrc but might be shortened to 1 if the
115904  ** WHERE_ONETABLE_ONLY flag is set.
115905  */
115906  for(ii=0; ii<pTabList->nSrc; ii++){
115907    createMask(pMaskSet, pTabList->a[ii].iCursor);
115908  }
115909#ifndef NDEBUG
115910  {
115911    Bitmask toTheLeft = 0;
115912    for(ii=0; ii<pTabList->nSrc; ii++){
115913      Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
115914      assert( (m-1)==toTheLeft );
115915      toTheLeft |= m;
115916    }
115917  }
115918#endif
115919
115920  /* Analyze all of the subexpressions.  Note that exprAnalyze() might
115921  ** add new virtual terms onto the end of the WHERE clause.  We do not
115922  ** want to analyze these virtual terms, so start analyzing at the end
115923  ** and work forward so that the added virtual terms are never processed.
115924  */
115925  exprAnalyzeAll(pTabList, &pWInfo->sWC);
115926  if( db->mallocFailed ){
115927    goto whereBeginError;
115928  }
115929
115930  if( wctrlFlags & WHERE_WANT_DISTINCT ){
115931    if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
115932      /* The DISTINCT marking is pointless.  Ignore it. */
115933      pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
115934    }else if( pOrderBy==0 ){
115935      /* Try to ORDER BY the result set to make distinct processing easier */
115936      pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
115937      pWInfo->pOrderBy = pResultSet;
115938    }
115939  }
115940
115941  /* Construct the WhereLoop objects */
115942  WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
115943  /* Display all terms of the WHERE clause */
115944#if defined(WHERETRACE_ENABLED) && defined(SQLITE_ENABLE_TREE_EXPLAIN)
115945  if( sqlite3WhereTrace & 0x100 ){
115946    int i;
115947    Vdbe *v = pParse->pVdbe;
115948    sqlite3ExplainBegin(v);
115949    for(i=0; i<sWLB.pWC->nTerm; i++){
115950      sqlite3ExplainPrintf(v, "#%-2d ", i);
115951      sqlite3ExplainPush(v);
115952      whereExplainTerm(v, &sWLB.pWC->a[i]);
115953      sqlite3ExplainPop(v);
115954      sqlite3ExplainNL(v);
115955    }
115956    sqlite3ExplainFinish(v);
115957    sqlite3DebugPrintf("%s", sqlite3VdbeExplanation(v));
115958  }
115959#endif
115960  if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
115961    rc = whereLoopAddAll(&sWLB);
115962    if( rc ) goto whereBeginError;
115963
115964    /* Display all of the WhereLoop objects if wheretrace is enabled */
115965#ifdef WHERETRACE_ENABLED /* !=0 */
115966    if( sqlite3WhereTrace ){
115967      WhereLoop *p;
115968      int i;
115969      static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
115970                                       "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
115971      for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
115972        p->cId = zLabel[i%sizeof(zLabel)];
115973        whereLoopPrint(p, sWLB.pWC);
115974      }
115975    }
115976#endif
115977
115978    wherePathSolver(pWInfo, 0);
115979    if( db->mallocFailed ) goto whereBeginError;
115980    if( pWInfo->pOrderBy ){
115981       wherePathSolver(pWInfo, pWInfo->nRowOut+1);
115982       if( db->mallocFailed ) goto whereBeginError;
115983    }
115984  }
115985  if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
115986     pWInfo->revMask = (Bitmask)(-1);
115987  }
115988  if( pParse->nErr || NEVER(db->mallocFailed) ){
115989    goto whereBeginError;
115990  }
115991#ifdef WHERETRACE_ENABLED /* !=0 */
115992  if( sqlite3WhereTrace ){
115993    int ii;
115994    sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
115995    if( pWInfo->nOBSat>0 ){
115996      sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
115997    }
115998    switch( pWInfo->eDistinct ){
115999      case WHERE_DISTINCT_UNIQUE: {
116000        sqlite3DebugPrintf("  DISTINCT=unique");
116001        break;
116002      }
116003      case WHERE_DISTINCT_ORDERED: {
116004        sqlite3DebugPrintf("  DISTINCT=ordered");
116005        break;
116006      }
116007      case WHERE_DISTINCT_UNORDERED: {
116008        sqlite3DebugPrintf("  DISTINCT=unordered");
116009        break;
116010      }
116011    }
116012    sqlite3DebugPrintf("\n");
116013    for(ii=0; ii<pWInfo->nLevel; ii++){
116014      whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
116015    }
116016  }
116017#endif
116018  /* Attempt to omit tables from the join that do not effect the result */
116019  if( pWInfo->nLevel>=2
116020   && pResultSet!=0
116021   && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
116022  ){
116023    Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
116024    if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy);
116025    while( pWInfo->nLevel>=2 ){
116026      WhereTerm *pTerm, *pEnd;
116027      pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
116028      if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
116029      if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
116030       && (pLoop->wsFlags & WHERE_ONEROW)==0
116031      ){
116032        break;
116033      }
116034      if( (tabUsed & pLoop->maskSelf)!=0 ) break;
116035      pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
116036      for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
116037        if( (pTerm->prereqAll & pLoop->maskSelf)!=0
116038         && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
116039        ){
116040          break;
116041        }
116042      }
116043      if( pTerm<pEnd ) break;
116044      WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
116045      pWInfo->nLevel--;
116046      nTabList--;
116047    }
116048  }
116049  WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
116050  pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
116051
116052  /* If the caller is an UPDATE or DELETE statement that is requesting
116053  ** to use a one-pass algorithm, determine if this is appropriate.
116054  ** The one-pass algorithm only works if the WHERE clause constrains
116055  ** the statement to update a single row.
116056  */
116057  assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
116058  if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
116059   && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
116060    pWInfo->okOnePass = 1;
116061    if( HasRowid(pTabList->a[0].pTab) ){
116062      pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
116063    }
116064  }
116065
116066  /* Open all tables in the pTabList and any indices selected for
116067  ** searching those tables.
116068  */
116069  notReady = ~(Bitmask)0;
116070  for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
116071    Table *pTab;     /* Table to open */
116072    int iDb;         /* Index of database containing table/index */
116073    struct SrcList_item *pTabItem;
116074
116075    pTabItem = &pTabList->a[pLevel->iFrom];
116076    pTab = pTabItem->pTab;
116077    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
116078    pLoop = pLevel->pWLoop;
116079    if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
116080      /* Do nothing */
116081    }else
116082#ifndef SQLITE_OMIT_VIRTUALTABLE
116083    if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
116084      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
116085      int iCur = pTabItem->iCursor;
116086      sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
116087    }else if( IsVirtual(pTab) ){
116088      /* noop */
116089    }else
116090#endif
116091    if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
116092         && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
116093      int op = OP_OpenRead;
116094      if( pWInfo->okOnePass ){
116095        op = OP_OpenWrite;
116096        pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
116097      };
116098      sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
116099      assert( pTabItem->iCursor==pLevel->iTabCur );
116100      testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
116101      testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
116102      if( !pWInfo->okOnePass && pTab->nCol<BMS && HasRowid(pTab) ){
116103        Bitmask b = pTabItem->colUsed;
116104        int n = 0;
116105        for(; b; b=b>>1, n++){}
116106        sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
116107                            SQLITE_INT_TO_PTR(n), P4_INT32);
116108        assert( n<=pTab->nCol );
116109      }
116110    }else{
116111      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
116112    }
116113    if( pLoop->wsFlags & WHERE_INDEXED ){
116114      Index *pIx = pLoop->u.btree.pIndex;
116115      int iIndexCur;
116116      int op = OP_OpenRead;
116117      /* iIdxCur is always set if to a positive value if ONEPASS is possible */
116118      assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
116119      if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
116120       && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0
116121      ){
116122        /* This is one term of an OR-optimization using the PRIMARY KEY of a
116123        ** WITHOUT ROWID table.  No need for a separate index */
116124        iIndexCur = pLevel->iTabCur;
116125        op = 0;
116126      }else if( pWInfo->okOnePass ){
116127        Index *pJ = pTabItem->pTab->pIndex;
116128        iIndexCur = iIdxCur;
116129        assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
116130        while( ALWAYS(pJ) && pJ!=pIx ){
116131          iIndexCur++;
116132          pJ = pJ->pNext;
116133        }
116134        op = OP_OpenWrite;
116135        pWInfo->aiCurOnePass[1] = iIndexCur;
116136      }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){
116137        iIndexCur = iIdxCur;
116138      }else{
116139        iIndexCur = pParse->nTab++;
116140      }
116141      pLevel->iIdxCur = iIndexCur;
116142      assert( pIx->pSchema==pTab->pSchema );
116143      assert( iIndexCur>=0 );
116144      if( op ){
116145        sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
116146        sqlite3VdbeSetP4KeyInfo(pParse, pIx);
116147        VdbeComment((v, "%s", pIx->zName));
116148      }
116149    }
116150    if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
116151    notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
116152  }
116153  pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
116154  if( db->mallocFailed ) goto whereBeginError;
116155
116156  /* Generate the code to do the search.  Each iteration of the for
116157  ** loop below generates code for a single nested loop of the VM
116158  ** program.
116159  */
116160  notReady = ~(Bitmask)0;
116161  for(ii=0; ii<nTabList; ii++){
116162    pLevel = &pWInfo->a[ii];
116163#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
116164    if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
116165      constructAutomaticIndex(pParse, &pWInfo->sWC,
116166                &pTabList->a[pLevel->iFrom], notReady, pLevel);
116167      if( db->mallocFailed ) goto whereBeginError;
116168    }
116169#endif
116170    explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
116171    pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
116172    notReady = codeOneLoopStart(pWInfo, ii, notReady);
116173    pWInfo->iContinue = pLevel->addrCont;
116174  }
116175
116176  /* Done. */
116177  VdbeModuleComment((v, "Begin WHERE-core"));
116178  return pWInfo;
116179
116180  /* Jump here if malloc fails */
116181whereBeginError:
116182  if( pWInfo ){
116183    pParse->nQueryLoop = pWInfo->savedNQueryLoop;
116184    whereInfoFree(db, pWInfo);
116185  }
116186  return 0;
116187}
116188
116189/*
116190** Generate the end of the WHERE loop.  See comments on
116191** sqlite3WhereBegin() for additional information.
116192*/
116193SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
116194  Parse *pParse = pWInfo->pParse;
116195  Vdbe *v = pParse->pVdbe;
116196  int i;
116197  WhereLevel *pLevel;
116198  WhereLoop *pLoop;
116199  SrcList *pTabList = pWInfo->pTabList;
116200  sqlite3 *db = pParse->db;
116201
116202  /* Generate loop termination code.
116203  */
116204  VdbeModuleComment((v, "End WHERE-core"));
116205  sqlite3ExprCacheClear(pParse);
116206  for(i=pWInfo->nLevel-1; i>=0; i--){
116207    int addr;
116208    pLevel = &pWInfo->a[i];
116209    pLoop = pLevel->pWLoop;
116210    sqlite3VdbeResolveLabel(v, pLevel->addrCont);
116211    if( pLevel->op!=OP_Noop ){
116212      sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
116213      sqlite3VdbeChangeP5(v, pLevel->p5);
116214      VdbeCoverage(v);
116215      VdbeCoverageIf(v, pLevel->op==OP_Next);
116216      VdbeCoverageIf(v, pLevel->op==OP_Prev);
116217      VdbeCoverageIf(v, pLevel->op==OP_VNext);
116218    }
116219    if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
116220      struct InLoop *pIn;
116221      int j;
116222      sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
116223      for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
116224        sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
116225        sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
116226        VdbeCoverage(v);
116227        VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
116228        VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
116229        sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
116230      }
116231      sqlite3DbFree(db, pLevel->u.in.aInLoop);
116232    }
116233    sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
116234    if( pLevel->addrSkip ){
116235      sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrSkip);
116236      VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
116237      sqlite3VdbeJumpHere(v, pLevel->addrSkip);
116238      sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
116239    }
116240    if( pLevel->iLeftJoin ){
116241      addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
116242      assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
116243           || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
116244      if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
116245        sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
116246      }
116247      if( pLoop->wsFlags & WHERE_INDEXED ){
116248        sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
116249      }
116250      if( pLevel->op==OP_Return ){
116251        sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
116252      }else{
116253        sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
116254      }
116255      sqlite3VdbeJumpHere(v, addr);
116256    }
116257    VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
116258                     pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
116259  }
116260
116261  /* The "break" point is here, just past the end of the outer loop.
116262  ** Set it.
116263  */
116264  sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
116265
116266  assert( pWInfo->nLevel<=pTabList->nSrc );
116267  for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
116268    int k, last;
116269    VdbeOp *pOp;
116270    Index *pIdx = 0;
116271    struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
116272    Table *pTab = pTabItem->pTab;
116273    assert( pTab!=0 );
116274    pLoop = pLevel->pWLoop;
116275
116276    /* For a co-routine, change all OP_Column references to the table of
116277    ** the co-routine into OP_SCopy of result contained in a register.
116278    ** OP_Rowid becomes OP_Null.
116279    */
116280    if( pTabItem->viaCoroutine && !db->mallocFailed ){
116281      last = sqlite3VdbeCurrentAddr(v);
116282      k = pLevel->addrBody;
116283      pOp = sqlite3VdbeGetOp(v, k);
116284      for(; k<last; k++, pOp++){
116285        if( pOp->p1!=pLevel->iTabCur ) continue;
116286        if( pOp->opcode==OP_Column ){
116287          pOp->opcode = OP_Copy;
116288          pOp->p1 = pOp->p2 + pTabItem->regResult;
116289          pOp->p2 = pOp->p3;
116290          pOp->p3 = 0;
116291        }else if( pOp->opcode==OP_Rowid ){
116292          pOp->opcode = OP_Null;
116293          pOp->p1 = 0;
116294          pOp->p3 = 0;
116295        }
116296      }
116297      continue;
116298    }
116299
116300    /* Close all of the cursors that were opened by sqlite3WhereBegin.
116301    ** Except, do not close cursors that will be reused by the OR optimization
116302    ** (WHERE_OMIT_OPEN_CLOSE).  And do not close the OP_OpenWrite cursors
116303    ** created for the ONEPASS optimization.
116304    */
116305    if( (pTab->tabFlags & TF_Ephemeral)==0
116306     && pTab->pSelect==0
116307     && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
116308    ){
116309      int ws = pLoop->wsFlags;
116310      if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
116311        sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
116312      }
116313      if( (ws & WHERE_INDEXED)!=0
116314       && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
116315       && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
116316      ){
116317        sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
116318      }
116319    }
116320
116321    /* If this scan uses an index, make VDBE code substitutions to read data
116322    ** from the index instead of from the table where possible.  In some cases
116323    ** this optimization prevents the table from ever being read, which can
116324    ** yield a significant performance boost.
116325    **
116326    ** Calls to the code generator in between sqlite3WhereBegin and
116327    ** sqlite3WhereEnd will have created code that references the table
116328    ** directly.  This loop scans all that code looking for opcodes
116329    ** that reference the table and converts them into opcodes that
116330    ** reference the index.
116331    */
116332    if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
116333      pIdx = pLoop->u.btree.pIndex;
116334    }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
116335      pIdx = pLevel->u.pCovidx;
116336    }
116337    if( pIdx && !db->mallocFailed ){
116338      last = sqlite3VdbeCurrentAddr(v);
116339      k = pLevel->addrBody;
116340      pOp = sqlite3VdbeGetOp(v, k);
116341      for(; k<last; k++, pOp++){
116342        if( pOp->p1!=pLevel->iTabCur ) continue;
116343        if( pOp->opcode==OP_Column ){
116344          int x = pOp->p2;
116345          assert( pIdx->pTable==pTab );
116346          if( !HasRowid(pTab) ){
116347            Index *pPk = sqlite3PrimaryKeyIndex(pTab);
116348            x = pPk->aiColumn[x];
116349          }
116350          x = sqlite3ColumnOfIndex(pIdx, x);
116351          if( x>=0 ){
116352            pOp->p2 = x;
116353            pOp->p1 = pLevel->iIdxCur;
116354          }
116355          assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
116356        }else if( pOp->opcode==OP_Rowid ){
116357          pOp->p1 = pLevel->iIdxCur;
116358          pOp->opcode = OP_IdxRowid;
116359        }
116360      }
116361    }
116362  }
116363
116364  /* Final cleanup
116365  */
116366  pParse->nQueryLoop = pWInfo->savedNQueryLoop;
116367  whereInfoFree(db, pWInfo);
116368  return;
116369}
116370
116371/************** End of where.c ***********************************************/
116372/************** Begin file parse.c *******************************************/
116373/* Driver template for the LEMON parser generator.
116374** The author disclaims copyright to this source code.
116375**
116376** This version of "lempar.c" is modified, slightly, for use by SQLite.
116377** The only modifications are the addition of a couple of NEVER()
116378** macros to disable tests that are needed in the case of a general
116379** LALR(1) grammar but which are always false in the
116380** specific grammar used by SQLite.
116381*/
116382/* First off, code is included that follows the "include" declaration
116383** in the input grammar file. */
116384/* #include <stdio.h> */
116385
116386
116387/*
116388** Disable all error recovery processing in the parser push-down
116389** automaton.
116390*/
116391#define YYNOERRORRECOVERY 1
116392
116393/*
116394** Make yytestcase() the same as testcase()
116395*/
116396#define yytestcase(X) testcase(X)
116397
116398/*
116399** An instance of this structure holds information about the
116400** LIMIT clause of a SELECT statement.
116401*/
116402struct LimitVal {
116403  Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
116404  Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
116405};
116406
116407/*
116408** An instance of this structure is used to store the LIKE,
116409** GLOB, NOT LIKE, and NOT GLOB operators.
116410*/
116411struct LikeOp {
116412  Token eOperator;  /* "like" or "glob" or "regexp" */
116413  int bNot;         /* True if the NOT keyword is present */
116414};
116415
116416/*
116417** An instance of the following structure describes the event of a
116418** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
116419** TK_DELETE, or TK_INSTEAD.  If the event is of the form
116420**
116421**      UPDATE ON (a,b,c)
116422**
116423** Then the "b" IdList records the list "a,b,c".
116424*/
116425struct TrigEvent { int a; IdList * b; };
116426
116427/*
116428** An instance of this structure holds the ATTACH key and the key type.
116429*/
116430struct AttachKey { int type;  Token key; };
116431
116432
116433  /* This is a utility routine used to set the ExprSpan.zStart and
116434  ** ExprSpan.zEnd values of pOut so that the span covers the complete
116435  ** range of text beginning with pStart and going to the end of pEnd.
116436  */
116437  static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
116438    pOut->zStart = pStart->z;
116439    pOut->zEnd = &pEnd->z[pEnd->n];
116440  }
116441
116442  /* Construct a new Expr object from a single identifier.  Use the
116443  ** new Expr to populate pOut.  Set the span of pOut to be the identifier
116444  ** that created the expression.
116445  */
116446  static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
116447    pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
116448    pOut->zStart = pValue->z;
116449    pOut->zEnd = &pValue->z[pValue->n];
116450  }
116451
116452  /* This routine constructs a binary expression node out of two ExprSpan
116453  ** objects and uses the result to populate a new ExprSpan object.
116454  */
116455  static void spanBinaryExpr(
116456    ExprSpan *pOut,     /* Write the result here */
116457    Parse *pParse,      /* The parsing context.  Errors accumulate here */
116458    int op,             /* The binary operation */
116459    ExprSpan *pLeft,    /* The left operand */
116460    ExprSpan *pRight    /* The right operand */
116461  ){
116462    pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
116463    pOut->zStart = pLeft->zStart;
116464    pOut->zEnd = pRight->zEnd;
116465  }
116466
116467  /* Construct an expression node for a unary postfix operator
116468  */
116469  static void spanUnaryPostfix(
116470    ExprSpan *pOut,        /* Write the new expression node here */
116471    Parse *pParse,         /* Parsing context to record errors */
116472    int op,                /* The operator */
116473    ExprSpan *pOperand,    /* The operand */
116474    Token *pPostOp         /* The operand token for setting the span */
116475  ){
116476    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
116477    pOut->zStart = pOperand->zStart;
116478    pOut->zEnd = &pPostOp->z[pPostOp->n];
116479  }
116480
116481  /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
116482  ** unary TK_ISNULL or TK_NOTNULL expression. */
116483  static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
116484    sqlite3 *db = pParse->db;
116485    if( db->mallocFailed==0 && pY->op==TK_NULL ){
116486      pA->op = (u8)op;
116487      sqlite3ExprDelete(db, pA->pRight);
116488      pA->pRight = 0;
116489    }
116490  }
116491
116492  /* Construct an expression node for a unary prefix operator
116493  */
116494  static void spanUnaryPrefix(
116495    ExprSpan *pOut,        /* Write the new expression node here */
116496    Parse *pParse,         /* Parsing context to record errors */
116497    int op,                /* The operator */
116498    ExprSpan *pOperand,    /* The operand */
116499    Token *pPreOp         /* The operand token for setting the span */
116500  ){
116501    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
116502    pOut->zStart = pPreOp->z;
116503    pOut->zEnd = pOperand->zEnd;
116504  }
116505/* Next is all token values, in a form suitable for use by makeheaders.
116506** This section will be null unless lemon is run with the -m switch.
116507*/
116508/*
116509** These constants (all generated automatically by the parser generator)
116510** specify the various kinds of tokens (terminals) that the parser
116511** understands.
116512**
116513** Each symbol here is a terminal symbol in the grammar.
116514*/
116515/* Make sure the INTERFACE macro is defined.
116516*/
116517#ifndef INTERFACE
116518# define INTERFACE 1
116519#endif
116520/* The next thing included is series of defines which control
116521** various aspects of the generated parser.
116522**    YYCODETYPE         is the data type used for storing terminal
116523**                       and nonterminal numbers.  "unsigned char" is
116524**                       used if there are fewer than 250 terminals
116525**                       and nonterminals.  "int" is used otherwise.
116526**    YYNOCODE           is a number of type YYCODETYPE which corresponds
116527**                       to no legal terminal or nonterminal number.  This
116528**                       number is used to fill in empty slots of the hash
116529**                       table.
116530**    YYFALLBACK         If defined, this indicates that one or more tokens
116531**                       have fall-back values which should be used if the
116532**                       original value of the token will not parse.
116533**    YYACTIONTYPE       is the data type used for storing terminal
116534**                       and nonterminal numbers.  "unsigned char" is
116535**                       used if there are fewer than 250 rules and
116536**                       states combined.  "int" is used otherwise.
116537**    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given
116538**                       directly to the parser from the tokenizer.
116539**    YYMINORTYPE        is the data type used for all minor tokens.
116540**                       This is typically a union of many types, one of
116541**                       which is sqlite3ParserTOKENTYPE.  The entry in the union
116542**                       for base tokens is called "yy0".
116543**    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
116544**                       zero the stack is dynamically sized using realloc()
116545**    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
116546**    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
116547**    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
116548**    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
116549**    YYNSTATE           the combined number of states.
116550**    YYNRULE            the number of rules in the grammar
116551**    YYERRORSYMBOL      is the code number of the error symbol.  If not
116552**                       defined, then do no error processing.
116553*/
116554#define YYCODETYPE unsigned char
116555#define YYNOCODE 254
116556#define YYACTIONTYPE unsigned short int
116557#define YYWILDCARD 70
116558#define sqlite3ParserTOKENTYPE Token
116559typedef union {
116560  int yyinit;
116561  sqlite3ParserTOKENTYPE yy0;
116562  Select* yy3;
116563  ExprList* yy14;
116564  With* yy59;
116565  SrcList* yy65;
116566  struct LikeOp yy96;
116567  Expr* yy132;
116568  u8 yy186;
116569  int yy328;
116570  ExprSpan yy346;
116571  struct TrigEvent yy378;
116572  u16 yy381;
116573  IdList* yy408;
116574  struct {int value; int mask;} yy429;
116575  TriggerStep* yy473;
116576  struct LimitVal yy476;
116577} YYMINORTYPE;
116578#ifndef YYSTACKDEPTH
116579#define YYSTACKDEPTH 100
116580#endif
116581#define sqlite3ParserARG_SDECL Parse *pParse;
116582#define sqlite3ParserARG_PDECL ,Parse *pParse
116583#define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
116584#define sqlite3ParserARG_STORE yypParser->pParse = pParse
116585#define YYNSTATE 642
116586#define YYNRULE 327
116587#define YYFALLBACK 1
116588#define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
116589#define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
116590#define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
116591
116592/* The yyzerominor constant is used to initialize instances of
116593** YYMINORTYPE objects to zero. */
116594static const YYMINORTYPE yyzerominor = { 0 };
116595
116596/* Define the yytestcase() macro to be a no-op if is not already defined
116597** otherwise.
116598**
116599** Applications can choose to define yytestcase() in the %include section
116600** to a macro that can assist in verifying code coverage.  For production
116601** code the yytestcase() macro should be turned off.  But it is useful
116602** for testing.
116603*/
116604#ifndef yytestcase
116605# define yytestcase(X)
116606#endif
116607
116608
116609/* Next are the tables used to determine what action to take based on the
116610** current state and lookahead token.  These tables are used to implement
116611** functions that take a state number and lookahead value and return an
116612** action integer.
116613**
116614** Suppose the action integer is N.  Then the action is determined as
116615** follows
116616**
116617**   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
116618**                                      token onto the stack and goto state N.
116619**
116620**   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
116621**
116622**   N == YYNSTATE+YYNRULE              A syntax error has occurred.
116623**
116624**   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
116625**
116626**   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
116627**                                      slots in the yy_action[] table.
116628**
116629** The action table is constructed as a single large table named yy_action[].
116630** Given state S and lookahead X, the action is computed as
116631**
116632**      yy_action[ yy_shift_ofst[S] + X ]
116633**
116634** If the index value yy_shift_ofst[S]+X is out of range or if the value
116635** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
116636** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
116637** and that yy_default[S] should be used instead.
116638**
116639** The formula above is for computing the action when the lookahead is
116640** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
116641** a reduce action) then the yy_reduce_ofst[] array is used in place of
116642** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
116643** YY_SHIFT_USE_DFLT.
116644**
116645** The following are the tables generated in this section:
116646**
116647**  yy_action[]        A single table containing all actions.
116648**  yy_lookahead[]     A table containing the lookahead for each entry in
116649**                     yy_action.  Used to detect hash collisions.
116650**  yy_shift_ofst[]    For each state, the offset into yy_action for
116651**                     shifting terminals.
116652**  yy_reduce_ofst[]   For each state, the offset into yy_action for
116653**                     shifting non-terminals after a reduce.
116654**  yy_default[]       Default action for each state.
116655*/
116656#define YY_ACTTAB_COUNT (1497)
116657static const YYACTIONTYPE yy_action[] = {
116658 /*     0 */   306,  212,  432,  955,  639,  191,  955,  295,  559,   88,
116659 /*    10 */    88,   88,   88,   81,   86,   86,   86,   86,   85,   85,
116660 /*    20 */    84,   84,   84,   83,  330,  185,  184,  183,  635,  635,
116661 /*    30 */   292,  606,  606,   88,   88,   88,   88,  683,   86,   86,
116662 /*    40 */    86,   86,   85,   85,   84,   84,   84,   83,  330,   16,
116663 /*    50 */   436,  597,   89,   90,   80,  600,  599,  601,  601,   87,
116664 /*    60 */    87,   88,   88,   88,   88,  684,   86,   86,   86,   86,
116665 /*    70 */    85,   85,   84,   84,   84,   83,  330,  306,  559,   84,
116666 /*    80 */    84,   84,   83,  330,   65,   86,   86,   86,   86,   85,
116667 /*    90 */    85,   84,   84,   84,   83,  330,  635,  635,  634,  633,
116668 /*   100 */   182,  682,  550,  379,  376,  375,   17,  322,  606,  606,
116669 /*   110 */   371,  198,  479,   91,  374,   82,   79,  165,   85,   85,
116670 /*   120 */    84,   84,   84,   83,  330,  598,  635,  635,  107,   89,
116671 /*   130 */    90,   80,  600,  599,  601,  601,   87,   87,   88,   88,
116672 /*   140 */    88,   88,  186,   86,   86,   86,   86,   85,   85,   84,
116673 /*   150 */    84,   84,   83,  330,  306,  594,  594,  142,  328,  327,
116674 /*   160 */   484,  249,  344,  238,  635,  635,  634,  633,  585,  448,
116675 /*   170 */   526,  525,  229,  388,    1,  394,  450,  584,  449,  635,
116676 /*   180 */   635,  635,  635,  319,  395,  606,  606,  199,  157,  273,
116677 /*   190 */   382,  268,  381,  187,  635,  635,  634,  633,  311,  555,
116678 /*   200 */   266,  593,  593,  266,  347,  588,   89,   90,   80,  600,
116679 /*   210 */   599,  601,  601,   87,   87,   88,   88,   88,   88,  478,
116680 /*   220 */    86,   86,   86,   86,   85,   85,   84,   84,   84,   83,
116681 /*   230 */   330,  306,  272,  536,  634,  633,  146,  610,  197,  310,
116682 /*   240 */   575,  182,  482,  271,  379,  376,  375,  506,   21,  634,
116683 /*   250 */   633,  634,  633,  635,  635,  374,  611,  574,  548,  440,
116684 /*   260 */   111,  563,  606,  606,  634,  633,  324,  479,  608,  608,
116685 /*   270 */   608,  300,  435,  573,  119,  407,  210,  162,  562,  883,
116686 /*   280 */   592,  592,  306,   89,   90,   80,  600,  599,  601,  601,
116687 /*   290 */    87,   87,   88,   88,   88,   88,  506,   86,   86,   86,
116688 /*   300 */    86,   85,   85,   84,   84,   84,   83,  330,  620,  111,
116689 /*   310 */   635,  635,  361,  606,  606,  358,  249,  349,  248,  433,
116690 /*   320 */   243,  479,  586,  634,  633,  195,  611,   93,  119,  221,
116691 /*   330 */   575,  497,  534,  534,   89,   90,   80,  600,  599,  601,
116692 /*   340 */   601,   87,   87,   88,   88,   88,   88,  574,   86,   86,
116693 /*   350 */    86,   86,   85,   85,   84,   84,   84,   83,  330,  306,
116694 /*   360 */    77,  429,  638,  573,  589,  530,  240,  230,  242,  105,
116695 /*   370 */   249,  349,  248,  515,  588,  208,  460,  529,  564,  173,
116696 /*   380 */   634,  633,  970,  144,  430,    2,  424,  228,  380,  557,
116697 /*   390 */   606,  606,  190,  153,  159,  158,  514,   51,  632,  631,
116698 /*   400 */   630,   71,  536,  432,  954,  196,  610,  954,  614,   45,
116699 /*   410 */    18,   89,   90,   80,  600,  599,  601,  601,   87,   87,
116700 /*   420 */    88,   88,   88,   88,  261,   86,   86,   86,   86,   85,
116701 /*   430 */    85,   84,   84,   84,   83,  330,  306,  608,  608,  608,
116702 /*   440 */   542,  424,  402,  385,  241,  506,  451,  320,  211,  543,
116703 /*   450 */   164,  436,  386,  293,  451,  587,  108,  496,  111,  334,
116704 /*   460 */   391,  591,  424,  614,   27,  452,  453,  606,  606,   72,
116705 /*   470 */   257,   70,  259,  452,  339,  342,  564,  582,   68,  415,
116706 /*   480 */   469,  328,  327,   62,  614,   45,  110,  393,   89,   90,
116707 /*   490 */    80,  600,  599,  601,  601,   87,   87,   88,   88,   88,
116708 /*   500 */    88,  152,   86,   86,   86,   86,   85,   85,   84,   84,
116709 /*   510 */    84,   83,  330,  306,  110,  499,  520,  538,  402,  389,
116710 /*   520 */   424,  110,  566,  500,  593,  593,  454,   82,   79,  165,
116711 /*   530 */   424,  591,  384,  564,  340,  615,  188,  162,  424,  350,
116712 /*   540 */   616,  424,  614,   44,  606,  606,  445,  582,  300,  434,
116713 /*   550 */   151,   19,  614,    9,  568,  580,  348,  615,  469,  567,
116714 /*   560 */   614,   26,  616,  614,   45,   89,   90,   80,  600,  599,
116715 /*   570 */   601,  601,   87,   87,   88,   88,   88,   88,  411,   86,
116716 /*   580 */    86,   86,   86,   85,   85,   84,   84,   84,   83,  330,
116717 /*   590 */   306,  579,  110,  578,  521,  282,  433,  398,  400,  255,
116718 /*   600 */   486,   82,   79,  165,  487,  164,   82,   79,  165,  488,
116719 /*   610 */   488,  364,  387,  424,  544,  544,  509,  350,  362,  155,
116720 /*   620 */   191,  606,  606,  559,  642,  640,  333,   82,   79,  165,
116721 /*   630 */   305,  564,  507,  312,  357,  614,   45,  329,  596,  595,
116722 /*   640 */   194,  337,   89,   90,   80,  600,  599,  601,  601,   87,
116723 /*   650 */    87,   88,   88,   88,   88,  424,   86,   86,   86,   86,
116724 /*   660 */    85,   85,   84,   84,   84,   83,  330,  306,   20,  323,
116725 /*   670 */   150,  263,  211,  543,  421,  596,  595,  614,   22,  424,
116726 /*   680 */   193,  424,  284,  424,  391,  424,  509,  424,  577,  424,
116727 /*   690 */   186,  335,  424,  559,  424,  313,  120,  546,  606,  606,
116728 /*   700 */    67,  614,   47,  614,   50,  614,   48,  614,  100,  614,
116729 /*   710 */    99,  614,  101,  576,  614,  102,  614,  109,  326,   89,
116730 /*   720 */    90,   80,  600,  599,  601,  601,   87,   87,   88,   88,
116731 /*   730 */    88,   88,  424,   86,   86,   86,   86,   85,   85,   84,
116732 /*   740 */    84,   84,   83,  330,  306,  424,  311,  424,  585,   54,
116733 /*   750 */   424,  516,  517,  590,  614,  112,  424,  584,  424,  572,
116734 /*   760 */   424,  195,  424,  571,  424,   67,  424,  614,   94,  614,
116735 /*   770 */    98,  424,  614,   97,  264,  606,  606,  195,  614,   46,
116736 /*   780 */   614,   96,  614,   30,  614,   49,  614,  115,  614,  114,
116737 /*   790 */   418,  229,  388,  614,  113,  306,   89,   90,   80,  600,
116738 /*   800 */   599,  601,  601,   87,   87,   88,   88,   88,   88,  424,
116739 /*   810 */    86,   86,   86,   86,   85,   85,   84,   84,   84,   83,
116740 /*   820 */   330,  119,  424,  590,  110,  372,  606,  606,  195,   53,
116741 /*   830 */   250,  614,   29,  195,  472,  438,  729,  190,  302,  498,
116742 /*   840 */    14,  523,  641,    2,  614,   43,  306,   89,   90,   80,
116743 /*   850 */   600,  599,  601,  601,   87,   87,   88,   88,   88,   88,
116744 /*   860 */   424,   86,   86,   86,   86,   85,   85,   84,   84,   84,
116745 /*   870 */    83,  330,  424,  613,  964,  964,  354,  606,  606,  420,
116746 /*   880 */   312,   64,  614,   42,  391,  355,  283,  437,  301,  255,
116747 /*   890 */   414,  410,  495,  492,  614,   28,  471,  306,   89,   90,
116748 /*   900 */    80,  600,  599,  601,  601,   87,   87,   88,   88,   88,
116749 /*   910 */    88,  424,   86,   86,   86,   86,   85,   85,   84,   84,
116750 /*   920 */    84,   83,  330,  424,  110,  110,  110,  110,  606,  606,
116751 /*   930 */   110,  254,   13,  614,   41,  532,  531,  283,  481,  531,
116752 /*   940 */   457,  284,  119,  561,  356,  614,   40,  284,  306,   89,
116753 /*   950 */    78,   80,  600,  599,  601,  601,   87,   87,   88,   88,
116754 /*   960 */    88,   88,  424,   86,   86,   86,   86,   85,   85,   84,
116755 /*   970 */    84,   84,   83,  330,  110,  424,  341,  220,  555,  606,
116756 /*   980 */   606,  351,  555,  318,  614,   95,  413,  255,   83,  330,
116757 /*   990 */   284,  284,  255,  640,  333,  356,  255,  614,   39,  306,
116758 /*  1000 */   356,   90,   80,  600,  599,  601,  601,   87,   87,   88,
116759 /*  1010 */    88,   88,   88,  424,   86,   86,   86,   86,   85,   85,
116760 /*  1020 */    84,   84,   84,   83,  330,  424,  317,  316,  141,  465,
116761 /*  1030 */   606,  606,  219,  619,  463,  614,   10,  417,  462,  255,
116762 /*  1040 */   189,  510,  553,  351,  207,  363,  161,  614,   38,  315,
116763 /*  1050 */   218,  255,  255,   80,  600,  599,  601,  601,   87,   87,
116764 /*  1060 */    88,   88,   88,   88,  424,   86,   86,   86,   86,   85,
116765 /*  1070 */    85,   84,   84,   84,   83,  330,   76,  419,  255,    3,
116766 /*  1080 */   878,  461,  424,  247,  331,  331,  614,   37,  217,   76,
116767 /*  1090 */   419,  390,    3,  216,  215,  422,    4,  331,  331,  424,
116768 /*  1100 */   547,   12,  424,  545,  614,   36,  424,  541,  422,  424,
116769 /*  1110 */   540,  424,  214,  424,  408,  424,  539,  403,  605,  605,
116770 /*  1120 */   237,  614,   25,  119,  614,   24,  588,  408,  614,   45,
116771 /*  1130 */   118,  614,   35,  614,   34,  614,   33,  614,   23,  588,
116772 /*  1140 */    60,  223,  603,  602,  513,  378,   73,   74,  140,  139,
116773 /*  1150 */   424,  110,  265,   75,  426,  425,   59,  424,  610,   73,
116774 /*  1160 */    74,  549,  402,  404,  424,  373,   75,  426,  425,  604,
116775 /*  1170 */   138,  610,  614,   11,  392,   76,  419,  181,    3,  614,
116776 /*  1180 */    32,  271,  369,  331,  331,  493,  614,   31,  149,  608,
116777 /*  1190 */   608,  608,  607,   15,  422,  365,  614,    8,  137,  489,
116778 /*  1200 */   136,  190,  608,  608,  608,  607,   15,  485,  176,  135,
116779 /*  1210 */     7,  252,  477,  408,  174,  133,  175,  474,   57,   56,
116780 /*  1220 */   132,  130,  119,   76,  419,  588,    3,  468,  245,  464,
116781 /*  1230 */   171,  331,  331,  125,  123,  456,  447,  122,  446,  104,
116782 /*  1240 */   336,  231,  422,  166,  154,   73,   74,  332,  116,  431,
116783 /*  1250 */   121,  309,   75,  426,  425,  222,  106,  610,  308,  637,
116784 /*  1260 */   204,  408,  629,  627,  628,    6,  200,  428,  427,  290,
116785 /*  1270 */   203,  622,  201,  588,   62,   63,  289,   66,  419,  399,
116786 /*  1280 */     3,  401,  288,   92,  143,  331,  331,  287,  608,  608,
116787 /*  1290 */   608,  607,   15,   73,   74,  227,  422,  325,   69,  416,
116788 /*  1300 */    75,  426,  425,  612,  412,  610,  192,   61,  569,  209,
116789 /*  1310 */   396,  226,  278,  225,  383,  408,  527,  558,  276,  533,
116790 /*  1320 */   552,  528,  321,  523,  370,  508,  180,  588,  494,  179,
116791 /*  1330 */   366,  117,  253,  269,  522,  503,  608,  608,  608,  607,
116792 /*  1340 */    15,  551,  502,   58,  274,  524,  178,   73,   74,  304,
116793 /*  1350 */   501,  368,  303,  206,   75,  426,  425,  491,  360,  610,
116794 /*  1360 */   213,  177,  483,  131,  345,  298,  297,  296,  202,  294,
116795 /*  1370 */   480,  490,  466,  134,  172,  129,  444,  346,  470,  128,
116796 /*  1380 */   314,  459,  103,  127,  126,  148,  124,  167,  443,  235,
116797 /*  1390 */   608,  608,  608,  607,   15,  442,  439,  623,  234,  299,
116798 /*  1400 */   145,  583,  291,  377,  581,  160,  119,  156,  270,  636,
116799 /*  1410 */   971,  169,  279,  626,  520,  625,  473,  624,  170,  621,
116800 /*  1420 */   618,  119,  168,   55,  409,  423,  537,  609,  286,  285,
116801 /*  1430 */   405,  570,  560,  556,    5,   52,  458,  554,  147,  267,
116802 /*  1440 */   519,  504,  518,  406,  262,  239,  260,  512,  343,  511,
116803 /*  1450 */   258,  353,  565,  256,  224,  251,  359,  277,  275,  476,
116804 /*  1460 */   475,  246,  352,  244,  467,  455,  236,  233,  232,  307,
116805 /*  1470 */   441,  281,  205,  163,  397,  280,  535,  505,  330,  617,
116806 /*  1480 */   971,  971,  971,  971,  367,  971,  971,  971,  971,  971,
116807 /*  1490 */   971,  971,  971,  971,  971,  971,  338,
116808};
116809static const YYCODETYPE yy_lookahead[] = {
116810 /*     0 */    19,   22,   22,   23,    1,   24,   26,   15,   27,   80,
116811 /*    10 */    81,   82,   83,   84,   85,   86,   87,   88,   89,   90,
116812 /*    20 */    91,   92,   93,   94,   95,  108,  109,  110,   27,   28,
116813 /*    30 */    23,   50,   51,   80,   81,   82,   83,  122,   85,   86,
116814 /*    40 */    87,   88,   89,   90,   91,   92,   93,   94,   95,   22,
116815 /*    50 */    70,   23,   71,   72,   73,   74,   75,   76,   77,   78,
116816 /*    60 */    79,   80,   81,   82,   83,  122,   85,   86,   87,   88,
116817 /*    70 */    89,   90,   91,   92,   93,   94,   95,   19,   97,   91,
116818 /*    80 */    92,   93,   94,   95,   26,   85,   86,   87,   88,   89,
116819 /*    90 */    90,   91,   92,   93,   94,   95,   27,   28,   97,   98,
116820 /*   100 */    99,  122,  211,  102,  103,  104,   79,   19,   50,   51,
116821 /*   110 */    19,  122,   59,   55,  113,  224,  225,  226,   89,   90,
116822 /*   120 */    91,   92,   93,   94,   95,   23,   27,   28,   26,   71,
116823 /*   130 */    72,   73,   74,   75,   76,   77,   78,   79,   80,   81,
116824 /*   140 */    82,   83,   51,   85,   86,   87,   88,   89,   90,   91,
116825 /*   150 */    92,   93,   94,   95,   19,  132,  133,   58,   89,   90,
116826 /*   160 */    21,  108,  109,  110,   27,   28,   97,   98,   33,  100,
116827 /*   170 */     7,    8,  119,  120,   22,   19,  107,   42,  109,   27,
116828 /*   180 */    28,   27,   28,   95,   28,   50,   51,   99,  100,  101,
116829 /*   190 */   102,  103,  104,  105,   27,   28,   97,   98,  107,  152,
116830 /*   200 */   112,  132,  133,  112,   65,   69,   71,   72,   73,   74,
116831 /*   210 */    75,   76,   77,   78,   79,   80,   81,   82,   83,   11,
116832 /*   220 */    85,   86,   87,   88,   89,   90,   91,   92,   93,   94,
116833 /*   230 */    95,   19,  101,   97,   97,   98,   24,  101,  122,  157,
116834 /*   240 */    12,   99,  103,  112,  102,  103,  104,  152,   22,   97,
116835 /*   250 */    98,   97,   98,   27,   28,  113,   27,   29,   91,  164,
116836 /*   260 */   165,  124,   50,   51,   97,   98,  219,   59,  132,  133,
116837 /*   270 */   134,   22,   23,   45,   66,   47,  212,  213,  124,  140,
116838 /*   280 */   132,  133,   19,   71,   72,   73,   74,   75,   76,   77,
116839 /*   290 */    78,   79,   80,   81,   82,   83,  152,   85,   86,   87,
116840 /*   300 */    88,   89,   90,   91,   92,   93,   94,   95,  164,  165,
116841 /*   310 */    27,   28,  230,   50,   51,  233,  108,  109,  110,   70,
116842 /*   320 */    16,   59,   23,   97,   98,   26,   97,   22,   66,  185,
116843 /*   330 */    12,  187,   27,   28,   71,   72,   73,   74,   75,   76,
116844 /*   340 */    77,   78,   79,   80,   81,   82,   83,   29,   85,   86,
116845 /*   350 */    87,   88,   89,   90,   91,   92,   93,   94,   95,   19,
116846 /*   360 */    22,  148,  149,   45,   23,   47,   62,  154,   64,  156,
116847 /*   370 */   108,  109,  110,   37,   69,   23,  163,   59,   26,   26,
116848 /*   380 */    97,   98,  144,  145,  146,  147,  152,  200,   52,   23,
116849 /*   390 */    50,   51,   26,   22,   89,   90,   60,  210,    7,    8,
116850 /*   400 */     9,  138,   97,   22,   23,   26,  101,   26,  174,  175,
116851 /*   410 */   197,   71,   72,   73,   74,   75,   76,   77,   78,   79,
116852 /*   420 */    80,   81,   82,   83,   16,   85,   86,   87,   88,   89,
116853 /*   430 */    90,   91,   92,   93,   94,   95,   19,  132,  133,  134,
116854 /*   440 */    23,  152,  208,  209,  140,  152,  152,  111,  195,  196,
116855 /*   450 */    98,   70,  163,  160,  152,   23,   22,  164,  165,  246,
116856 /*   460 */   207,   27,  152,  174,  175,  171,  172,   50,   51,  137,
116857 /*   470 */    62,  139,   64,  171,  172,  222,  124,   27,  138,   24,
116858 /*   480 */   163,   89,   90,  130,  174,  175,  197,  163,   71,   72,
116859 /*   490 */    73,   74,   75,   76,   77,   78,   79,   80,   81,   82,
116860 /*   500 */    83,   22,   85,   86,   87,   88,   89,   90,   91,   92,
116861 /*   510 */    93,   94,   95,   19,  197,  181,  182,   23,  208,  209,
116862 /*   520 */   152,  197,   26,  189,  132,  133,  232,  224,  225,  226,
116863 /*   530 */   152,   97,   91,   26,  232,  116,  212,  213,  152,  222,
116864 /*   540 */   121,  152,  174,  175,   50,   51,  243,   97,   22,   23,
116865 /*   550 */    22,  234,  174,  175,  177,   23,  239,  116,  163,  177,
116866 /*   560 */   174,  175,  121,  174,  175,   71,   72,   73,   74,   75,
116867 /*   570 */    76,   77,   78,   79,   80,   81,   82,   83,   24,   85,
116868 /*   580 */    86,   87,   88,   89,   90,   91,   92,   93,   94,   95,
116869 /*   590 */    19,   23,  197,   11,   23,  227,   70,  208,  220,  152,
116870 /*   600 */    31,  224,  225,  226,   35,   98,  224,  225,  226,  108,
116871 /*   610 */   109,  110,  115,  152,  117,  118,   27,  222,   49,  123,
116872 /*   620 */    24,   50,   51,   27,    0,    1,    2,  224,  225,  226,
116873 /*   630 */   166,  124,  168,  169,  239,  174,  175,  170,  171,  172,
116874 /*   640 */    22,  194,   71,   72,   73,   74,   75,   76,   77,   78,
116875 /*   650 */    79,   80,   81,   82,   83,  152,   85,   86,   87,   88,
116876 /*   660 */    89,   90,   91,   92,   93,   94,   95,   19,   22,  208,
116877 /*   670 */    24,   23,  195,  196,  170,  171,  172,  174,  175,  152,
116878 /*   680 */    26,  152,  152,  152,  207,  152,   97,  152,   23,  152,
116879 /*   690 */    51,  244,  152,   97,  152,  247,  248,   23,   50,   51,
116880 /*   700 */    26,  174,  175,  174,  175,  174,  175,  174,  175,  174,
116881 /*   710 */   175,  174,  175,   23,  174,  175,  174,  175,  188,   71,
116882 /*   720 */    72,   73,   74,   75,   76,   77,   78,   79,   80,   81,
116883 /*   730 */    82,   83,  152,   85,   86,   87,   88,   89,   90,   91,
116884 /*   740 */    92,   93,   94,   95,   19,  152,  107,  152,   33,   24,
116885 /*   750 */   152,  100,  101,   27,  174,  175,  152,   42,  152,   23,
116886 /*   760 */   152,   26,  152,   23,  152,   26,  152,  174,  175,  174,
116887 /*   770 */   175,  152,  174,  175,   23,   50,   51,   26,  174,  175,
116888 /*   780 */   174,  175,  174,  175,  174,  175,  174,  175,  174,  175,
116889 /*   790 */   163,  119,  120,  174,  175,   19,   71,   72,   73,   74,
116890 /*   800 */    75,   76,   77,   78,   79,   80,   81,   82,   83,  152,
116891 /*   810 */    85,   86,   87,   88,   89,   90,   91,   92,   93,   94,
116892 /*   820 */    95,   66,  152,   97,  197,   23,   50,   51,   26,   53,
116893 /*   830 */    23,  174,  175,   26,   23,   23,   23,   26,   26,   26,
116894 /*   840 */    36,  106,  146,  147,  174,  175,   19,   71,   72,   73,
116895 /*   850 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
116896 /*   860 */   152,   85,   86,   87,   88,   89,   90,   91,   92,   93,
116897 /*   870 */    94,   95,  152,  196,  119,  120,   19,   50,   51,  168,
116898 /*   880 */   169,   26,  174,  175,  207,   28,  152,  249,  250,  152,
116899 /*   890 */   163,  163,  163,  163,  174,  175,  163,   19,   71,   72,
116900 /*   900 */    73,   74,   75,   76,   77,   78,   79,   80,   81,   82,
116901 /*   910 */    83,  152,   85,   86,   87,   88,   89,   90,   91,   92,
116902 /*   920 */    93,   94,   95,  152,  197,  197,  197,  197,   50,   51,
116903 /*   930 */   197,  194,   36,  174,  175,  191,  192,  152,  191,  192,
116904 /*   940 */   163,  152,   66,  124,  152,  174,  175,  152,   19,   71,
116905 /*   950 */    72,   73,   74,   75,   76,   77,   78,   79,   80,   81,
116906 /*   960 */    82,   83,  152,   85,   86,   87,   88,   89,   90,   91,
116907 /*   970 */    92,   93,   94,   95,  197,  152,  100,  188,  152,   50,
116908 /*   980 */    51,  152,  152,  188,  174,  175,  252,  152,   94,   95,
116909 /*   990 */   152,  152,  152,    1,    2,  152,  152,  174,  175,   19,
116910 /*  1000 */   152,   72,   73,   74,   75,   76,   77,   78,   79,   80,
116911 /*  1010 */    81,   82,   83,  152,   85,   86,   87,   88,   89,   90,
116912 /*  1020 */    91,   92,   93,   94,   95,  152,  188,  188,   22,  194,
116913 /*  1030 */    50,   51,  240,  173,  194,  174,  175,  252,  194,  152,
116914 /*  1040 */    36,  181,   28,  152,   23,  219,  122,  174,  175,  219,
116915 /*  1050 */   221,  152,  152,   73,   74,   75,   76,   77,   78,   79,
116916 /*  1060 */    80,   81,   82,   83,  152,   85,   86,   87,   88,   89,
116917 /*  1070 */    90,   91,   92,   93,   94,   95,   19,   20,  152,   22,
116918 /*  1080 */    23,  194,  152,  240,   27,   28,  174,  175,  240,   19,
116919 /*  1090 */    20,   26,   22,  194,  194,   38,   22,   27,   28,  152,
116920 /*  1100 */    23,   22,  152,  116,  174,  175,  152,   23,   38,  152,
116921 /*  1110 */    23,  152,  221,  152,   57,  152,   23,  163,   50,   51,
116922 /*  1120 */   194,  174,  175,   66,  174,  175,   69,   57,  174,  175,
116923 /*  1130 */    40,  174,  175,  174,  175,  174,  175,  174,  175,   69,
116924 /*  1140 */    22,   53,   74,   75,   30,   53,   89,   90,   22,   22,
116925 /*  1150 */   152,  197,   23,   96,   97,   98,   22,  152,  101,   89,
116926 /*  1160 */    90,   91,  208,  209,  152,   53,   96,   97,   98,  101,
116927 /*  1170 */    22,  101,  174,  175,  152,   19,   20,  105,   22,  174,
116928 /*  1180 */   175,  112,   19,   27,   28,   20,  174,  175,   24,  132,
116929 /*  1190 */   133,  134,  135,  136,   38,   44,  174,  175,  107,   61,
116930 /*  1200 */    54,   26,  132,  133,  134,  135,  136,   54,  107,   22,
116931 /*  1210 */     5,  140,    1,   57,   36,  111,  122,   28,   79,   79,
116932 /*  1220 */   131,  123,   66,   19,   20,   69,   22,    1,   16,   20,
116933 /*  1230 */   125,   27,   28,  123,  111,  120,   23,  131,   23,   16,
116934 /*  1240 */    68,  142,   38,   15,   22,   89,   90,    3,  167,    4,
116935 /*  1250 */   248,  251,   96,   97,   98,  180,  180,  101,  251,  151,
116936 /*  1260 */     6,   57,  151,   13,  151,   26,   25,  151,  161,  202,
116937 /*  1270 */   153,  162,  153,   69,  130,  128,  203,   19,   20,  127,
116938 /*  1280 */    22,  126,  204,  129,   22,   27,   28,  205,  132,  133,
116939 /*  1290 */   134,  135,  136,   89,   90,  231,   38,   95,  137,  179,
116940 /*  1300 */    96,   97,   98,  206,  179,  101,  122,  107,  159,  159,
116941 /*  1310 */   125,  231,  216,  228,  107,   57,  184,  217,  216,  176,
116942 /*  1320 */   217,  176,   48,  106,   18,  184,  158,   69,  159,  158,
116943 /*  1330 */    46,   71,  237,  176,  176,  176,  132,  133,  134,  135,
116944 /*  1340 */   136,  217,  176,  137,  216,  178,  158,   89,   90,  179,
116945 /*  1350 */   176,  159,  179,  159,   96,   97,   98,  159,  159,  101,
116946 /*  1360 */     5,  158,  202,   22,   18,   10,   11,   12,   13,   14,
116947 /*  1370 */   190,  238,   17,  190,  158,  193,   41,  159,  202,  193,
116948 /*  1380 */   159,  202,  245,  193,  193,  223,  190,   32,  159,   34,
116949 /*  1390 */   132,  133,  134,  135,  136,  159,   39,  155,   43,  150,
116950 /*  1400 */   223,  177,  201,  178,  177,  186,   66,  199,  177,  152,
116951 /*  1410 */   253,   56,  215,  152,  182,  152,  202,  152,   63,  152,
116952 /*  1420 */   152,   66,   67,  242,  229,  152,  174,  152,  152,  152,
116953 /*  1430 */   152,  152,  152,  152,  199,  242,  202,  152,  198,  152,
116954 /*  1440 */   152,  152,  183,  192,  152,  215,  152,  183,  215,  183,
116955 /*  1450 */   152,  241,  214,  152,  211,  152,  152,  211,  211,  152,
116956 /*  1460 */   152,  241,  152,  152,  152,  152,  152,  152,  152,  114,
116957 /*  1470 */   152,  152,  235,  152,  152,  152,  174,  187,   95,  174,
116958 /*  1480 */   253,  253,  253,  253,  236,  253,  253,  253,  253,  253,
116959 /*  1490 */   253,  253,  253,  253,  253,  253,  141,
116960};
116961#define YY_SHIFT_USE_DFLT (-86)
116962#define YY_SHIFT_COUNT (429)
116963#define YY_SHIFT_MIN   (-85)
116964#define YY_SHIFT_MAX   (1383)
116965static const short yy_shift_ofst[] = {
116966 /*     0 */   992, 1057, 1355, 1156, 1204, 1204,    1,  262,  -19,  135,
116967 /*    10 */   135,  776, 1204, 1204, 1204, 1204,   69,   69,   53,  208,
116968 /*    20 */   283,  755,   58,  725,  648,  571,  494,  417,  340,  263,
116969 /*    30 */   212,  827,  827,  827,  827,  827,  827,  827,  827,  827,
116970 /*    40 */   827,  827,  827,  827,  827,  827,  878,  827,  929,  980,
116971 /*    50 */   980, 1070, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
116972 /*    60 */  1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
116973 /*    70 */  1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
116974 /*    80 */  1258, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
116975 /*    90 */  1204, 1204, 1204, 1204,  -71,  -47,  -47,  -47,  -47,  -47,
116976 /*   100 */     0,   29,  -12,  283,  283,  139,   91,  392,  392,  894,
116977 /*   110 */   672,  726, 1383,  -86,  -86,  -86,   88,  318,  318,   99,
116978 /*   120 */   381,  -20,  283,  283,  283,  283,  283,  283,  283,  283,
116979 /*   130 */   283,  283,  283,  283,  283,  283,  283,  283,  283,  283,
116980 /*   140 */   283,  283,  283,  283,  624,  876,  726,  672, 1340, 1340,
116981 /*   150 */  1340, 1340, 1340, 1340,  -86,  -86,  -86,  305,  136,  136,
116982 /*   160 */   142,  167,  226,  154,  137,  152,  283,  283,  283,  283,
116983 /*   170 */   283,  283,  283,  283,  283,  283,  283,  283,  283,  283,
116984 /*   180 */   283,  283,  283,  336,  336,  336,  283,  283,  352,  283,
116985 /*   190 */   283,  283,  283,  283,  228,  283,  283,  283,  283,  283,
116986 /*   200 */   283,  283,  283,  283,  283,  501,  569,  596,  596,  596,
116987 /*   210 */   507,  497,  441,  391,  353,  156,  156,  857,  353,  857,
116988 /*   220 */   735,  813,  639,  715,  156,  332,  715,  715,  496,  419,
116989 /*   230 */   646, 1357, 1184, 1184, 1335, 1335, 1184, 1341, 1260, 1144,
116990 /*   240 */  1346, 1346, 1346, 1346, 1184, 1306, 1144, 1341, 1260, 1260,
116991 /*   250 */  1144, 1184, 1306, 1206, 1284, 1184, 1184, 1306, 1184, 1306,
116992 /*   260 */  1184, 1306, 1262, 1207, 1207, 1207, 1274, 1262, 1207, 1217,
116993 /*   270 */  1207, 1274, 1207, 1207, 1185, 1200, 1185, 1200, 1185, 1200,
116994 /*   280 */  1184, 1184, 1161, 1262, 1202, 1202, 1262, 1154, 1155, 1147,
116995 /*   290 */  1152, 1144, 1241, 1239, 1250, 1250, 1254, 1254, 1254, 1254,
116996 /*   300 */   -86,  -86,  -86,  -86,  -86,  -86, 1068,  304,  526,  249,
116997 /*   310 */   408,  -83,  434,  812,   27,  811,  807,  802,  751,  589,
116998 /*   320 */   651,  163,  131,  674,  366,  450,  299,  148,   23,  102,
116999 /*   330 */   229,  -21, 1245, 1244, 1222, 1099, 1228, 1172, 1223, 1215,
117000 /*   340 */  1213, 1115, 1106, 1123, 1110, 1209, 1105, 1212, 1226, 1098,
117001 /*   350 */  1089, 1140, 1139, 1104, 1189, 1178, 1094, 1211, 1205, 1187,
117002 /*   360 */  1101, 1071, 1153, 1175, 1146, 1138, 1151, 1091, 1164, 1165,
117003 /*   370 */  1163, 1069, 1072, 1148, 1112, 1134, 1127, 1129, 1126, 1092,
117004 /*   380 */  1114, 1118, 1088, 1090, 1093, 1087, 1084,  987, 1079, 1077,
117005 /*   390 */  1074, 1065,  924, 1021, 1014, 1004, 1006,  819,  739,  896,
117006 /*   400 */   855,  804,  739,  740,  736,  690,  654,  665,  618,  582,
117007 /*   410 */   568,  528,  554,  379,  532,  479,  455,  379,  432,  371,
117008 /*   420 */   341,   28,  338,  116,  -11,  -57,  -85,    7,   -8,    3,
117009};
117010#define YY_REDUCE_USE_DFLT (-110)
117011#define YY_REDUCE_COUNT (305)
117012#define YY_REDUCE_MIN   (-109)
117013#define YY_REDUCE_MAX   (1323)
117014static const short yy_reduce_ofst[] = {
117015 /*     0 */   238,  954,  213,  289,  310,  234,  144,  317, -109,  382,
117016 /*    10 */   377,  303,  461,  389,  378,  368,  302,  294,  253,  395,
117017 /*    20 */   293,  324,  403,  403,  403,  403,  403,  403,  403,  403,
117018 /*    30 */   403,  403,  403,  403,  403,  403,  403,  403,  403,  403,
117019 /*    40 */   403,  403,  403,  403,  403,  403,  403,  403,  403,  403,
117020 /*    50 */   403, 1022, 1012, 1005,  998,  963,  961,  959,  957,  950,
117021 /*    60 */   947,  930,  912,  873,  861,  823,  810,  771,  759,  720,
117022 /*    70 */   708,  670,  657,  619,  614,  612,  610,  608,  606,  604,
117023 /*    80 */   598,  595,  593,  580,  542,  540,  537,  535,  533,  531,
117024 /*    90 */   529,  527,  503,  386,  403,  403,  403,  403,  403,  403,
117025 /*   100 */   403,  403,  403,   95,  447,   82,  334,  504,  467,  403,
117026 /*   110 */   477,  464,  403,  403,  403,  403,  860,  747,  744,  785,
117027 /*   120 */   638,  638,  926,  891,  900,  899,  887,  844,  840,  835,
117028 /*   130 */   848,  830,  843,  829,  792,  839,  826,  737,  838,  795,
117029 /*   140 */   789,   47,  734,  530,  696,  777,  711,  677,  733,  730,
117030 /*   150 */   729,  728,  727,  627,  448,   64,  187, 1305, 1302, 1252,
117031 /*   160 */  1290, 1273, 1323, 1322, 1321, 1319, 1318, 1316, 1315, 1314,
117032 /*   170 */  1313, 1312, 1311, 1310, 1308, 1307, 1304, 1303, 1301, 1298,
117033 /*   180 */  1294, 1292, 1289, 1266, 1264, 1259, 1288, 1287, 1238, 1285,
117034 /*   190 */  1281, 1280, 1279, 1278, 1251, 1277, 1276, 1275, 1273, 1268,
117035 /*   200 */  1267, 1265, 1263, 1261, 1257, 1248, 1237, 1247, 1246, 1243,
117036 /*   210 */  1238, 1240, 1235, 1249, 1234, 1233, 1230, 1220, 1214, 1210,
117037 /*   220 */  1225, 1219, 1232, 1231, 1197, 1195, 1227, 1224, 1201, 1208,
117038 /*   230 */  1242, 1137, 1236, 1229, 1193, 1181, 1221, 1177, 1196, 1179,
117039 /*   240 */  1191, 1190, 1186, 1182, 1218, 1216, 1176, 1162, 1183, 1180,
117040 /*   250 */  1160, 1199, 1203, 1133, 1095, 1198, 1194, 1188, 1192, 1171,
117041 /*   260 */  1169, 1168, 1173, 1174, 1166, 1159, 1141, 1170, 1158, 1167,
117042 /*   270 */  1157, 1132, 1145, 1143, 1124, 1128, 1103, 1102, 1100, 1096,
117043 /*   280 */  1150, 1149, 1085, 1125, 1080, 1064, 1120, 1097, 1082, 1078,
117044 /*   290 */  1073, 1067, 1109, 1107, 1119, 1117, 1116, 1113, 1111, 1108,
117045 /*   300 */  1007, 1000, 1002, 1076, 1075, 1081,
117046};
117047static const YYACTIONTYPE yy_default[] = {
117048 /*     0 */   647,  964,  964,  964,  878,  878,  969,  964,  774,  802,
117049 /*    10 */   802,  938,  969,  969,  969,  876,  969,  969,  969,  964,
117050 /*    20 */   969,  778,  808,  969,  969,  969,  969,  969,  969,  969,
117051 /*    30 */   969,  937,  939,  816,  815,  918,  789,  813,  806,  810,
117052 /*    40 */   879,  872,  873,  871,  875,  880,  969,  809,  841,  856,
117053 /*    50 */   840,  969,  969,  969,  969,  969,  969,  969,  969,  969,
117054 /*    60 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
117055 /*    70 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
117056 /*    80 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
117057 /*    90 */   969,  969,  969,  969,  850,  855,  862,  854,  851,  843,
117058 /*   100 */   842,  844,  845,  969,  969,  673,  739,  969,  969,  846,
117059 /*   110 */   969,  685,  847,  859,  858,  857,  680,  969,  969,  969,
117060 /*   120 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
117061 /*   130 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
117062 /*   140 */   969,  969,  969,  969,  647,  964,  969,  969,  964,  964,
117063 /*   150 */   964,  964,  964,  964,  956,  778,  768,  969,  969,  969,
117064 /*   160 */   969,  969,  969,  969,  969,  969,  969,  944,  942,  969,
117065 /*   170 */   891,  969,  969,  969,  969,  969,  969,  969,  969,  969,
117066 /*   180 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
117067 /*   190 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
117068 /*   200 */   969,  969,  969,  969,  653,  969,  911,  774,  774,  774,
117069 /*   210 */   776,  754,  766,  655,  812,  791,  791,  923,  812,  923,
117070 /*   220 */   710,  733,  707,  802,  791,  874,  802,  802,  775,  766,
117071 /*   230 */   969,  949,  782,  782,  941,  941,  782,  821,  743,  812,
117072 /*   240 */   750,  750,  750,  750,  782,  670,  812,  821,  743,  743,
117073 /*   250 */   812,  782,  670,  917,  915,  782,  782,  670,  782,  670,
117074 /*   260 */   782,  670,  884,  741,  741,  741,  725,  884,  741,  710,
117075 /*   270 */   741,  725,  741,  741,  795,  790,  795,  790,  795,  790,
117076 /*   280 */   782,  782,  969,  884,  888,  888,  884,  807,  796,  805,
117077 /*   290 */   803,  812,  676,  728,  663,  663,  652,  652,  652,  652,
117078 /*   300 */   961,  961,  956,  712,  712,  695,  969,  969,  969,  969,
117079 /*   310 */   969,  969,  687,  969,  893,  969,  969,  969,  969,  969,
117080 /*   320 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
117081 /*   330 */   969,  828,  969,  648,  951,  969,  969,  948,  969,  969,
117082 /*   340 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
117083 /*   350 */   969,  969,  969,  969,  969,  969,  921,  969,  969,  969,
117084 /*   360 */   969,  969,  969,  914,  913,  969,  969,  969,  969,  969,
117085 /*   370 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
117086 /*   380 */   969,  969,  969,  969,  969,  969,  969,  757,  969,  969,
117087 /*   390 */   969,  761,  969,  969,  969,  969,  969,  969,  804,  969,
117088 /*   400 */   797,  969,  877,  969,  969,  969,  969,  969,  969,  969,
117089 /*   410 */   969,  969,  969,  966,  969,  969,  969,  965,  969,  969,
117090 /*   420 */   969,  969,  969,  830,  969,  829,  833,  969,  661,  969,
117091 /*   430 */   644,  649,  960,  963,  962,  959,  958,  957,  952,  950,
117092 /*   440 */   947,  946,  945,  943,  940,  936,  897,  895,  902,  901,
117093 /*   450 */   900,  899,  898,  896,  894,  892,  818,  817,  814,  811,
117094 /*   460 */   753,  935,  890,  752,  749,  748,  669,  953,  920,  929,
117095 /*   470 */   928,  927,  822,  926,  925,  924,  922,  919,  906,  820,
117096 /*   480 */   819,  744,  882,  881,  672,  910,  909,  908,  912,  916,
117097 /*   490 */   907,  784,  751,  671,  668,  675,  679,  731,  732,  740,
117098 /*   500 */   738,  737,  736,  735,  734,  730,  681,  686,  724,  709,
117099 /*   510 */   708,  717,  716,  722,  721,  720,  719,  718,  715,  714,
117100 /*   520 */   713,  706,  705,  711,  704,  727,  726,  723,  703,  747,
117101 /*   530 */   746,  745,  742,  702,  701,  700,  833,  699,  698,  838,
117102 /*   540 */   837,  866,  826,  755,  759,  758,  762,  763,  771,  770,
117103 /*   550 */   769,  780,  781,  793,  792,  824,  823,  794,  779,  773,
117104 /*   560 */   772,  788,  787,  786,  785,  777,  767,  799,  798,  868,
117105 /*   570 */   783,  867,  865,  934,  933,  932,  931,  930,  870,  967,
117106 /*   580 */   968,  887,  889,  886,  801,  800,  885,  869,  839,  836,
117107 /*   590 */   690,  691,  905,  904,  903,  693,  692,  689,  688,  863,
117108 /*   600 */   860,  852,  864,  861,  853,  849,  848,  834,  832,  831,
117109 /*   610 */   827,  835,  760,  756,  825,  765,  764,  697,  696,  694,
117110 /*   620 */   678,  677,  674,  667,  665,  664,  666,  662,  660,  659,
117111 /*   630 */   658,  657,  656,  684,  683,  682,  654,  651,  650,  646,
117112 /*   640 */   645,  643,
117113};
117114
117115/* The next table maps tokens into fallback tokens.  If a construct
117116** like the following:
117117**
117118**      %fallback ID X Y Z.
117119**
117120** appears in the grammar, then ID becomes a fallback token for X, Y,
117121** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
117122** but it does not parse, the type of the token is changed to ID and
117123** the parse is retried before an error is thrown.
117124*/
117125#ifdef YYFALLBACK
117126static const YYCODETYPE yyFallback[] = {
117127    0,  /*          $ => nothing */
117128    0,  /*       SEMI => nothing */
117129   27,  /*    EXPLAIN => ID */
117130   27,  /*      QUERY => ID */
117131   27,  /*       PLAN => ID */
117132   27,  /*      BEGIN => ID */
117133    0,  /* TRANSACTION => nothing */
117134   27,  /*   DEFERRED => ID */
117135   27,  /*  IMMEDIATE => ID */
117136   27,  /*  EXCLUSIVE => ID */
117137    0,  /*     COMMIT => nothing */
117138   27,  /*        END => ID */
117139   27,  /*   ROLLBACK => ID */
117140   27,  /*  SAVEPOINT => ID */
117141   27,  /*    RELEASE => ID */
117142    0,  /*         TO => nothing */
117143    0,  /*      TABLE => nothing */
117144    0,  /*     CREATE => nothing */
117145   27,  /*         IF => ID */
117146    0,  /*        NOT => nothing */
117147    0,  /*     EXISTS => nothing */
117148   27,  /*       TEMP => ID */
117149    0,  /*         LP => nothing */
117150    0,  /*         RP => nothing */
117151    0,  /*         AS => nothing */
117152   27,  /*    WITHOUT => ID */
117153    0,  /*      COMMA => nothing */
117154    0,  /*         ID => nothing */
117155    0,  /*    INDEXED => nothing */
117156   27,  /*      ABORT => ID */
117157   27,  /*     ACTION => ID */
117158   27,  /*      AFTER => ID */
117159   27,  /*    ANALYZE => ID */
117160   27,  /*        ASC => ID */
117161   27,  /*     ATTACH => ID */
117162   27,  /*     BEFORE => ID */
117163   27,  /*         BY => ID */
117164   27,  /*    CASCADE => ID */
117165   27,  /*       CAST => ID */
117166   27,  /*   COLUMNKW => ID */
117167   27,  /*   CONFLICT => ID */
117168   27,  /*   DATABASE => ID */
117169   27,  /*       DESC => ID */
117170   27,  /*     DETACH => ID */
117171   27,  /*       EACH => ID */
117172   27,  /*       FAIL => ID */
117173   27,  /*        FOR => ID */
117174   27,  /*     IGNORE => ID */
117175   27,  /*  INITIALLY => ID */
117176   27,  /*    INSTEAD => ID */
117177   27,  /*    LIKE_KW => ID */
117178   27,  /*      MATCH => ID */
117179   27,  /*         NO => ID */
117180   27,  /*        KEY => ID */
117181   27,  /*         OF => ID */
117182   27,  /*     OFFSET => ID */
117183   27,  /*     PRAGMA => ID */
117184   27,  /*      RAISE => ID */
117185   27,  /*  RECURSIVE => ID */
117186   27,  /*    REPLACE => ID */
117187   27,  /*   RESTRICT => ID */
117188   27,  /*        ROW => ID */
117189   27,  /*    TRIGGER => ID */
117190   27,  /*     VACUUM => ID */
117191   27,  /*       VIEW => ID */
117192   27,  /*    VIRTUAL => ID */
117193   27,  /*       WITH => ID */
117194   27,  /*    REINDEX => ID */
117195   27,  /*     RENAME => ID */
117196   27,  /*   CTIME_KW => ID */
117197};
117198#endif /* YYFALLBACK */
117199
117200/* The following structure represents a single element of the
117201** parser's stack.  Information stored includes:
117202**
117203**   +  The state number for the parser at this level of the stack.
117204**
117205**   +  The value of the token stored at this level of the stack.
117206**      (In other words, the "major" token.)
117207**
117208**   +  The semantic value stored at this level of the stack.  This is
117209**      the information used by the action routines in the grammar.
117210**      It is sometimes called the "minor" token.
117211*/
117212struct yyStackEntry {
117213  YYACTIONTYPE stateno;  /* The state-number */
117214  YYCODETYPE major;      /* The major token value.  This is the code
117215                         ** number for the token at this stack level */
117216  YYMINORTYPE minor;     /* The user-supplied minor token value.  This
117217                         ** is the value of the token  */
117218};
117219typedef struct yyStackEntry yyStackEntry;
117220
117221/* The state of the parser is completely contained in an instance of
117222** the following structure */
117223struct yyParser {
117224  int yyidx;                    /* Index of top element in stack */
117225#ifdef YYTRACKMAXSTACKDEPTH
117226  int yyidxMax;                 /* Maximum value of yyidx */
117227#endif
117228  int yyerrcnt;                 /* Shifts left before out of the error */
117229  sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
117230#if YYSTACKDEPTH<=0
117231  int yystksz;                  /* Current side of the stack */
117232  yyStackEntry *yystack;        /* The parser's stack */
117233#else
117234  yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
117235#endif
117236};
117237typedef struct yyParser yyParser;
117238
117239#ifndef NDEBUG
117240/* #include <stdio.h> */
117241static FILE *yyTraceFILE = 0;
117242static char *yyTracePrompt = 0;
117243#endif /* NDEBUG */
117244
117245#ifndef NDEBUG
117246/*
117247** Turn parser tracing on by giving a stream to which to write the trace
117248** and a prompt to preface each trace message.  Tracing is turned off
117249** by making either argument NULL
117250**
117251** Inputs:
117252** <ul>
117253** <li> A FILE* to which trace output should be written.
117254**      If NULL, then tracing is turned off.
117255** <li> A prefix string written at the beginning of every
117256**      line of trace output.  If NULL, then tracing is
117257**      turned off.
117258** </ul>
117259**
117260** Outputs:
117261** None.
117262*/
117263SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
117264  yyTraceFILE = TraceFILE;
117265  yyTracePrompt = zTracePrompt;
117266  if( yyTraceFILE==0 ) yyTracePrompt = 0;
117267  else if( yyTracePrompt==0 ) yyTraceFILE = 0;
117268}
117269#endif /* NDEBUG */
117270
117271#ifndef NDEBUG
117272/* For tracing shifts, the names of all terminals and nonterminals
117273** are required.  The following table supplies these names */
117274static const char *const yyTokenName[] = {
117275  "$",             "SEMI",          "EXPLAIN",       "QUERY",
117276  "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",
117277  "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",
117278  "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",
117279  "TABLE",         "CREATE",        "IF",            "NOT",
117280  "EXISTS",        "TEMP",          "LP",            "RP",
117281  "AS",            "WITHOUT",       "COMMA",         "ID",
117282  "INDEXED",       "ABORT",         "ACTION",        "AFTER",
117283  "ANALYZE",       "ASC",           "ATTACH",        "BEFORE",
117284  "BY",            "CASCADE",       "CAST",          "COLUMNKW",
117285  "CONFLICT",      "DATABASE",      "DESC",          "DETACH",
117286  "EACH",          "FAIL",          "FOR",           "IGNORE",
117287  "INITIALLY",     "INSTEAD",       "LIKE_KW",       "MATCH",
117288  "NO",            "KEY",           "OF",            "OFFSET",
117289  "PRAGMA",        "RAISE",         "RECURSIVE",     "REPLACE",
117290  "RESTRICT",      "ROW",           "TRIGGER",       "VACUUM",
117291  "VIEW",          "VIRTUAL",       "WITH",          "REINDEX",
117292  "RENAME",        "CTIME_KW",      "ANY",           "OR",
117293  "AND",           "IS",            "BETWEEN",       "IN",
117294  "ISNULL",        "NOTNULL",       "NE",            "EQ",
117295  "GT",            "LE",            "LT",            "GE",
117296  "ESCAPE",        "BITAND",        "BITOR",         "LSHIFT",
117297  "RSHIFT",        "PLUS",          "MINUS",         "STAR",
117298  "SLASH",         "REM",           "CONCAT",        "COLLATE",
117299  "BITNOT",        "STRING",        "JOIN_KW",       "CONSTRAINT",
117300  "DEFAULT",       "NULL",          "PRIMARY",       "UNIQUE",
117301  "CHECK",         "REFERENCES",    "AUTOINCR",      "ON",
117302  "INSERT",        "DELETE",        "UPDATE",        "SET",
117303  "DEFERRABLE",    "FOREIGN",       "DROP",          "UNION",
117304  "ALL",           "EXCEPT",        "INTERSECT",     "SELECT",
117305  "VALUES",        "DISTINCT",      "DOT",           "FROM",
117306  "JOIN",          "USING",         "ORDER",         "GROUP",
117307  "HAVING",        "LIMIT",         "WHERE",         "INTO",
117308  "INTEGER",       "FLOAT",         "BLOB",          "VARIABLE",
117309  "CASE",          "WHEN",          "THEN",          "ELSE",
117310  "INDEX",         "ALTER",         "ADD",           "error",
117311  "input",         "cmdlist",       "ecmd",          "explain",
117312  "cmdx",          "cmd",           "transtype",     "trans_opt",
117313  "nm",            "savepoint_opt",  "create_table",  "create_table_args",
117314  "createkw",      "temp",          "ifnotexists",   "dbnm",
117315  "columnlist",    "conslist_opt",  "table_options",  "select",
117316  "column",        "columnid",      "type",          "carglist",
117317  "typetoken",     "typename",      "signed",        "plus_num",
117318  "minus_num",     "ccons",         "term",          "expr",
117319  "onconf",        "sortorder",     "autoinc",       "idxlist_opt",
117320  "refargs",       "defer_subclause",  "refarg",        "refact",
117321  "init_deferred_pred_opt",  "conslist",      "tconscomma",    "tcons",
117322  "idxlist",       "defer_subclause_opt",  "orconf",        "resolvetype",
117323  "raisetype",     "ifexists",      "fullname",      "selectnowith",
117324  "oneselect",     "with",          "multiselect_op",  "distinct",
117325  "selcollist",    "from",          "where_opt",     "groupby_opt",
117326  "having_opt",    "orderby_opt",   "limit_opt",     "values",
117327  "nexprlist",     "exprlist",      "sclp",          "as",
117328  "seltablist",    "stl_prefix",    "joinop",        "indexed_opt",
117329  "on_opt",        "using_opt",     "joinop2",       "idlist",
117330  "sortlist",      "setlist",       "insert_cmd",    "inscollist_opt",
117331  "likeop",        "between_op",    "in_op",         "case_operand",
117332  "case_exprlist",  "case_else",     "uniqueflag",    "collate",
117333  "nmnum",         "trigger_decl",  "trigger_cmd_list",  "trigger_time",
117334  "trigger_event",  "foreach_clause",  "when_clause",   "trigger_cmd",
117335  "trnm",          "tridxby",       "database_kw_opt",  "key_opt",
117336  "add_column_fullname",  "kwcolumn_opt",  "create_vtab",   "vtabarglist",
117337  "vtabarg",       "vtabargtoken",  "lp",            "anylist",
117338  "wqlist",
117339};
117340#endif /* NDEBUG */
117341
117342#ifndef NDEBUG
117343/* For tracing reduce actions, the names of all rules are required.
117344*/
117345static const char *const yyRuleName[] = {
117346 /*   0 */ "input ::= cmdlist",
117347 /*   1 */ "cmdlist ::= cmdlist ecmd",
117348 /*   2 */ "cmdlist ::= ecmd",
117349 /*   3 */ "ecmd ::= SEMI",
117350 /*   4 */ "ecmd ::= explain cmdx SEMI",
117351 /*   5 */ "explain ::=",
117352 /*   6 */ "explain ::= EXPLAIN",
117353 /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
117354 /*   8 */ "cmdx ::= cmd",
117355 /*   9 */ "cmd ::= BEGIN transtype trans_opt",
117356 /*  10 */ "trans_opt ::=",
117357 /*  11 */ "trans_opt ::= TRANSACTION",
117358 /*  12 */ "trans_opt ::= TRANSACTION nm",
117359 /*  13 */ "transtype ::=",
117360 /*  14 */ "transtype ::= DEFERRED",
117361 /*  15 */ "transtype ::= IMMEDIATE",
117362 /*  16 */ "transtype ::= EXCLUSIVE",
117363 /*  17 */ "cmd ::= COMMIT trans_opt",
117364 /*  18 */ "cmd ::= END trans_opt",
117365 /*  19 */ "cmd ::= ROLLBACK trans_opt",
117366 /*  20 */ "savepoint_opt ::= SAVEPOINT",
117367 /*  21 */ "savepoint_opt ::=",
117368 /*  22 */ "cmd ::= SAVEPOINT nm",
117369 /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
117370 /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
117371 /*  25 */ "cmd ::= create_table create_table_args",
117372 /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
117373 /*  27 */ "createkw ::= CREATE",
117374 /*  28 */ "ifnotexists ::=",
117375 /*  29 */ "ifnotexists ::= IF NOT EXISTS",
117376 /*  30 */ "temp ::= TEMP",
117377 /*  31 */ "temp ::=",
117378 /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
117379 /*  33 */ "create_table_args ::= AS select",
117380 /*  34 */ "table_options ::=",
117381 /*  35 */ "table_options ::= WITHOUT nm",
117382 /*  36 */ "columnlist ::= columnlist COMMA column",
117383 /*  37 */ "columnlist ::= column",
117384 /*  38 */ "column ::= columnid type carglist",
117385 /*  39 */ "columnid ::= nm",
117386 /*  40 */ "nm ::= ID|INDEXED",
117387 /*  41 */ "nm ::= STRING",
117388 /*  42 */ "nm ::= JOIN_KW",
117389 /*  43 */ "type ::=",
117390 /*  44 */ "type ::= typetoken",
117391 /*  45 */ "typetoken ::= typename",
117392 /*  46 */ "typetoken ::= typename LP signed RP",
117393 /*  47 */ "typetoken ::= typename LP signed COMMA signed RP",
117394 /*  48 */ "typename ::= ID|STRING",
117395 /*  49 */ "typename ::= typename ID|STRING",
117396 /*  50 */ "signed ::= plus_num",
117397 /*  51 */ "signed ::= minus_num",
117398 /*  52 */ "carglist ::= carglist ccons",
117399 /*  53 */ "carglist ::=",
117400 /*  54 */ "ccons ::= CONSTRAINT nm",
117401 /*  55 */ "ccons ::= DEFAULT term",
117402 /*  56 */ "ccons ::= DEFAULT LP expr RP",
117403 /*  57 */ "ccons ::= DEFAULT PLUS term",
117404 /*  58 */ "ccons ::= DEFAULT MINUS term",
117405 /*  59 */ "ccons ::= DEFAULT ID|INDEXED",
117406 /*  60 */ "ccons ::= NULL onconf",
117407 /*  61 */ "ccons ::= NOT NULL onconf",
117408 /*  62 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
117409 /*  63 */ "ccons ::= UNIQUE onconf",
117410 /*  64 */ "ccons ::= CHECK LP expr RP",
117411 /*  65 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
117412 /*  66 */ "ccons ::= defer_subclause",
117413 /*  67 */ "ccons ::= COLLATE ID|STRING",
117414 /*  68 */ "autoinc ::=",
117415 /*  69 */ "autoinc ::= AUTOINCR",
117416 /*  70 */ "refargs ::=",
117417 /*  71 */ "refargs ::= refargs refarg",
117418 /*  72 */ "refarg ::= MATCH nm",
117419 /*  73 */ "refarg ::= ON INSERT refact",
117420 /*  74 */ "refarg ::= ON DELETE refact",
117421 /*  75 */ "refarg ::= ON UPDATE refact",
117422 /*  76 */ "refact ::= SET NULL",
117423 /*  77 */ "refact ::= SET DEFAULT",
117424 /*  78 */ "refact ::= CASCADE",
117425 /*  79 */ "refact ::= RESTRICT",
117426 /*  80 */ "refact ::= NO ACTION",
117427 /*  81 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
117428 /*  82 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
117429 /*  83 */ "init_deferred_pred_opt ::=",
117430 /*  84 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
117431 /*  85 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
117432 /*  86 */ "conslist_opt ::=",
117433 /*  87 */ "conslist_opt ::= COMMA conslist",
117434 /*  88 */ "conslist ::= conslist tconscomma tcons",
117435 /*  89 */ "conslist ::= tcons",
117436 /*  90 */ "tconscomma ::= COMMA",
117437 /*  91 */ "tconscomma ::=",
117438 /*  92 */ "tcons ::= CONSTRAINT nm",
117439 /*  93 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
117440 /*  94 */ "tcons ::= UNIQUE LP idxlist RP onconf",
117441 /*  95 */ "tcons ::= CHECK LP expr RP onconf",
117442 /*  96 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
117443 /*  97 */ "defer_subclause_opt ::=",
117444 /*  98 */ "defer_subclause_opt ::= defer_subclause",
117445 /*  99 */ "onconf ::=",
117446 /* 100 */ "onconf ::= ON CONFLICT resolvetype",
117447 /* 101 */ "orconf ::=",
117448 /* 102 */ "orconf ::= OR resolvetype",
117449 /* 103 */ "resolvetype ::= raisetype",
117450 /* 104 */ "resolvetype ::= IGNORE",
117451 /* 105 */ "resolvetype ::= REPLACE",
117452 /* 106 */ "cmd ::= DROP TABLE ifexists fullname",
117453 /* 107 */ "ifexists ::= IF EXISTS",
117454 /* 108 */ "ifexists ::=",
117455 /* 109 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
117456 /* 110 */ "cmd ::= DROP VIEW ifexists fullname",
117457 /* 111 */ "cmd ::= select",
117458 /* 112 */ "select ::= with selectnowith",
117459 /* 113 */ "selectnowith ::= oneselect",
117460 /* 114 */ "selectnowith ::= selectnowith multiselect_op oneselect",
117461 /* 115 */ "multiselect_op ::= UNION",
117462 /* 116 */ "multiselect_op ::= UNION ALL",
117463 /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
117464 /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
117465 /* 119 */ "oneselect ::= values",
117466 /* 120 */ "values ::= VALUES LP nexprlist RP",
117467 /* 121 */ "values ::= values COMMA LP exprlist RP",
117468 /* 122 */ "distinct ::= DISTINCT",
117469 /* 123 */ "distinct ::= ALL",
117470 /* 124 */ "distinct ::=",
117471 /* 125 */ "sclp ::= selcollist COMMA",
117472 /* 126 */ "sclp ::=",
117473 /* 127 */ "selcollist ::= sclp expr as",
117474 /* 128 */ "selcollist ::= sclp STAR",
117475 /* 129 */ "selcollist ::= sclp nm DOT STAR",
117476 /* 130 */ "as ::= AS nm",
117477 /* 131 */ "as ::= ID|STRING",
117478 /* 132 */ "as ::=",
117479 /* 133 */ "from ::=",
117480 /* 134 */ "from ::= FROM seltablist",
117481 /* 135 */ "stl_prefix ::= seltablist joinop",
117482 /* 136 */ "stl_prefix ::=",
117483 /* 137 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
117484 /* 138 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
117485 /* 139 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
117486 /* 140 */ "dbnm ::=",
117487 /* 141 */ "dbnm ::= DOT nm",
117488 /* 142 */ "fullname ::= nm dbnm",
117489 /* 143 */ "joinop ::= COMMA|JOIN",
117490 /* 144 */ "joinop ::= JOIN_KW JOIN",
117491 /* 145 */ "joinop ::= JOIN_KW nm JOIN",
117492 /* 146 */ "joinop ::= JOIN_KW nm nm JOIN",
117493 /* 147 */ "on_opt ::= ON expr",
117494 /* 148 */ "on_opt ::=",
117495 /* 149 */ "indexed_opt ::=",
117496 /* 150 */ "indexed_opt ::= INDEXED BY nm",
117497 /* 151 */ "indexed_opt ::= NOT INDEXED",
117498 /* 152 */ "using_opt ::= USING LP idlist RP",
117499 /* 153 */ "using_opt ::=",
117500 /* 154 */ "orderby_opt ::=",
117501 /* 155 */ "orderby_opt ::= ORDER BY sortlist",
117502 /* 156 */ "sortlist ::= sortlist COMMA expr sortorder",
117503 /* 157 */ "sortlist ::= expr sortorder",
117504 /* 158 */ "sortorder ::= ASC",
117505 /* 159 */ "sortorder ::= DESC",
117506 /* 160 */ "sortorder ::=",
117507 /* 161 */ "groupby_opt ::=",
117508 /* 162 */ "groupby_opt ::= GROUP BY nexprlist",
117509 /* 163 */ "having_opt ::=",
117510 /* 164 */ "having_opt ::= HAVING expr",
117511 /* 165 */ "limit_opt ::=",
117512 /* 166 */ "limit_opt ::= LIMIT expr",
117513 /* 167 */ "limit_opt ::= LIMIT expr OFFSET expr",
117514 /* 168 */ "limit_opt ::= LIMIT expr COMMA expr",
117515 /* 169 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
117516 /* 170 */ "where_opt ::=",
117517 /* 171 */ "where_opt ::= WHERE expr",
117518 /* 172 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
117519 /* 173 */ "setlist ::= setlist COMMA nm EQ expr",
117520 /* 174 */ "setlist ::= nm EQ expr",
117521 /* 175 */ "cmd ::= with insert_cmd INTO fullname inscollist_opt select",
117522 /* 176 */ "cmd ::= with insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
117523 /* 177 */ "insert_cmd ::= INSERT orconf",
117524 /* 178 */ "insert_cmd ::= REPLACE",
117525 /* 179 */ "inscollist_opt ::=",
117526 /* 180 */ "inscollist_opt ::= LP idlist RP",
117527 /* 181 */ "idlist ::= idlist COMMA nm",
117528 /* 182 */ "idlist ::= nm",
117529 /* 183 */ "expr ::= term",
117530 /* 184 */ "expr ::= LP expr RP",
117531 /* 185 */ "term ::= NULL",
117532 /* 186 */ "expr ::= ID|INDEXED",
117533 /* 187 */ "expr ::= JOIN_KW",
117534 /* 188 */ "expr ::= nm DOT nm",
117535 /* 189 */ "expr ::= nm DOT nm DOT nm",
117536 /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
117537 /* 191 */ "term ::= STRING",
117538 /* 192 */ "expr ::= VARIABLE",
117539 /* 193 */ "expr ::= expr COLLATE ID|STRING",
117540 /* 194 */ "expr ::= CAST LP expr AS typetoken RP",
117541 /* 195 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
117542 /* 196 */ "expr ::= ID|INDEXED LP STAR RP",
117543 /* 197 */ "term ::= CTIME_KW",
117544 /* 198 */ "expr ::= expr AND expr",
117545 /* 199 */ "expr ::= expr OR expr",
117546 /* 200 */ "expr ::= expr LT|GT|GE|LE expr",
117547 /* 201 */ "expr ::= expr EQ|NE expr",
117548 /* 202 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
117549 /* 203 */ "expr ::= expr PLUS|MINUS expr",
117550 /* 204 */ "expr ::= expr STAR|SLASH|REM expr",
117551 /* 205 */ "expr ::= expr CONCAT expr",
117552 /* 206 */ "likeop ::= LIKE_KW|MATCH",
117553 /* 207 */ "likeop ::= NOT LIKE_KW|MATCH",
117554 /* 208 */ "expr ::= expr likeop expr",
117555 /* 209 */ "expr ::= expr likeop expr ESCAPE expr",
117556 /* 210 */ "expr ::= expr ISNULL|NOTNULL",
117557 /* 211 */ "expr ::= expr NOT NULL",
117558 /* 212 */ "expr ::= expr IS expr",
117559 /* 213 */ "expr ::= expr IS NOT expr",
117560 /* 214 */ "expr ::= NOT expr",
117561 /* 215 */ "expr ::= BITNOT expr",
117562 /* 216 */ "expr ::= MINUS expr",
117563 /* 217 */ "expr ::= PLUS expr",
117564 /* 218 */ "between_op ::= BETWEEN",
117565 /* 219 */ "between_op ::= NOT BETWEEN",
117566 /* 220 */ "expr ::= expr between_op expr AND expr",
117567 /* 221 */ "in_op ::= IN",
117568 /* 222 */ "in_op ::= NOT IN",
117569 /* 223 */ "expr ::= expr in_op LP exprlist RP",
117570 /* 224 */ "expr ::= LP select RP",
117571 /* 225 */ "expr ::= expr in_op LP select RP",
117572 /* 226 */ "expr ::= expr in_op nm dbnm",
117573 /* 227 */ "expr ::= EXISTS LP select RP",
117574 /* 228 */ "expr ::= CASE case_operand case_exprlist case_else END",
117575 /* 229 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
117576 /* 230 */ "case_exprlist ::= WHEN expr THEN expr",
117577 /* 231 */ "case_else ::= ELSE expr",
117578 /* 232 */ "case_else ::=",
117579 /* 233 */ "case_operand ::= expr",
117580 /* 234 */ "case_operand ::=",
117581 /* 235 */ "exprlist ::= nexprlist",
117582 /* 236 */ "exprlist ::=",
117583 /* 237 */ "nexprlist ::= nexprlist COMMA expr",
117584 /* 238 */ "nexprlist ::= expr",
117585 /* 239 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt",
117586 /* 240 */ "uniqueflag ::= UNIQUE",
117587 /* 241 */ "uniqueflag ::=",
117588 /* 242 */ "idxlist_opt ::=",
117589 /* 243 */ "idxlist_opt ::= LP idxlist RP",
117590 /* 244 */ "idxlist ::= idxlist COMMA nm collate sortorder",
117591 /* 245 */ "idxlist ::= nm collate sortorder",
117592 /* 246 */ "collate ::=",
117593 /* 247 */ "collate ::= COLLATE ID|STRING",
117594 /* 248 */ "cmd ::= DROP INDEX ifexists fullname",
117595 /* 249 */ "cmd ::= VACUUM",
117596 /* 250 */ "cmd ::= VACUUM nm",
117597 /* 251 */ "cmd ::= PRAGMA nm dbnm",
117598 /* 252 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
117599 /* 253 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
117600 /* 254 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
117601 /* 255 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
117602 /* 256 */ "nmnum ::= plus_num",
117603 /* 257 */ "nmnum ::= nm",
117604 /* 258 */ "nmnum ::= ON",
117605 /* 259 */ "nmnum ::= DELETE",
117606 /* 260 */ "nmnum ::= DEFAULT",
117607 /* 261 */ "plus_num ::= PLUS INTEGER|FLOAT",
117608 /* 262 */ "plus_num ::= INTEGER|FLOAT",
117609 /* 263 */ "minus_num ::= MINUS INTEGER|FLOAT",
117610 /* 264 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
117611 /* 265 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
117612 /* 266 */ "trigger_time ::= BEFORE",
117613 /* 267 */ "trigger_time ::= AFTER",
117614 /* 268 */ "trigger_time ::= INSTEAD OF",
117615 /* 269 */ "trigger_time ::=",
117616 /* 270 */ "trigger_event ::= DELETE|INSERT",
117617 /* 271 */ "trigger_event ::= UPDATE",
117618 /* 272 */ "trigger_event ::= UPDATE OF idlist",
117619 /* 273 */ "foreach_clause ::=",
117620 /* 274 */ "foreach_clause ::= FOR EACH ROW",
117621 /* 275 */ "when_clause ::=",
117622 /* 276 */ "when_clause ::= WHEN expr",
117623 /* 277 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
117624 /* 278 */ "trigger_cmd_list ::= trigger_cmd SEMI",
117625 /* 279 */ "trnm ::= nm",
117626 /* 280 */ "trnm ::= nm DOT nm",
117627 /* 281 */ "tridxby ::=",
117628 /* 282 */ "tridxby ::= INDEXED BY nm",
117629 /* 283 */ "tridxby ::= NOT INDEXED",
117630 /* 284 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
117631 /* 285 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
117632 /* 286 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
117633 /* 287 */ "trigger_cmd ::= select",
117634 /* 288 */ "expr ::= RAISE LP IGNORE RP",
117635 /* 289 */ "expr ::= RAISE LP raisetype COMMA nm RP",
117636 /* 290 */ "raisetype ::= ROLLBACK",
117637 /* 291 */ "raisetype ::= ABORT",
117638 /* 292 */ "raisetype ::= FAIL",
117639 /* 293 */ "cmd ::= DROP TRIGGER ifexists fullname",
117640 /* 294 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
117641 /* 295 */ "cmd ::= DETACH database_kw_opt expr",
117642 /* 296 */ "key_opt ::=",
117643 /* 297 */ "key_opt ::= KEY expr",
117644 /* 298 */ "database_kw_opt ::= DATABASE",
117645 /* 299 */ "database_kw_opt ::=",
117646 /* 300 */ "cmd ::= REINDEX",
117647 /* 301 */ "cmd ::= REINDEX nm dbnm",
117648 /* 302 */ "cmd ::= ANALYZE",
117649 /* 303 */ "cmd ::= ANALYZE nm dbnm",
117650 /* 304 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
117651 /* 305 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
117652 /* 306 */ "add_column_fullname ::= fullname",
117653 /* 307 */ "kwcolumn_opt ::=",
117654 /* 308 */ "kwcolumn_opt ::= COLUMNKW",
117655 /* 309 */ "cmd ::= create_vtab",
117656 /* 310 */ "cmd ::= create_vtab LP vtabarglist RP",
117657 /* 311 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
117658 /* 312 */ "vtabarglist ::= vtabarg",
117659 /* 313 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
117660 /* 314 */ "vtabarg ::=",
117661 /* 315 */ "vtabarg ::= vtabarg vtabargtoken",
117662 /* 316 */ "vtabargtoken ::= ANY",
117663 /* 317 */ "vtabargtoken ::= lp anylist RP",
117664 /* 318 */ "lp ::= LP",
117665 /* 319 */ "anylist ::=",
117666 /* 320 */ "anylist ::= anylist LP anylist RP",
117667 /* 321 */ "anylist ::= anylist ANY",
117668 /* 322 */ "with ::=",
117669 /* 323 */ "with ::= WITH wqlist",
117670 /* 324 */ "with ::= WITH RECURSIVE wqlist",
117671 /* 325 */ "wqlist ::= nm idxlist_opt AS LP select RP",
117672 /* 326 */ "wqlist ::= wqlist COMMA nm idxlist_opt AS LP select RP",
117673};
117674#endif /* NDEBUG */
117675
117676
117677#if YYSTACKDEPTH<=0
117678/*
117679** Try to increase the size of the parser stack.
117680*/
117681static void yyGrowStack(yyParser *p){
117682  int newSize;
117683  yyStackEntry *pNew;
117684
117685  newSize = p->yystksz*2 + 100;
117686  pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
117687  if( pNew ){
117688    p->yystack = pNew;
117689    p->yystksz = newSize;
117690#ifndef NDEBUG
117691    if( yyTraceFILE ){
117692      fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
117693              yyTracePrompt, p->yystksz);
117694    }
117695#endif
117696  }
117697}
117698#endif
117699
117700/*
117701** This function allocates a new parser.
117702** The only argument is a pointer to a function which works like
117703** malloc.
117704**
117705** Inputs:
117706** A pointer to the function used to allocate memory.
117707**
117708** Outputs:
117709** A pointer to a parser.  This pointer is used in subsequent calls
117710** to sqlite3Parser and sqlite3ParserFree.
117711*/
117712SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
117713  yyParser *pParser;
117714  pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
117715  if( pParser ){
117716    pParser->yyidx = -1;
117717#ifdef YYTRACKMAXSTACKDEPTH
117718    pParser->yyidxMax = 0;
117719#endif
117720#if YYSTACKDEPTH<=0
117721    pParser->yystack = NULL;
117722    pParser->yystksz = 0;
117723    yyGrowStack(pParser);
117724#endif
117725  }
117726  return pParser;
117727}
117728
117729/* The following function deletes the value associated with a
117730** symbol.  The symbol can be either a terminal or nonterminal.
117731** "yymajor" is the symbol code, and "yypminor" is a pointer to
117732** the value.
117733*/
117734static void yy_destructor(
117735  yyParser *yypParser,    /* The parser */
117736  YYCODETYPE yymajor,     /* Type code for object to destroy */
117737  YYMINORTYPE *yypminor   /* The object to be destroyed */
117738){
117739  sqlite3ParserARG_FETCH;
117740  switch( yymajor ){
117741    /* Here is inserted the actions which take place when a
117742    ** terminal or non-terminal is destroyed.  This can happen
117743    ** when the symbol is popped from the stack during a
117744    ** reduce or during error processing or when a parser is
117745    ** being destroyed before it is finished parsing.
117746    **
117747    ** Note: during a reduce, the only symbols destroyed are those
117748    ** which appear on the RHS of the rule, but which are not used
117749    ** inside the C code.
117750    */
117751    case 163: /* select */
117752    case 195: /* selectnowith */
117753    case 196: /* oneselect */
117754    case 207: /* values */
117755{
117756sqlite3SelectDelete(pParse->db, (yypminor->yy3));
117757}
117758      break;
117759    case 174: /* term */
117760    case 175: /* expr */
117761{
117762sqlite3ExprDelete(pParse->db, (yypminor->yy346).pExpr);
117763}
117764      break;
117765    case 179: /* idxlist_opt */
117766    case 188: /* idxlist */
117767    case 200: /* selcollist */
117768    case 203: /* groupby_opt */
117769    case 205: /* orderby_opt */
117770    case 208: /* nexprlist */
117771    case 209: /* exprlist */
117772    case 210: /* sclp */
117773    case 220: /* sortlist */
117774    case 221: /* setlist */
117775    case 228: /* case_exprlist */
117776{
117777sqlite3ExprListDelete(pParse->db, (yypminor->yy14));
117778}
117779      break;
117780    case 194: /* fullname */
117781    case 201: /* from */
117782    case 212: /* seltablist */
117783    case 213: /* stl_prefix */
117784{
117785sqlite3SrcListDelete(pParse->db, (yypminor->yy65));
117786}
117787      break;
117788    case 197: /* with */
117789    case 252: /* wqlist */
117790{
117791sqlite3WithDelete(pParse->db, (yypminor->yy59));
117792}
117793      break;
117794    case 202: /* where_opt */
117795    case 204: /* having_opt */
117796    case 216: /* on_opt */
117797    case 227: /* case_operand */
117798    case 229: /* case_else */
117799    case 238: /* when_clause */
117800    case 243: /* key_opt */
117801{
117802sqlite3ExprDelete(pParse->db, (yypminor->yy132));
117803}
117804      break;
117805    case 217: /* using_opt */
117806    case 219: /* idlist */
117807    case 223: /* inscollist_opt */
117808{
117809sqlite3IdListDelete(pParse->db, (yypminor->yy408));
117810}
117811      break;
117812    case 234: /* trigger_cmd_list */
117813    case 239: /* trigger_cmd */
117814{
117815sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy473));
117816}
117817      break;
117818    case 236: /* trigger_event */
117819{
117820sqlite3IdListDelete(pParse->db, (yypminor->yy378).b);
117821}
117822      break;
117823    default:  break;   /* If no destructor action specified: do nothing */
117824  }
117825}
117826
117827/*
117828** Pop the parser's stack once.
117829**
117830** If there is a destructor routine associated with the token which
117831** is popped from the stack, then call it.
117832**
117833** Return the major token number for the symbol popped.
117834*/
117835static int yy_pop_parser_stack(yyParser *pParser){
117836  YYCODETYPE yymajor;
117837  yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
117838
117839  /* There is no mechanism by which the parser stack can be popped below
117840  ** empty in SQLite.  */
117841  if( NEVER(pParser->yyidx<0) ) return 0;
117842#ifndef NDEBUG
117843  if( yyTraceFILE && pParser->yyidx>=0 ){
117844    fprintf(yyTraceFILE,"%sPopping %s\n",
117845      yyTracePrompt,
117846      yyTokenName[yytos->major]);
117847  }
117848#endif
117849  yymajor = yytos->major;
117850  yy_destructor(pParser, yymajor, &yytos->minor);
117851  pParser->yyidx--;
117852  return yymajor;
117853}
117854
117855/*
117856** Deallocate and destroy a parser.  Destructors are all called for
117857** all stack elements before shutting the parser down.
117858**
117859** Inputs:
117860** <ul>
117861** <li>  A pointer to the parser.  This should be a pointer
117862**       obtained from sqlite3ParserAlloc.
117863** <li>  A pointer to a function used to reclaim memory obtained
117864**       from malloc.
117865** </ul>
117866*/
117867SQLITE_PRIVATE void sqlite3ParserFree(
117868  void *p,                    /* The parser to be deleted */
117869  void (*freeProc)(void*)     /* Function used to reclaim memory */
117870){
117871  yyParser *pParser = (yyParser*)p;
117872  /* In SQLite, we never try to destroy a parser that was not successfully
117873  ** created in the first place. */
117874  if( NEVER(pParser==0) ) return;
117875  while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
117876#if YYSTACKDEPTH<=0
117877  free(pParser->yystack);
117878#endif
117879  (*freeProc)((void*)pParser);
117880}
117881
117882/*
117883** Return the peak depth of the stack for a parser.
117884*/
117885#ifdef YYTRACKMAXSTACKDEPTH
117886SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
117887  yyParser *pParser = (yyParser*)p;
117888  return pParser->yyidxMax;
117889}
117890#endif
117891
117892/*
117893** Find the appropriate action for a parser given the terminal
117894** look-ahead token iLookAhead.
117895**
117896** If the look-ahead token is YYNOCODE, then check to see if the action is
117897** independent of the look-ahead.  If it is, return the action, otherwise
117898** return YY_NO_ACTION.
117899*/
117900static int yy_find_shift_action(
117901  yyParser *pParser,        /* The parser */
117902  YYCODETYPE iLookAhead     /* The look-ahead token */
117903){
117904  int i;
117905  int stateno = pParser->yystack[pParser->yyidx].stateno;
117906
117907  if( stateno>YY_SHIFT_COUNT
117908   || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
117909    return yy_default[stateno];
117910  }
117911  assert( iLookAhead!=YYNOCODE );
117912  i += iLookAhead;
117913  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
117914    if( iLookAhead>0 ){
117915#ifdef YYFALLBACK
117916      YYCODETYPE iFallback;            /* Fallback token */
117917      if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
117918             && (iFallback = yyFallback[iLookAhead])!=0 ){
117919#ifndef NDEBUG
117920        if( yyTraceFILE ){
117921          fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
117922             yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
117923        }
117924#endif
117925        return yy_find_shift_action(pParser, iFallback);
117926      }
117927#endif
117928#ifdef YYWILDCARD
117929      {
117930        int j = i - iLookAhead + YYWILDCARD;
117931        if(
117932#if YY_SHIFT_MIN+YYWILDCARD<0
117933          j>=0 &&
117934#endif
117935#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
117936          j<YY_ACTTAB_COUNT &&
117937#endif
117938          yy_lookahead[j]==YYWILDCARD
117939        ){
117940#ifndef NDEBUG
117941          if( yyTraceFILE ){
117942            fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
117943               yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
117944          }
117945#endif /* NDEBUG */
117946          return yy_action[j];
117947        }
117948      }
117949#endif /* YYWILDCARD */
117950    }
117951    return yy_default[stateno];
117952  }else{
117953    return yy_action[i];
117954  }
117955}
117956
117957/*
117958** Find the appropriate action for a parser given the non-terminal
117959** look-ahead token iLookAhead.
117960**
117961** If the look-ahead token is YYNOCODE, then check to see if the action is
117962** independent of the look-ahead.  If it is, return the action, otherwise
117963** return YY_NO_ACTION.
117964*/
117965static int yy_find_reduce_action(
117966  int stateno,              /* Current state number */
117967  YYCODETYPE iLookAhead     /* The look-ahead token */
117968){
117969  int i;
117970#ifdef YYERRORSYMBOL
117971  if( stateno>YY_REDUCE_COUNT ){
117972    return yy_default[stateno];
117973  }
117974#else
117975  assert( stateno<=YY_REDUCE_COUNT );
117976#endif
117977  i = yy_reduce_ofst[stateno];
117978  assert( i!=YY_REDUCE_USE_DFLT );
117979  assert( iLookAhead!=YYNOCODE );
117980  i += iLookAhead;
117981#ifdef YYERRORSYMBOL
117982  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
117983    return yy_default[stateno];
117984  }
117985#else
117986  assert( i>=0 && i<YY_ACTTAB_COUNT );
117987  assert( yy_lookahead[i]==iLookAhead );
117988#endif
117989  return yy_action[i];
117990}
117991
117992/*
117993** The following routine is called if the stack overflows.
117994*/
117995static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
117996   sqlite3ParserARG_FETCH;
117997   yypParser->yyidx--;
117998#ifndef NDEBUG
117999   if( yyTraceFILE ){
118000     fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
118001   }
118002#endif
118003   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
118004   /* Here code is inserted which will execute if the parser
118005   ** stack every overflows */
118006
118007  UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
118008  sqlite3ErrorMsg(pParse, "parser stack overflow");
118009   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
118010}
118011
118012/*
118013** Perform a shift action.
118014*/
118015static void yy_shift(
118016  yyParser *yypParser,          /* The parser to be shifted */
118017  int yyNewState,               /* The new state to shift in */
118018  int yyMajor,                  /* The major token to shift in */
118019  YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
118020){
118021  yyStackEntry *yytos;
118022  yypParser->yyidx++;
118023#ifdef YYTRACKMAXSTACKDEPTH
118024  if( yypParser->yyidx>yypParser->yyidxMax ){
118025    yypParser->yyidxMax = yypParser->yyidx;
118026  }
118027#endif
118028#if YYSTACKDEPTH>0
118029  if( yypParser->yyidx>=YYSTACKDEPTH ){
118030    yyStackOverflow(yypParser, yypMinor);
118031    return;
118032  }
118033#else
118034  if( yypParser->yyidx>=yypParser->yystksz ){
118035    yyGrowStack(yypParser);
118036    if( yypParser->yyidx>=yypParser->yystksz ){
118037      yyStackOverflow(yypParser, yypMinor);
118038      return;
118039    }
118040  }
118041#endif
118042  yytos = &yypParser->yystack[yypParser->yyidx];
118043  yytos->stateno = (YYACTIONTYPE)yyNewState;
118044  yytos->major = (YYCODETYPE)yyMajor;
118045  yytos->minor = *yypMinor;
118046#ifndef NDEBUG
118047  if( yyTraceFILE && yypParser->yyidx>0 ){
118048    int i;
118049    fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
118050    fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
118051    for(i=1; i<=yypParser->yyidx; i++)
118052      fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
118053    fprintf(yyTraceFILE,"\n");
118054  }
118055#endif
118056}
118057
118058/* The following table contains information about every rule that
118059** is used during the reduce.
118060*/
118061static const struct {
118062  YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
118063  unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
118064} yyRuleInfo[] = {
118065  { 144, 1 },
118066  { 145, 2 },
118067  { 145, 1 },
118068  { 146, 1 },
118069  { 146, 3 },
118070  { 147, 0 },
118071  { 147, 1 },
118072  { 147, 3 },
118073  { 148, 1 },
118074  { 149, 3 },
118075  { 151, 0 },
118076  { 151, 1 },
118077  { 151, 2 },
118078  { 150, 0 },
118079  { 150, 1 },
118080  { 150, 1 },
118081  { 150, 1 },
118082  { 149, 2 },
118083  { 149, 2 },
118084  { 149, 2 },
118085  { 153, 1 },
118086  { 153, 0 },
118087  { 149, 2 },
118088  { 149, 3 },
118089  { 149, 5 },
118090  { 149, 2 },
118091  { 154, 6 },
118092  { 156, 1 },
118093  { 158, 0 },
118094  { 158, 3 },
118095  { 157, 1 },
118096  { 157, 0 },
118097  { 155, 5 },
118098  { 155, 2 },
118099  { 162, 0 },
118100  { 162, 2 },
118101  { 160, 3 },
118102  { 160, 1 },
118103  { 164, 3 },
118104  { 165, 1 },
118105  { 152, 1 },
118106  { 152, 1 },
118107  { 152, 1 },
118108  { 166, 0 },
118109  { 166, 1 },
118110  { 168, 1 },
118111  { 168, 4 },
118112  { 168, 6 },
118113  { 169, 1 },
118114  { 169, 2 },
118115  { 170, 1 },
118116  { 170, 1 },
118117  { 167, 2 },
118118  { 167, 0 },
118119  { 173, 2 },
118120  { 173, 2 },
118121  { 173, 4 },
118122  { 173, 3 },
118123  { 173, 3 },
118124  { 173, 2 },
118125  { 173, 2 },
118126  { 173, 3 },
118127  { 173, 5 },
118128  { 173, 2 },
118129  { 173, 4 },
118130  { 173, 4 },
118131  { 173, 1 },
118132  { 173, 2 },
118133  { 178, 0 },
118134  { 178, 1 },
118135  { 180, 0 },
118136  { 180, 2 },
118137  { 182, 2 },
118138  { 182, 3 },
118139  { 182, 3 },
118140  { 182, 3 },
118141  { 183, 2 },
118142  { 183, 2 },
118143  { 183, 1 },
118144  { 183, 1 },
118145  { 183, 2 },
118146  { 181, 3 },
118147  { 181, 2 },
118148  { 184, 0 },
118149  { 184, 2 },
118150  { 184, 2 },
118151  { 161, 0 },
118152  { 161, 2 },
118153  { 185, 3 },
118154  { 185, 1 },
118155  { 186, 1 },
118156  { 186, 0 },
118157  { 187, 2 },
118158  { 187, 7 },
118159  { 187, 5 },
118160  { 187, 5 },
118161  { 187, 10 },
118162  { 189, 0 },
118163  { 189, 1 },
118164  { 176, 0 },
118165  { 176, 3 },
118166  { 190, 0 },
118167  { 190, 2 },
118168  { 191, 1 },
118169  { 191, 1 },
118170  { 191, 1 },
118171  { 149, 4 },
118172  { 193, 2 },
118173  { 193, 0 },
118174  { 149, 8 },
118175  { 149, 4 },
118176  { 149, 1 },
118177  { 163, 2 },
118178  { 195, 1 },
118179  { 195, 3 },
118180  { 198, 1 },
118181  { 198, 2 },
118182  { 198, 1 },
118183  { 196, 9 },
118184  { 196, 1 },
118185  { 207, 4 },
118186  { 207, 5 },
118187  { 199, 1 },
118188  { 199, 1 },
118189  { 199, 0 },
118190  { 210, 2 },
118191  { 210, 0 },
118192  { 200, 3 },
118193  { 200, 2 },
118194  { 200, 4 },
118195  { 211, 2 },
118196  { 211, 1 },
118197  { 211, 0 },
118198  { 201, 0 },
118199  { 201, 2 },
118200  { 213, 2 },
118201  { 213, 0 },
118202  { 212, 7 },
118203  { 212, 7 },
118204  { 212, 7 },
118205  { 159, 0 },
118206  { 159, 2 },
118207  { 194, 2 },
118208  { 214, 1 },
118209  { 214, 2 },
118210  { 214, 3 },
118211  { 214, 4 },
118212  { 216, 2 },
118213  { 216, 0 },
118214  { 215, 0 },
118215  { 215, 3 },
118216  { 215, 2 },
118217  { 217, 4 },
118218  { 217, 0 },
118219  { 205, 0 },
118220  { 205, 3 },
118221  { 220, 4 },
118222  { 220, 2 },
118223  { 177, 1 },
118224  { 177, 1 },
118225  { 177, 0 },
118226  { 203, 0 },
118227  { 203, 3 },
118228  { 204, 0 },
118229  { 204, 2 },
118230  { 206, 0 },
118231  { 206, 2 },
118232  { 206, 4 },
118233  { 206, 4 },
118234  { 149, 6 },
118235  { 202, 0 },
118236  { 202, 2 },
118237  { 149, 8 },
118238  { 221, 5 },
118239  { 221, 3 },
118240  { 149, 6 },
118241  { 149, 7 },
118242  { 222, 2 },
118243  { 222, 1 },
118244  { 223, 0 },
118245  { 223, 3 },
118246  { 219, 3 },
118247  { 219, 1 },
118248  { 175, 1 },
118249  { 175, 3 },
118250  { 174, 1 },
118251  { 175, 1 },
118252  { 175, 1 },
118253  { 175, 3 },
118254  { 175, 5 },
118255  { 174, 1 },
118256  { 174, 1 },
118257  { 175, 1 },
118258  { 175, 3 },
118259  { 175, 6 },
118260  { 175, 5 },
118261  { 175, 4 },
118262  { 174, 1 },
118263  { 175, 3 },
118264  { 175, 3 },
118265  { 175, 3 },
118266  { 175, 3 },
118267  { 175, 3 },
118268  { 175, 3 },
118269  { 175, 3 },
118270  { 175, 3 },
118271  { 224, 1 },
118272  { 224, 2 },
118273  { 175, 3 },
118274  { 175, 5 },
118275  { 175, 2 },
118276  { 175, 3 },
118277  { 175, 3 },
118278  { 175, 4 },
118279  { 175, 2 },
118280  { 175, 2 },
118281  { 175, 2 },
118282  { 175, 2 },
118283  { 225, 1 },
118284  { 225, 2 },
118285  { 175, 5 },
118286  { 226, 1 },
118287  { 226, 2 },
118288  { 175, 5 },
118289  { 175, 3 },
118290  { 175, 5 },
118291  { 175, 4 },
118292  { 175, 4 },
118293  { 175, 5 },
118294  { 228, 5 },
118295  { 228, 4 },
118296  { 229, 2 },
118297  { 229, 0 },
118298  { 227, 1 },
118299  { 227, 0 },
118300  { 209, 1 },
118301  { 209, 0 },
118302  { 208, 3 },
118303  { 208, 1 },
118304  { 149, 12 },
118305  { 230, 1 },
118306  { 230, 0 },
118307  { 179, 0 },
118308  { 179, 3 },
118309  { 188, 5 },
118310  { 188, 3 },
118311  { 231, 0 },
118312  { 231, 2 },
118313  { 149, 4 },
118314  { 149, 1 },
118315  { 149, 2 },
118316  { 149, 3 },
118317  { 149, 5 },
118318  { 149, 6 },
118319  { 149, 5 },
118320  { 149, 6 },
118321  { 232, 1 },
118322  { 232, 1 },
118323  { 232, 1 },
118324  { 232, 1 },
118325  { 232, 1 },
118326  { 171, 2 },
118327  { 171, 1 },
118328  { 172, 2 },
118329  { 149, 5 },
118330  { 233, 11 },
118331  { 235, 1 },
118332  { 235, 1 },
118333  { 235, 2 },
118334  { 235, 0 },
118335  { 236, 1 },
118336  { 236, 1 },
118337  { 236, 3 },
118338  { 237, 0 },
118339  { 237, 3 },
118340  { 238, 0 },
118341  { 238, 2 },
118342  { 234, 3 },
118343  { 234, 2 },
118344  { 240, 1 },
118345  { 240, 3 },
118346  { 241, 0 },
118347  { 241, 3 },
118348  { 241, 2 },
118349  { 239, 7 },
118350  { 239, 5 },
118351  { 239, 5 },
118352  { 239, 1 },
118353  { 175, 4 },
118354  { 175, 6 },
118355  { 192, 1 },
118356  { 192, 1 },
118357  { 192, 1 },
118358  { 149, 4 },
118359  { 149, 6 },
118360  { 149, 3 },
118361  { 243, 0 },
118362  { 243, 2 },
118363  { 242, 1 },
118364  { 242, 0 },
118365  { 149, 1 },
118366  { 149, 3 },
118367  { 149, 1 },
118368  { 149, 3 },
118369  { 149, 6 },
118370  { 149, 6 },
118371  { 244, 1 },
118372  { 245, 0 },
118373  { 245, 1 },
118374  { 149, 1 },
118375  { 149, 4 },
118376  { 246, 8 },
118377  { 247, 1 },
118378  { 247, 3 },
118379  { 248, 0 },
118380  { 248, 2 },
118381  { 249, 1 },
118382  { 249, 3 },
118383  { 250, 1 },
118384  { 251, 0 },
118385  { 251, 4 },
118386  { 251, 2 },
118387  { 197, 0 },
118388  { 197, 2 },
118389  { 197, 3 },
118390  { 252, 6 },
118391  { 252, 8 },
118392};
118393
118394static void yy_accept(yyParser*);  /* Forward Declaration */
118395
118396/*
118397** Perform a reduce action and the shift that must immediately
118398** follow the reduce.
118399*/
118400static void yy_reduce(
118401  yyParser *yypParser,         /* The parser */
118402  int yyruleno                 /* Number of the rule by which to reduce */
118403){
118404  int yygoto;                     /* The next state */
118405  int yyact;                      /* The next action */
118406  YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
118407  yyStackEntry *yymsp;            /* The top of the parser's stack */
118408  int yysize;                     /* Amount to pop the stack */
118409  sqlite3ParserARG_FETCH;
118410  yymsp = &yypParser->yystack[yypParser->yyidx];
118411#ifndef NDEBUG
118412  if( yyTraceFILE && yyruleno>=0
118413        && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
118414    fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
118415      yyRuleName[yyruleno]);
118416  }
118417#endif /* NDEBUG */
118418
118419  /* Silence complaints from purify about yygotominor being uninitialized
118420  ** in some cases when it is copied into the stack after the following
118421  ** switch.  yygotominor is uninitialized when a rule reduces that does
118422  ** not set the value of its left-hand side nonterminal.  Leaving the
118423  ** value of the nonterminal uninitialized is utterly harmless as long
118424  ** as the value is never used.  So really the only thing this code
118425  ** accomplishes is to quieten purify.
118426  **
118427  ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
118428  ** without this code, their parser segfaults.  I'm not sure what there
118429  ** parser is doing to make this happen.  This is the second bug report
118430  ** from wireshark this week.  Clearly they are stressing Lemon in ways
118431  ** that it has not been previously stressed...  (SQLite ticket #2172)
118432  */
118433  /*memset(&yygotominor, 0, sizeof(yygotominor));*/
118434  yygotominor = yyzerominor;
118435
118436
118437  switch( yyruleno ){
118438  /* Beginning here are the reduction cases.  A typical example
118439  ** follows:
118440  **   case 0:
118441  **  #line <lineno> <grammarfile>
118442  **     { ... }           // User supplied code
118443  **  #line <lineno> <thisfile>
118444  **     break;
118445  */
118446      case 5: /* explain ::= */
118447{ sqlite3BeginParse(pParse, 0); }
118448        break;
118449      case 6: /* explain ::= EXPLAIN */
118450{ sqlite3BeginParse(pParse, 1); }
118451        break;
118452      case 7: /* explain ::= EXPLAIN QUERY PLAN */
118453{ sqlite3BeginParse(pParse, 2); }
118454        break;
118455      case 8: /* cmdx ::= cmd */
118456{ sqlite3FinishCoding(pParse); }
118457        break;
118458      case 9: /* cmd ::= BEGIN transtype trans_opt */
118459{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy328);}
118460        break;
118461      case 13: /* transtype ::= */
118462{yygotominor.yy328 = TK_DEFERRED;}
118463        break;
118464      case 14: /* transtype ::= DEFERRED */
118465      case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
118466      case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
118467      case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
118468      case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
118469{yygotominor.yy328 = yymsp[0].major;}
118470        break;
118471      case 17: /* cmd ::= COMMIT trans_opt */
118472      case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
118473{sqlite3CommitTransaction(pParse);}
118474        break;
118475      case 19: /* cmd ::= ROLLBACK trans_opt */
118476{sqlite3RollbackTransaction(pParse);}
118477        break;
118478      case 22: /* cmd ::= SAVEPOINT nm */
118479{
118480  sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
118481}
118482        break;
118483      case 23: /* cmd ::= RELEASE savepoint_opt nm */
118484{
118485  sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
118486}
118487        break;
118488      case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
118489{
118490  sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
118491}
118492        break;
118493      case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
118494{
118495   sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy328,0,0,yymsp[-2].minor.yy328);
118496}
118497        break;
118498      case 27: /* createkw ::= CREATE */
118499{
118500  pParse->db->lookaside.bEnabled = 0;
118501  yygotominor.yy0 = yymsp[0].minor.yy0;
118502}
118503        break;
118504      case 28: /* ifnotexists ::= */
118505      case 31: /* temp ::= */ yytestcase(yyruleno==31);
118506      case 68: /* autoinc ::= */ yytestcase(yyruleno==68);
118507      case 81: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==81);
118508      case 83: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==83);
118509      case 85: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==85);
118510      case 97: /* defer_subclause_opt ::= */ yytestcase(yyruleno==97);
118511      case 108: /* ifexists ::= */ yytestcase(yyruleno==108);
118512      case 218: /* between_op ::= BETWEEN */ yytestcase(yyruleno==218);
118513      case 221: /* in_op ::= IN */ yytestcase(yyruleno==221);
118514{yygotominor.yy328 = 0;}
118515        break;
118516      case 29: /* ifnotexists ::= IF NOT EXISTS */
118517      case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
118518      case 69: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==69);
118519      case 84: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==84);
118520      case 107: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==107);
118521      case 219: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==219);
118522      case 222: /* in_op ::= NOT IN */ yytestcase(yyruleno==222);
118523{yygotominor.yy328 = 1;}
118524        break;
118525      case 32: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
118526{
118527  sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy186,0);
118528}
118529        break;
118530      case 33: /* create_table_args ::= AS select */
118531{
118532  sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy3);
118533  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
118534}
118535        break;
118536      case 34: /* table_options ::= */
118537{yygotominor.yy186 = 0;}
118538        break;
118539      case 35: /* table_options ::= WITHOUT nm */
118540{
118541  if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
118542    yygotominor.yy186 = TF_WithoutRowid;
118543  }else{
118544    yygotominor.yy186 = 0;
118545    sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
118546  }
118547}
118548        break;
118549      case 38: /* column ::= columnid type carglist */
118550{
118551  yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
118552  yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
118553}
118554        break;
118555      case 39: /* columnid ::= nm */
118556{
118557  sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
118558  yygotominor.yy0 = yymsp[0].minor.yy0;
118559  pParse->constraintName.n = 0;
118560}
118561        break;
118562      case 40: /* nm ::= ID|INDEXED */
118563      case 41: /* nm ::= STRING */ yytestcase(yyruleno==41);
118564      case 42: /* nm ::= JOIN_KW */ yytestcase(yyruleno==42);
118565      case 45: /* typetoken ::= typename */ yytestcase(yyruleno==45);
118566      case 48: /* typename ::= ID|STRING */ yytestcase(yyruleno==48);
118567      case 130: /* as ::= AS nm */ yytestcase(yyruleno==130);
118568      case 131: /* as ::= ID|STRING */ yytestcase(yyruleno==131);
118569      case 141: /* dbnm ::= DOT nm */ yytestcase(yyruleno==141);
118570      case 150: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==150);
118571      case 247: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==247);
118572      case 256: /* nmnum ::= plus_num */ yytestcase(yyruleno==256);
118573      case 257: /* nmnum ::= nm */ yytestcase(yyruleno==257);
118574      case 258: /* nmnum ::= ON */ yytestcase(yyruleno==258);
118575      case 259: /* nmnum ::= DELETE */ yytestcase(yyruleno==259);
118576      case 260: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==260);
118577      case 261: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==261);
118578      case 262: /* plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==262);
118579      case 263: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==263);
118580      case 279: /* trnm ::= nm */ yytestcase(yyruleno==279);
118581{yygotominor.yy0 = yymsp[0].minor.yy0;}
118582        break;
118583      case 44: /* type ::= typetoken */
118584{sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
118585        break;
118586      case 46: /* typetoken ::= typename LP signed RP */
118587{
118588  yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
118589  yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
118590}
118591        break;
118592      case 47: /* typetoken ::= typename LP signed COMMA signed RP */
118593{
118594  yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
118595  yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
118596}
118597        break;
118598      case 49: /* typename ::= typename ID|STRING */
118599{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);}
118600        break;
118601      case 54: /* ccons ::= CONSTRAINT nm */
118602      case 92: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==92);
118603{pParse->constraintName = yymsp[0].minor.yy0;}
118604        break;
118605      case 55: /* ccons ::= DEFAULT term */
118606      case 57: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==57);
118607{sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy346);}
118608        break;
118609      case 56: /* ccons ::= DEFAULT LP expr RP */
118610{sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy346);}
118611        break;
118612      case 58: /* ccons ::= DEFAULT MINUS term */
118613{
118614  ExprSpan v;
118615  v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy346.pExpr, 0, 0);
118616  v.zStart = yymsp[-1].minor.yy0.z;
118617  v.zEnd = yymsp[0].minor.yy346.zEnd;
118618  sqlite3AddDefaultValue(pParse,&v);
118619}
118620        break;
118621      case 59: /* ccons ::= DEFAULT ID|INDEXED */
118622{
118623  ExprSpan v;
118624  spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
118625  sqlite3AddDefaultValue(pParse,&v);
118626}
118627        break;
118628      case 61: /* ccons ::= NOT NULL onconf */
118629{sqlite3AddNotNull(pParse, yymsp[0].minor.yy328);}
118630        break;
118631      case 62: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
118632{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy328,yymsp[0].minor.yy328,yymsp[-2].minor.yy328);}
118633        break;
118634      case 63: /* ccons ::= UNIQUE onconf */
118635{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy328,0,0,0,0);}
118636        break;
118637      case 64: /* ccons ::= CHECK LP expr RP */
118638{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy346.pExpr);}
118639        break;
118640      case 65: /* ccons ::= REFERENCES nm idxlist_opt refargs */
118641{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy14,yymsp[0].minor.yy328);}
118642        break;
118643      case 66: /* ccons ::= defer_subclause */
118644{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy328);}
118645        break;
118646      case 67: /* ccons ::= COLLATE ID|STRING */
118647{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
118648        break;
118649      case 70: /* refargs ::= */
118650{ yygotominor.yy328 = OE_None*0x0101; /* EV: R-19803-45884 */}
118651        break;
118652      case 71: /* refargs ::= refargs refarg */
118653{ yygotominor.yy328 = (yymsp[-1].minor.yy328 & ~yymsp[0].minor.yy429.mask) | yymsp[0].minor.yy429.value; }
118654        break;
118655      case 72: /* refarg ::= MATCH nm */
118656      case 73: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==73);
118657{ yygotominor.yy429.value = 0;     yygotominor.yy429.mask = 0x000000; }
118658        break;
118659      case 74: /* refarg ::= ON DELETE refact */
118660{ yygotominor.yy429.value = yymsp[0].minor.yy328;     yygotominor.yy429.mask = 0x0000ff; }
118661        break;
118662      case 75: /* refarg ::= ON UPDATE refact */
118663{ yygotominor.yy429.value = yymsp[0].minor.yy328<<8;  yygotominor.yy429.mask = 0x00ff00; }
118664        break;
118665      case 76: /* refact ::= SET NULL */
118666{ yygotominor.yy328 = OE_SetNull;  /* EV: R-33326-45252 */}
118667        break;
118668      case 77: /* refact ::= SET DEFAULT */
118669{ yygotominor.yy328 = OE_SetDflt;  /* EV: R-33326-45252 */}
118670        break;
118671      case 78: /* refact ::= CASCADE */
118672{ yygotominor.yy328 = OE_Cascade;  /* EV: R-33326-45252 */}
118673        break;
118674      case 79: /* refact ::= RESTRICT */
118675{ yygotominor.yy328 = OE_Restrict; /* EV: R-33326-45252 */}
118676        break;
118677      case 80: /* refact ::= NO ACTION */
118678{ yygotominor.yy328 = OE_None;     /* EV: R-33326-45252 */}
118679        break;
118680      case 82: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
118681      case 98: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==98);
118682      case 100: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==100);
118683      case 103: /* resolvetype ::= raisetype */ yytestcase(yyruleno==103);
118684{yygotominor.yy328 = yymsp[0].minor.yy328;}
118685        break;
118686      case 86: /* conslist_opt ::= */
118687{yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
118688        break;
118689      case 87: /* conslist_opt ::= COMMA conslist */
118690{yygotominor.yy0 = yymsp[-1].minor.yy0;}
118691        break;
118692      case 90: /* tconscomma ::= COMMA */
118693{pParse->constraintName.n = 0;}
118694        break;
118695      case 93: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
118696{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy14,yymsp[0].minor.yy328,yymsp[-2].minor.yy328,0);}
118697        break;
118698      case 94: /* tcons ::= UNIQUE LP idxlist RP onconf */
118699{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy14,yymsp[0].minor.yy328,0,0,0,0);}
118700        break;
118701      case 95: /* tcons ::= CHECK LP expr RP onconf */
118702{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy346.pExpr);}
118703        break;
118704      case 96: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
118705{
118706    sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy14, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[-1].minor.yy328);
118707    sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy328);
118708}
118709        break;
118710      case 99: /* onconf ::= */
118711{yygotominor.yy328 = OE_Default;}
118712        break;
118713      case 101: /* orconf ::= */
118714{yygotominor.yy186 = OE_Default;}
118715        break;
118716      case 102: /* orconf ::= OR resolvetype */
118717{yygotominor.yy186 = (u8)yymsp[0].minor.yy328;}
118718        break;
118719      case 104: /* resolvetype ::= IGNORE */
118720{yygotominor.yy328 = OE_Ignore;}
118721        break;
118722      case 105: /* resolvetype ::= REPLACE */
118723{yygotominor.yy328 = OE_Replace;}
118724        break;
118725      case 106: /* cmd ::= DROP TABLE ifexists fullname */
118726{
118727  sqlite3DropTable(pParse, yymsp[0].minor.yy65, 0, yymsp[-1].minor.yy328);
118728}
118729        break;
118730      case 109: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
118731{
118732  sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy3, yymsp[-6].minor.yy328, yymsp[-4].minor.yy328);
118733}
118734        break;
118735      case 110: /* cmd ::= DROP VIEW ifexists fullname */
118736{
118737  sqlite3DropTable(pParse, yymsp[0].minor.yy65, 1, yymsp[-1].minor.yy328);
118738}
118739        break;
118740      case 111: /* cmd ::= select */
118741{
118742  SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
118743  sqlite3Select(pParse, yymsp[0].minor.yy3, &dest);
118744  sqlite3ExplainBegin(pParse->pVdbe);
118745  sqlite3ExplainSelect(pParse->pVdbe, yymsp[0].minor.yy3);
118746  sqlite3ExplainFinish(pParse->pVdbe);
118747  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
118748}
118749        break;
118750      case 112: /* select ::= with selectnowith */
118751{
118752  Select *p = yymsp[0].minor.yy3, *pNext, *pLoop;
118753  if( p ){
118754    int cnt = 0, mxSelect;
118755    p->pWith = yymsp[-1].minor.yy59;
118756    if( p->pPrior ){
118757      pNext = 0;
118758      for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
118759        pLoop->pNext = pNext;
118760        pLoop->selFlags |= SF_Compound;
118761      }
118762      mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
118763      if( mxSelect && cnt>mxSelect ){
118764        sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
118765      }
118766    }
118767  }else{
118768    sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy59);
118769  }
118770  yygotominor.yy3 = p;
118771}
118772        break;
118773      case 113: /* selectnowith ::= oneselect */
118774      case 119: /* oneselect ::= values */ yytestcase(yyruleno==119);
118775{yygotominor.yy3 = yymsp[0].minor.yy3;}
118776        break;
118777      case 114: /* selectnowith ::= selectnowith multiselect_op oneselect */
118778{
118779  Select *pRhs = yymsp[0].minor.yy3;
118780  if( pRhs && pRhs->pPrior ){
118781    SrcList *pFrom;
118782    Token x;
118783    x.n = 0;
118784    pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
118785    pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
118786  }
118787  if( pRhs ){
118788    pRhs->op = (u8)yymsp[-1].minor.yy328;
118789    pRhs->pPrior = yymsp[-2].minor.yy3;
118790    if( yymsp[-1].minor.yy328!=TK_ALL ) pParse->hasCompound = 1;
118791  }else{
118792    sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy3);
118793  }
118794  yygotominor.yy3 = pRhs;
118795}
118796        break;
118797      case 116: /* multiselect_op ::= UNION ALL */
118798{yygotominor.yy328 = TK_ALL;}
118799        break;
118800      case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
118801{
118802  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);
118803}
118804        break;
118805      case 120: /* values ::= VALUES LP nexprlist RP */
118806{
118807  yygotominor.yy3 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values,0,0);
118808}
118809        break;
118810      case 121: /* values ::= values COMMA LP exprlist RP */
118811{
118812  Select *pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values,0,0);
118813  if( pRight ){
118814    pRight->op = TK_ALL;
118815    pRight->pPrior = yymsp[-4].minor.yy3;
118816    yygotominor.yy3 = pRight;
118817  }else{
118818    yygotominor.yy3 = yymsp[-4].minor.yy3;
118819  }
118820}
118821        break;
118822      case 122: /* distinct ::= DISTINCT */
118823{yygotominor.yy381 = SF_Distinct;}
118824        break;
118825      case 123: /* distinct ::= ALL */
118826      case 124: /* distinct ::= */ yytestcase(yyruleno==124);
118827{yygotominor.yy381 = 0;}
118828        break;
118829      case 125: /* sclp ::= selcollist COMMA */
118830      case 243: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==243);
118831{yygotominor.yy14 = yymsp[-1].minor.yy14;}
118832        break;
118833      case 126: /* sclp ::= */
118834      case 154: /* orderby_opt ::= */ yytestcase(yyruleno==154);
118835      case 161: /* groupby_opt ::= */ yytestcase(yyruleno==161);
118836      case 236: /* exprlist ::= */ yytestcase(yyruleno==236);
118837      case 242: /* idxlist_opt ::= */ yytestcase(yyruleno==242);
118838{yygotominor.yy14 = 0;}
118839        break;
118840      case 127: /* selcollist ::= sclp expr as */
118841{
118842   yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, yymsp[-1].minor.yy346.pExpr);
118843   if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[0].minor.yy0, 1);
118844   sqlite3ExprListSetSpan(pParse,yygotominor.yy14,&yymsp[-1].minor.yy346);
118845}
118846        break;
118847      case 128: /* selcollist ::= sclp STAR */
118848{
118849  Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
118850  yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy14, p);
118851}
118852        break;
118853      case 129: /* selcollist ::= sclp nm DOT STAR */
118854{
118855  Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
118856  Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
118857  Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
118858  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14, pDot);
118859}
118860        break;
118861      case 132: /* as ::= */
118862{yygotominor.yy0.n = 0;}
118863        break;
118864      case 133: /* from ::= */
118865{yygotominor.yy65 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy65));}
118866        break;
118867      case 134: /* from ::= FROM seltablist */
118868{
118869  yygotominor.yy65 = yymsp[0].minor.yy65;
118870  sqlite3SrcListShiftJoinType(yygotominor.yy65);
118871}
118872        break;
118873      case 135: /* stl_prefix ::= seltablist joinop */
118874{
118875   yygotominor.yy65 = yymsp[-1].minor.yy65;
118876   if( ALWAYS(yygotominor.yy65 && yygotominor.yy65->nSrc>0) ) yygotominor.yy65->a[yygotominor.yy65->nSrc-1].jointype = (u8)yymsp[0].minor.yy328;
118877}
118878        break;
118879      case 136: /* stl_prefix ::= */
118880{yygotominor.yy65 = 0;}
118881        break;
118882      case 137: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
118883{
118884  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);
118885  sqlite3SrcListIndexedBy(pParse, yygotominor.yy65, &yymsp[-2].minor.yy0);
118886}
118887        break;
118888      case 138: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
118889{
118890    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);
118891  }
118892        break;
118893      case 139: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
118894{
118895    if( yymsp[-6].minor.yy65==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy132==0 && yymsp[0].minor.yy408==0 ){
118896      yygotominor.yy65 = yymsp[-4].minor.yy65;
118897    }else if( yymsp[-4].minor.yy65->nSrc==1 ){
118898      yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
118899      if( yygotominor.yy65 ){
118900        struct SrcList_item *pNew = &yygotominor.yy65->a[yygotominor.yy65->nSrc-1];
118901        struct SrcList_item *pOld = yymsp[-4].minor.yy65->a;
118902        pNew->zName = pOld->zName;
118903        pNew->zDatabase = pOld->zDatabase;
118904        pNew->pSelect = pOld->pSelect;
118905        pOld->zName = pOld->zDatabase = 0;
118906        pOld->pSelect = 0;
118907      }
118908      sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy65);
118909    }else{
118910      Select *pSubquery;
118911      sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy65);
118912      pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy65,0,0,0,0,SF_NestedFrom,0,0);
118913      yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
118914    }
118915  }
118916        break;
118917      case 140: /* dbnm ::= */
118918      case 149: /* indexed_opt ::= */ yytestcase(yyruleno==149);
118919{yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
118920        break;
118921      case 142: /* fullname ::= nm dbnm */
118922{yygotominor.yy65 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
118923        break;
118924      case 143: /* joinop ::= COMMA|JOIN */
118925{ yygotominor.yy328 = JT_INNER; }
118926        break;
118927      case 144: /* joinop ::= JOIN_KW JOIN */
118928{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
118929        break;
118930      case 145: /* joinop ::= JOIN_KW nm JOIN */
118931{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
118932        break;
118933      case 146: /* joinop ::= JOIN_KW nm nm JOIN */
118934{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
118935        break;
118936      case 147: /* on_opt ::= ON expr */
118937      case 164: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==164);
118938      case 171: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==171);
118939      case 231: /* case_else ::= ELSE expr */ yytestcase(yyruleno==231);
118940      case 233: /* case_operand ::= expr */ yytestcase(yyruleno==233);
118941{yygotominor.yy132 = yymsp[0].minor.yy346.pExpr;}
118942        break;
118943      case 148: /* on_opt ::= */
118944      case 163: /* having_opt ::= */ yytestcase(yyruleno==163);
118945      case 170: /* where_opt ::= */ yytestcase(yyruleno==170);
118946      case 232: /* case_else ::= */ yytestcase(yyruleno==232);
118947      case 234: /* case_operand ::= */ yytestcase(yyruleno==234);
118948{yygotominor.yy132 = 0;}
118949        break;
118950      case 151: /* indexed_opt ::= NOT INDEXED */
118951{yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
118952        break;
118953      case 152: /* using_opt ::= USING LP idlist RP */
118954      case 180: /* inscollist_opt ::= LP idlist RP */ yytestcase(yyruleno==180);
118955{yygotominor.yy408 = yymsp[-1].minor.yy408;}
118956        break;
118957      case 153: /* using_opt ::= */
118958      case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
118959{yygotominor.yy408 = 0;}
118960        break;
118961      case 155: /* orderby_opt ::= ORDER BY sortlist */
118962      case 162: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==162);
118963      case 235: /* exprlist ::= nexprlist */ yytestcase(yyruleno==235);
118964{yygotominor.yy14 = yymsp[0].minor.yy14;}
118965        break;
118966      case 156: /* sortlist ::= sortlist COMMA expr sortorder */
118967{
118968  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14,yymsp[-1].minor.yy346.pExpr);
118969  if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
118970}
118971        break;
118972      case 157: /* sortlist ::= expr sortorder */
118973{
118974  yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy346.pExpr);
118975  if( yygotominor.yy14 && ALWAYS(yygotominor.yy14->a) ) yygotominor.yy14->a[0].sortOrder = (u8)yymsp[0].minor.yy328;
118976}
118977        break;
118978      case 158: /* sortorder ::= ASC */
118979      case 160: /* sortorder ::= */ yytestcase(yyruleno==160);
118980{yygotominor.yy328 = SQLITE_SO_ASC;}
118981        break;
118982      case 159: /* sortorder ::= DESC */
118983{yygotominor.yy328 = SQLITE_SO_DESC;}
118984        break;
118985      case 165: /* limit_opt ::= */
118986{yygotominor.yy476.pLimit = 0; yygotominor.yy476.pOffset = 0;}
118987        break;
118988      case 166: /* limit_opt ::= LIMIT expr */
118989{yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr; yygotominor.yy476.pOffset = 0;}
118990        break;
118991      case 167: /* limit_opt ::= LIMIT expr OFFSET expr */
118992{yygotominor.yy476.pLimit = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pOffset = yymsp[0].minor.yy346.pExpr;}
118993        break;
118994      case 168: /* limit_opt ::= LIMIT expr COMMA expr */
118995{yygotominor.yy476.pOffset = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr;}
118996        break;
118997      case 169: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
118998{
118999  sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
119000  sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy65, &yymsp[-1].minor.yy0);
119001  sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy65,yymsp[0].minor.yy132);
119002}
119003        break;
119004      case 172: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
119005{
119006  sqlite3WithPush(pParse, yymsp[-7].minor.yy59, 1);
119007  sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy65, &yymsp[-3].minor.yy0);
119008  sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy14,"set list");
119009  sqlite3Update(pParse,yymsp[-4].minor.yy65,yymsp[-1].minor.yy14,yymsp[0].minor.yy132,yymsp[-5].minor.yy186);
119010}
119011        break;
119012      case 173: /* setlist ::= setlist COMMA nm EQ expr */
119013{
119014  yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[0].minor.yy346.pExpr);
119015  sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
119016}
119017        break;
119018      case 174: /* setlist ::= nm EQ expr */
119019{
119020  yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy346.pExpr);
119021  sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
119022}
119023        break;
119024      case 175: /* cmd ::= with insert_cmd INTO fullname inscollist_opt select */
119025{
119026  sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
119027  sqlite3Insert(pParse, yymsp[-2].minor.yy65, yymsp[0].minor.yy3, yymsp[-1].minor.yy408, yymsp[-4].minor.yy186);
119028}
119029        break;
119030      case 176: /* cmd ::= with insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
119031{
119032  sqlite3WithPush(pParse, yymsp[-6].minor.yy59, 1);
119033  sqlite3Insert(pParse, yymsp[-3].minor.yy65, 0, yymsp[-2].minor.yy408, yymsp[-5].minor.yy186);
119034}
119035        break;
119036      case 177: /* insert_cmd ::= INSERT orconf */
119037{yygotominor.yy186 = yymsp[0].minor.yy186;}
119038        break;
119039      case 178: /* insert_cmd ::= REPLACE */
119040{yygotominor.yy186 = OE_Replace;}
119041        break;
119042      case 181: /* idlist ::= idlist COMMA nm */
119043{yygotominor.yy408 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy408,&yymsp[0].minor.yy0);}
119044        break;
119045      case 182: /* idlist ::= nm */
119046{yygotominor.yy408 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
119047        break;
119048      case 183: /* expr ::= term */
119049{yygotominor.yy346 = yymsp[0].minor.yy346;}
119050        break;
119051      case 184: /* expr ::= LP expr RP */
119052{yygotominor.yy346.pExpr = yymsp[-1].minor.yy346.pExpr; spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
119053        break;
119054      case 185: /* term ::= NULL */
119055      case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
119056      case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
119057{spanExpr(&yygotominor.yy346, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
119058        break;
119059      case 186: /* expr ::= ID|INDEXED */
119060      case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
119061{spanExpr(&yygotominor.yy346, pParse, TK_ID, &yymsp[0].minor.yy0);}
119062        break;
119063      case 188: /* expr ::= nm DOT nm */
119064{
119065  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
119066  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
119067  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
119068  spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
119069}
119070        break;
119071      case 189: /* expr ::= nm DOT nm DOT nm */
119072{
119073  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
119074  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
119075  Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
119076  Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
119077  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
119078  spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
119079}
119080        break;
119081      case 192: /* expr ::= VARIABLE */
119082{
119083  if( yymsp[0].minor.yy0.n>=2 && yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1]) ){
119084    /* When doing a nested parse, one can include terms in an expression
119085    ** that look like this:   #1 #2 ...  These terms refer to registers
119086    ** in the virtual machine.  #N is the N-th register. */
119087    if( pParse->nested==0 ){
119088      sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
119089      yygotominor.yy346.pExpr = 0;
119090    }else{
119091      yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
119092      if( yygotominor.yy346.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy346.pExpr->iTable);
119093    }
119094  }else{
119095    spanExpr(&yygotominor.yy346, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
119096    sqlite3ExprAssignVarNumber(pParse, yygotominor.yy346.pExpr);
119097  }
119098  spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
119099}
119100        break;
119101      case 193: /* expr ::= expr COLLATE ID|STRING */
119102{
119103  yygotominor.yy346.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy346.pExpr, &yymsp[0].minor.yy0);
119104  yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
119105  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
119106}
119107        break;
119108      case 194: /* expr ::= CAST LP expr AS typetoken RP */
119109{
119110  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy346.pExpr, 0, &yymsp[-1].minor.yy0);
119111  spanSet(&yygotominor.yy346,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
119112}
119113        break;
119114      case 195: /* expr ::= ID|INDEXED LP distinct exprlist RP */
119115{
119116  if( yymsp[-1].minor.yy14 && yymsp[-1].minor.yy14->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
119117    sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
119118  }
119119  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy14, &yymsp[-4].minor.yy0);
119120  spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
119121  if( yymsp[-2].minor.yy381 && yygotominor.yy346.pExpr ){
119122    yygotominor.yy346.pExpr->flags |= EP_Distinct;
119123  }
119124}
119125        break;
119126      case 196: /* expr ::= ID|INDEXED LP STAR RP */
119127{
119128  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
119129  spanSet(&yygotominor.yy346,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
119130}
119131        break;
119132      case 197: /* term ::= CTIME_KW */
119133{
119134  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
119135  spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
119136}
119137        break;
119138      case 198: /* expr ::= expr AND expr */
119139      case 199: /* expr ::= expr OR expr */ yytestcase(yyruleno==199);
119140      case 200: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==200);
119141      case 201: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==201);
119142      case 202: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==202);
119143      case 203: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==203);
119144      case 204: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==204);
119145      case 205: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==205);
119146{spanBinaryExpr(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);}
119147        break;
119148      case 206: /* likeop ::= LIKE_KW|MATCH */
119149{yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 0;}
119150        break;
119151      case 207: /* likeop ::= NOT LIKE_KW|MATCH */
119152{yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 1;}
119153        break;
119154      case 208: /* expr ::= expr likeop expr */
119155{
119156  ExprList *pList;
119157  pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy346.pExpr);
119158  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy346.pExpr);
119159  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy96.eOperator);
119160  if( yymsp[-1].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
119161  yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
119162  yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
119163  if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
119164}
119165        break;
119166      case 209: /* expr ::= expr likeop expr ESCAPE expr */
119167{
119168  ExprList *pList;
119169  pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
119170  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy346.pExpr);
119171  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
119172  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy96.eOperator);
119173  if( yymsp[-3].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
119174  yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
119175  yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
119176  if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
119177}
119178        break;
119179      case 210: /* expr ::= expr ISNULL|NOTNULL */
119180{spanUnaryPostfix(&yygotominor.yy346,pParse,yymsp[0].major,&yymsp[-1].minor.yy346,&yymsp[0].minor.yy0);}
119181        break;
119182      case 211: /* expr ::= expr NOT NULL */
119183{spanUnaryPostfix(&yygotominor.yy346,pParse,TK_NOTNULL,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy0);}
119184        break;
119185      case 212: /* expr ::= expr IS expr */
119186{
119187  spanBinaryExpr(&yygotominor.yy346,pParse,TK_IS,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);
119188  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_ISNULL);
119189}
119190        break;
119191      case 213: /* expr ::= expr IS NOT expr */
119192{
119193  spanBinaryExpr(&yygotominor.yy346,pParse,TK_ISNOT,&yymsp[-3].minor.yy346,&yymsp[0].minor.yy346);
119194  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_NOTNULL);
119195}
119196        break;
119197      case 214: /* expr ::= NOT expr */
119198      case 215: /* expr ::= BITNOT expr */ yytestcase(yyruleno==215);
119199{spanUnaryPrefix(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
119200        break;
119201      case 216: /* expr ::= MINUS expr */
119202{spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UMINUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
119203        break;
119204      case 217: /* expr ::= PLUS expr */
119205{spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UPLUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
119206        break;
119207      case 220: /* expr ::= expr between_op expr AND expr */
119208{
119209  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
119210  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
119211  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy346.pExpr, 0, 0);
119212  if( yygotominor.yy346.pExpr ){
119213    yygotominor.yy346.pExpr->x.pList = pList;
119214  }else{
119215    sqlite3ExprListDelete(pParse->db, pList);
119216  }
119217  if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
119218  yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
119219  yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
119220}
119221        break;
119222      case 223: /* expr ::= expr in_op LP exprlist RP */
119223{
119224    if( yymsp[-1].minor.yy14==0 ){
119225      /* Expressions of the form
119226      **
119227      **      expr1 IN ()
119228      **      expr1 NOT IN ()
119229      **
119230      ** simplify to constants 0 (false) and 1 (true), respectively,
119231      ** regardless of the value of expr1.
119232      */
119233      yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy328]);
119234      sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy346.pExpr);
119235    }else if( yymsp[-1].minor.yy14->nExpr==1 ){
119236      /* Expressions of the form:
119237      **
119238      **      expr1 IN (?1)
119239      **      expr1 NOT IN (?2)
119240      **
119241      ** with exactly one value on the RHS can be simplified to something
119242      ** like this:
119243      **
119244      **      expr1 == ?1
119245      **      expr1 <> ?2
119246      **
119247      ** But, the RHS of the == or <> is marked with the EP_Generic flag
119248      ** so that it may not contribute to the computation of comparison
119249      ** affinity or the collating sequence to use for comparison.  Otherwise,
119250      ** the semantics would be subtly different from IN or NOT IN.
119251      */
119252      Expr *pRHS = yymsp[-1].minor.yy14->a[0].pExpr;
119253      yymsp[-1].minor.yy14->a[0].pExpr = 0;
119254      sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
119255      /* pRHS cannot be NULL because a malloc error would have been detected
119256      ** before now and control would have never reached this point */
119257      if( ALWAYS(pRHS) ){
119258        pRHS->flags &= ~EP_Collate;
119259        pRHS->flags |= EP_Generic;
119260      }
119261      yygotominor.yy346.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy328 ? TK_NE : TK_EQ, yymsp[-4].minor.yy346.pExpr, pRHS, 0);
119262    }else{
119263      yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
119264      if( yygotominor.yy346.pExpr ){
119265        yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy14;
119266        sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
119267      }else{
119268        sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
119269      }
119270      if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
119271    }
119272    yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
119273    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
119274  }
119275        break;
119276      case 224: /* expr ::= LP select RP */
119277{
119278    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
119279    if( yygotominor.yy346.pExpr ){
119280      yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
119281      ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
119282      sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
119283    }else{
119284      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
119285    }
119286    yygotominor.yy346.zStart = yymsp[-2].minor.yy0.z;
119287    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
119288  }
119289        break;
119290      case 225: /* expr ::= expr in_op LP select RP */
119291{
119292    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
119293    if( yygotominor.yy346.pExpr ){
119294      yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
119295      ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
119296      sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
119297    }else{
119298      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
119299    }
119300    if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
119301    yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
119302    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
119303  }
119304        break;
119305      case 226: /* expr ::= expr in_op nm dbnm */
119306{
119307    SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
119308    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy346.pExpr, 0, 0);
119309    if( yygotominor.yy346.pExpr ){
119310      yygotominor.yy346.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
119311      ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
119312      sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
119313    }else{
119314      sqlite3SrcListDelete(pParse->db, pSrc);
119315    }
119316    if( yymsp[-2].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
119317    yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
119318    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];
119319  }
119320        break;
119321      case 227: /* expr ::= EXISTS LP select RP */
119322{
119323    Expr *p = yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
119324    if( p ){
119325      p->x.pSelect = yymsp[-1].minor.yy3;
119326      ExprSetProperty(p, EP_xIsSelect);
119327      sqlite3ExprSetHeight(pParse, p);
119328    }else{
119329      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
119330    }
119331    yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
119332    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
119333  }
119334        break;
119335      case 228: /* expr ::= CASE case_operand case_exprlist case_else END */
119336{
119337  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy132, 0, 0);
119338  if( yygotominor.yy346.pExpr ){
119339    yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy132 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[-1].minor.yy132) : yymsp[-2].minor.yy14;
119340    sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
119341  }else{
119342    sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy14);
119343    sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy132);
119344  }
119345  yygotominor.yy346.zStart = yymsp[-4].minor.yy0.z;
119346  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
119347}
119348        break;
119349      case 229: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
119350{
119351  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, yymsp[-2].minor.yy346.pExpr);
119352  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
119353}
119354        break;
119355      case 230: /* case_exprlist ::= WHEN expr THEN expr */
119356{
119357  yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
119358  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
119359}
119360        break;
119361      case 237: /* nexprlist ::= nexprlist COMMA expr */
119362{yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[0].minor.yy346.pExpr);}
119363        break;
119364      case 238: /* nexprlist ::= expr */
119365{yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy346.pExpr);}
119366        break;
119367      case 239: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt */
119368{
119369  sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
119370                     sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy14, yymsp[-10].minor.yy328,
119371                      &yymsp[-11].minor.yy0, yymsp[0].minor.yy132, SQLITE_SO_ASC, yymsp[-8].minor.yy328);
119372}
119373        break;
119374      case 240: /* uniqueflag ::= UNIQUE */
119375      case 291: /* raisetype ::= ABORT */ yytestcase(yyruleno==291);
119376{yygotominor.yy328 = OE_Abort;}
119377        break;
119378      case 241: /* uniqueflag ::= */
119379{yygotominor.yy328 = OE_None;}
119380        break;
119381      case 244: /* idxlist ::= idxlist COMMA nm collate sortorder */
119382{
119383  Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
119384  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, p);
119385  sqlite3ExprListSetName(pParse,yygotominor.yy14,&yymsp[-2].minor.yy0,1);
119386  sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
119387  if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
119388}
119389        break;
119390      case 245: /* idxlist ::= nm collate sortorder */
119391{
119392  Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
119393  yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, p);
119394  sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
119395  sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
119396  if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
119397}
119398        break;
119399      case 246: /* collate ::= */
119400{yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
119401        break;
119402      case 248: /* cmd ::= DROP INDEX ifexists fullname */
119403{sqlite3DropIndex(pParse, yymsp[0].minor.yy65, yymsp[-1].minor.yy328);}
119404        break;
119405      case 249: /* cmd ::= VACUUM */
119406      case 250: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==250);
119407{sqlite3Vacuum(pParse);}
119408        break;
119409      case 251: /* cmd ::= PRAGMA nm dbnm */
119410{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
119411        break;
119412      case 252: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
119413{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
119414        break;
119415      case 253: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
119416{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
119417        break;
119418      case 254: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
119419{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
119420        break;
119421      case 255: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
119422{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
119423        break;
119424      case 264: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
119425{
119426  Token all;
119427  all.z = yymsp[-3].minor.yy0.z;
119428  all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
119429  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy473, &all);
119430}
119431        break;
119432      case 265: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
119433{
119434  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);
119435  yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
119436}
119437        break;
119438      case 266: /* trigger_time ::= BEFORE */
119439      case 269: /* trigger_time ::= */ yytestcase(yyruleno==269);
119440{ yygotominor.yy328 = TK_BEFORE; }
119441        break;
119442      case 267: /* trigger_time ::= AFTER */
119443{ yygotominor.yy328 = TK_AFTER;  }
119444        break;
119445      case 268: /* trigger_time ::= INSTEAD OF */
119446{ yygotominor.yy328 = TK_INSTEAD;}
119447        break;
119448      case 270: /* trigger_event ::= DELETE|INSERT */
119449      case 271: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==271);
119450{yygotominor.yy378.a = yymsp[0].major; yygotominor.yy378.b = 0;}
119451        break;
119452      case 272: /* trigger_event ::= UPDATE OF idlist */
119453{yygotominor.yy378.a = TK_UPDATE; yygotominor.yy378.b = yymsp[0].minor.yy408;}
119454        break;
119455      case 275: /* when_clause ::= */
119456      case 296: /* key_opt ::= */ yytestcase(yyruleno==296);
119457{ yygotominor.yy132 = 0; }
119458        break;
119459      case 276: /* when_clause ::= WHEN expr */
119460      case 297: /* key_opt ::= KEY expr */ yytestcase(yyruleno==297);
119461{ yygotominor.yy132 = yymsp[0].minor.yy346.pExpr; }
119462        break;
119463      case 277: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
119464{
119465  assert( yymsp[-2].minor.yy473!=0 );
119466  yymsp[-2].minor.yy473->pLast->pNext = yymsp[-1].minor.yy473;
119467  yymsp[-2].minor.yy473->pLast = yymsp[-1].minor.yy473;
119468  yygotominor.yy473 = yymsp[-2].minor.yy473;
119469}
119470        break;
119471      case 278: /* trigger_cmd_list ::= trigger_cmd SEMI */
119472{
119473  assert( yymsp[-1].minor.yy473!=0 );
119474  yymsp[-1].minor.yy473->pLast = yymsp[-1].minor.yy473;
119475  yygotominor.yy473 = yymsp[-1].minor.yy473;
119476}
119477        break;
119478      case 280: /* trnm ::= nm DOT nm */
119479{
119480  yygotominor.yy0 = yymsp[0].minor.yy0;
119481  sqlite3ErrorMsg(pParse,
119482        "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
119483        "statements within triggers");
119484}
119485        break;
119486      case 282: /* tridxby ::= INDEXED BY nm */
119487{
119488  sqlite3ErrorMsg(pParse,
119489        "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
119490        "within triggers");
119491}
119492        break;
119493      case 283: /* tridxby ::= NOT INDEXED */
119494{
119495  sqlite3ErrorMsg(pParse,
119496        "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
119497        "within triggers");
119498}
119499        break;
119500      case 284: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
119501{ yygotominor.yy473 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy14, yymsp[0].minor.yy132, yymsp[-5].minor.yy186); }
119502        break;
119503      case 285: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
119504{yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy408, yymsp[0].minor.yy3, yymsp[-4].minor.yy186);}
119505        break;
119506      case 286: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
119507{yygotominor.yy473 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy132);}
119508        break;
119509      case 287: /* trigger_cmd ::= select */
119510{yygotominor.yy473 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy3); }
119511        break;
119512      case 288: /* expr ::= RAISE LP IGNORE RP */
119513{
119514  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
119515  if( yygotominor.yy346.pExpr ){
119516    yygotominor.yy346.pExpr->affinity = OE_Ignore;
119517  }
119518  yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
119519  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
119520}
119521        break;
119522      case 289: /* expr ::= RAISE LP raisetype COMMA nm RP */
119523{
119524  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
119525  if( yygotominor.yy346.pExpr ) {
119526    yygotominor.yy346.pExpr->affinity = (char)yymsp[-3].minor.yy328;
119527  }
119528  yygotominor.yy346.zStart = yymsp[-5].minor.yy0.z;
119529  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
119530}
119531        break;
119532      case 290: /* raisetype ::= ROLLBACK */
119533{yygotominor.yy328 = OE_Rollback;}
119534        break;
119535      case 292: /* raisetype ::= FAIL */
119536{yygotominor.yy328 = OE_Fail;}
119537        break;
119538      case 293: /* cmd ::= DROP TRIGGER ifexists fullname */
119539{
119540  sqlite3DropTrigger(pParse,yymsp[0].minor.yy65,yymsp[-1].minor.yy328);
119541}
119542        break;
119543      case 294: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
119544{
119545  sqlite3Attach(pParse, yymsp[-3].minor.yy346.pExpr, yymsp[-1].minor.yy346.pExpr, yymsp[0].minor.yy132);
119546}
119547        break;
119548      case 295: /* cmd ::= DETACH database_kw_opt expr */
119549{
119550  sqlite3Detach(pParse, yymsp[0].minor.yy346.pExpr);
119551}
119552        break;
119553      case 300: /* cmd ::= REINDEX */
119554{sqlite3Reindex(pParse, 0, 0);}
119555        break;
119556      case 301: /* cmd ::= REINDEX nm dbnm */
119557{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
119558        break;
119559      case 302: /* cmd ::= ANALYZE */
119560{sqlite3Analyze(pParse, 0, 0);}
119561        break;
119562      case 303: /* cmd ::= ANALYZE nm dbnm */
119563{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
119564        break;
119565      case 304: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
119566{
119567  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy65,&yymsp[0].minor.yy0);
119568}
119569        break;
119570      case 305: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
119571{
119572  sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
119573}
119574        break;
119575      case 306: /* add_column_fullname ::= fullname */
119576{
119577  pParse->db->lookaside.bEnabled = 0;
119578  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy65);
119579}
119580        break;
119581      case 309: /* cmd ::= create_vtab */
119582{sqlite3VtabFinishParse(pParse,0);}
119583        break;
119584      case 310: /* cmd ::= create_vtab LP vtabarglist RP */
119585{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
119586        break;
119587      case 311: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
119588{
119589    sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy328);
119590}
119591        break;
119592      case 314: /* vtabarg ::= */
119593{sqlite3VtabArgInit(pParse);}
119594        break;
119595      case 316: /* vtabargtoken ::= ANY */
119596      case 317: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==317);
119597      case 318: /* lp ::= LP */ yytestcase(yyruleno==318);
119598{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
119599        break;
119600      case 322: /* with ::= */
119601{yygotominor.yy59 = 0;}
119602        break;
119603      case 323: /* with ::= WITH wqlist */
119604      case 324: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==324);
119605{ yygotominor.yy59 = yymsp[0].minor.yy59; }
119606        break;
119607      case 325: /* wqlist ::= nm idxlist_opt AS LP select RP */
119608{
119609  yygotominor.yy59 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
119610}
119611        break;
119612      case 326: /* wqlist ::= wqlist COMMA nm idxlist_opt AS LP select RP */
119613{
119614  yygotominor.yy59 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy59, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
119615}
119616        break;
119617      default:
119618      /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
119619      /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
119620      /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
119621      /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
119622      /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
119623      /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
119624      /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
119625      /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
119626      /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
119627      /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
119628      /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
119629      /* (36) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==36);
119630      /* (37) columnlist ::= column */ yytestcase(yyruleno==37);
119631      /* (43) type ::= */ yytestcase(yyruleno==43);
119632      /* (50) signed ::= plus_num */ yytestcase(yyruleno==50);
119633      /* (51) signed ::= minus_num */ yytestcase(yyruleno==51);
119634      /* (52) carglist ::= carglist ccons */ yytestcase(yyruleno==52);
119635      /* (53) carglist ::= */ yytestcase(yyruleno==53);
119636      /* (60) ccons ::= NULL onconf */ yytestcase(yyruleno==60);
119637      /* (88) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==88);
119638      /* (89) conslist ::= tcons */ yytestcase(yyruleno==89);
119639      /* (91) tconscomma ::= */ yytestcase(yyruleno==91);
119640      /* (273) foreach_clause ::= */ yytestcase(yyruleno==273);
119641      /* (274) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==274);
119642      /* (281) tridxby ::= */ yytestcase(yyruleno==281);
119643      /* (298) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==298);
119644      /* (299) database_kw_opt ::= */ yytestcase(yyruleno==299);
119645      /* (307) kwcolumn_opt ::= */ yytestcase(yyruleno==307);
119646      /* (308) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==308);
119647      /* (312) vtabarglist ::= vtabarg */ yytestcase(yyruleno==312);
119648      /* (313) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==313);
119649      /* (315) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==315);
119650      /* (319) anylist ::= */ yytestcase(yyruleno==319);
119651      /* (320) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==320);
119652      /* (321) anylist ::= anylist ANY */ yytestcase(yyruleno==321);
119653        break;
119654  };
119655  assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
119656  yygoto = yyRuleInfo[yyruleno].lhs;
119657  yysize = yyRuleInfo[yyruleno].nrhs;
119658  yypParser->yyidx -= yysize;
119659  yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
119660  if( yyact < YYNSTATE ){
119661#ifdef NDEBUG
119662    /* If we are not debugging and the reduce action popped at least
119663    ** one element off the stack, then we can push the new element back
119664    ** onto the stack here, and skip the stack overflow test in yy_shift().
119665    ** That gives a significant speed improvement. */
119666    if( yysize ){
119667      yypParser->yyidx++;
119668      yymsp -= yysize-1;
119669      yymsp->stateno = (YYACTIONTYPE)yyact;
119670      yymsp->major = (YYCODETYPE)yygoto;
119671      yymsp->minor = yygotominor;
119672    }else
119673#endif
119674    {
119675      yy_shift(yypParser,yyact,yygoto,&yygotominor);
119676    }
119677  }else{
119678    assert( yyact == YYNSTATE + YYNRULE + 1 );
119679    yy_accept(yypParser);
119680  }
119681}
119682
119683/*
119684** The following code executes when the parse fails
119685*/
119686#ifndef YYNOERRORRECOVERY
119687static void yy_parse_failed(
119688  yyParser *yypParser           /* The parser */
119689){
119690  sqlite3ParserARG_FETCH;
119691#ifndef NDEBUG
119692  if( yyTraceFILE ){
119693    fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
119694  }
119695#endif
119696  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
119697  /* Here code is inserted which will be executed whenever the
119698  ** parser fails */
119699  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
119700}
119701#endif /* YYNOERRORRECOVERY */
119702
119703/*
119704** The following code executes when a syntax error first occurs.
119705*/
119706static void yy_syntax_error(
119707  yyParser *yypParser,           /* The parser */
119708  int yymajor,                   /* The major type of the error token */
119709  YYMINORTYPE yyminor            /* The minor type of the error token */
119710){
119711  sqlite3ParserARG_FETCH;
119712#define TOKEN (yyminor.yy0)
119713
119714  UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
119715  assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
119716  sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
119717  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
119718}
119719
119720/*
119721** The following is executed when the parser accepts
119722*/
119723static void yy_accept(
119724  yyParser *yypParser           /* The parser */
119725){
119726  sqlite3ParserARG_FETCH;
119727#ifndef NDEBUG
119728  if( yyTraceFILE ){
119729    fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
119730  }
119731#endif
119732  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
119733  /* Here code is inserted which will be executed whenever the
119734  ** parser accepts */
119735  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
119736}
119737
119738/* The main parser program.
119739** The first argument is a pointer to a structure obtained from
119740** "sqlite3ParserAlloc" which describes the current state of the parser.
119741** The second argument is the major token number.  The third is
119742** the minor token.  The fourth optional argument is whatever the
119743** user wants (and specified in the grammar) and is available for
119744** use by the action routines.
119745**
119746** Inputs:
119747** <ul>
119748** <li> A pointer to the parser (an opaque structure.)
119749** <li> The major token number.
119750** <li> The minor token number.
119751** <li> An option argument of a grammar-specified type.
119752** </ul>
119753**
119754** Outputs:
119755** None.
119756*/
119757SQLITE_PRIVATE void sqlite3Parser(
119758  void *yyp,                   /* The parser */
119759  int yymajor,                 /* The major token code number */
119760  sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
119761  sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
119762){
119763  YYMINORTYPE yyminorunion;
119764  int yyact;            /* The parser action. */
119765#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
119766  int yyendofinput;     /* True if we are at the end of input */
119767#endif
119768#ifdef YYERRORSYMBOL
119769  int yyerrorhit = 0;   /* True if yymajor has invoked an error */
119770#endif
119771  yyParser *yypParser;  /* The parser */
119772
119773  /* (re)initialize the parser, if necessary */
119774  yypParser = (yyParser*)yyp;
119775  if( yypParser->yyidx<0 ){
119776#if YYSTACKDEPTH<=0
119777    if( yypParser->yystksz <=0 ){
119778      /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
119779      yyminorunion = yyzerominor;
119780      yyStackOverflow(yypParser, &yyminorunion);
119781      return;
119782    }
119783#endif
119784    yypParser->yyidx = 0;
119785    yypParser->yyerrcnt = -1;
119786    yypParser->yystack[0].stateno = 0;
119787    yypParser->yystack[0].major = 0;
119788  }
119789  yyminorunion.yy0 = yyminor;
119790#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
119791  yyendofinput = (yymajor==0);
119792#endif
119793  sqlite3ParserARG_STORE;
119794
119795#ifndef NDEBUG
119796  if( yyTraceFILE ){
119797    fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
119798  }
119799#endif
119800
119801  do{
119802    yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
119803    if( yyact<YYNSTATE ){
119804      yy_shift(yypParser,yyact,yymajor,&yyminorunion);
119805      yypParser->yyerrcnt--;
119806      yymajor = YYNOCODE;
119807    }else if( yyact < YYNSTATE + YYNRULE ){
119808      yy_reduce(yypParser,yyact-YYNSTATE);
119809    }else{
119810      assert( yyact == YY_ERROR_ACTION );
119811#ifdef YYERRORSYMBOL
119812      int yymx;
119813#endif
119814#ifndef NDEBUG
119815      if( yyTraceFILE ){
119816        fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
119817      }
119818#endif
119819#ifdef YYERRORSYMBOL
119820      /* A syntax error has occurred.
119821      ** The response to an error depends upon whether or not the
119822      ** grammar defines an error token "ERROR".
119823      **
119824      ** This is what we do if the grammar does define ERROR:
119825      **
119826      **  * Call the %syntax_error function.
119827      **
119828      **  * Begin popping the stack until we enter a state where
119829      **    it is legal to shift the error symbol, then shift
119830      **    the error symbol.
119831      **
119832      **  * Set the error count to three.
119833      **
119834      **  * Begin accepting and shifting new tokens.  No new error
119835      **    processing will occur until three tokens have been
119836      **    shifted successfully.
119837      **
119838      */
119839      if( yypParser->yyerrcnt<0 ){
119840        yy_syntax_error(yypParser,yymajor,yyminorunion);
119841      }
119842      yymx = yypParser->yystack[yypParser->yyidx].major;
119843      if( yymx==YYERRORSYMBOL || yyerrorhit ){
119844#ifndef NDEBUG
119845        if( yyTraceFILE ){
119846          fprintf(yyTraceFILE,"%sDiscard input token %s\n",
119847             yyTracePrompt,yyTokenName[yymajor]);
119848        }
119849#endif
119850        yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
119851        yymajor = YYNOCODE;
119852      }else{
119853         while(
119854          yypParser->yyidx >= 0 &&
119855          yymx != YYERRORSYMBOL &&
119856          (yyact = yy_find_reduce_action(
119857                        yypParser->yystack[yypParser->yyidx].stateno,
119858                        YYERRORSYMBOL)) >= YYNSTATE
119859        ){
119860          yy_pop_parser_stack(yypParser);
119861        }
119862        if( yypParser->yyidx < 0 || yymajor==0 ){
119863          yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
119864          yy_parse_failed(yypParser);
119865          yymajor = YYNOCODE;
119866        }else if( yymx!=YYERRORSYMBOL ){
119867          YYMINORTYPE u2;
119868          u2.YYERRSYMDT = 0;
119869          yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
119870        }
119871      }
119872      yypParser->yyerrcnt = 3;
119873      yyerrorhit = 1;
119874#elif defined(YYNOERRORRECOVERY)
119875      /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
119876      ** do any kind of error recovery.  Instead, simply invoke the syntax
119877      ** error routine and continue going as if nothing had happened.
119878      **
119879      ** Applications can set this macro (for example inside %include) if
119880      ** they intend to abandon the parse upon the first syntax error seen.
119881      */
119882      yy_syntax_error(yypParser,yymajor,yyminorunion);
119883      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
119884      yymajor = YYNOCODE;
119885
119886#else  /* YYERRORSYMBOL is not defined */
119887      /* This is what we do if the grammar does not define ERROR:
119888      **
119889      **  * Report an error message, and throw away the input token.
119890      **
119891      **  * If the input token is $, then fail the parse.
119892      **
119893      ** As before, subsequent error messages are suppressed until
119894      ** three input tokens have been successfully shifted.
119895      */
119896      if( yypParser->yyerrcnt<=0 ){
119897        yy_syntax_error(yypParser,yymajor,yyminorunion);
119898      }
119899      yypParser->yyerrcnt = 3;
119900      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
119901      if( yyendofinput ){
119902        yy_parse_failed(yypParser);
119903      }
119904      yymajor = YYNOCODE;
119905#endif
119906    }
119907  }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
119908  return;
119909}
119910
119911/************** End of parse.c ***********************************************/
119912/************** Begin file tokenize.c ****************************************/
119913/*
119914** 2001 September 15
119915**
119916** The author disclaims copyright to this source code.  In place of
119917** a legal notice, here is a blessing:
119918**
119919**    May you do good and not evil.
119920**    May you find forgiveness for yourself and forgive others.
119921**    May you share freely, never taking more than you give.
119922**
119923*************************************************************************
119924** An tokenizer for SQL
119925**
119926** This file contains C code that splits an SQL input string up into
119927** individual tokens and sends those tokens one-by-one over to the
119928** parser for analysis.
119929*/
119930/* #include <stdlib.h> */
119931
119932/*
119933** The charMap() macro maps alphabetic characters into their
119934** lower-case ASCII equivalent.  On ASCII machines, this is just
119935** an upper-to-lower case map.  On EBCDIC machines we also need
119936** to adjust the encoding.  Only alphabetic characters and underscores
119937** need to be translated.
119938*/
119939#ifdef SQLITE_ASCII
119940# define charMap(X) sqlite3UpperToLower[(unsigned char)X]
119941#endif
119942#ifdef SQLITE_EBCDIC
119943# define charMap(X) ebcdicToAscii[(unsigned char)X]
119944const unsigned char ebcdicToAscii[] = {
119945/* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
119946   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
119947   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
119948   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
119949   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
119950   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
119951   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
119952   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
119953   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
119954   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
119955   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
119956   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
119957   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
119958   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
119959   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
119960   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
119961   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
119962};
119963#endif
119964
119965/*
119966** The sqlite3KeywordCode function looks up an identifier to determine if
119967** it is a keyword.  If it is a keyword, the token code of that keyword is
119968** returned.  If the input is not a keyword, TK_ID is returned.
119969**
119970** The implementation of this routine was generated by a program,
119971** mkkeywordhash.h, located in the tool subdirectory of the distribution.
119972** The output of the mkkeywordhash.c program is written into a file
119973** named keywordhash.h and then included into this source file by
119974** the #include below.
119975*/
119976/************** Include keywordhash.h in the middle of tokenize.c ************/
119977/************** Begin file keywordhash.h *************************************/
119978/***** This file contains automatically generated code ******
119979**
119980** The code in this file has been automatically generated by
119981**
119982**   sqlite/tool/mkkeywordhash.c
119983**
119984** The code in this file implements a function that determines whether
119985** or not a given identifier is really an SQL keyword.  The same thing
119986** might be implemented more directly using a hand-written hash table.
119987** But by using this automatically generated code, the size of the code
119988** is substantially reduced.  This is important for embedded applications
119989** on platforms with limited memory.
119990*/
119991/* Hash score: 182 */
119992static int keywordCode(const char *z, int n){
119993  /* zText[] encodes 834 bytes of keywords in 554 bytes */
119994  /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
119995  /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
119996  /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
119997  /*   UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE         */
119998  /*   BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH     */
119999  /*   IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN     */
120000  /*   WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT         */
120001  /*   CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL        */
120002  /*   FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING        */
120003  /*   VACUUMVIEWINITIALLY                                                */
120004  static const char zText[553] = {
120005    'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
120006    'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
120007    'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
120008    'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
120009    'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
120010    'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
120011    'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
120012    'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
120013    'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
120014    'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
120015    'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
120016    'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
120017    'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
120018    'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
120019    'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
120020    'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
120021    'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
120022    'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
120023    'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
120024    'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
120025    'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
120026    'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
120027    'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
120028    'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
120029    'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
120030    'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
120031    'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
120032    'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
120033    'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
120034    'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
120035    'V','I','E','W','I','N','I','T','I','A','L','L','Y',
120036  };
120037  static const unsigned char aHash[127] = {
120038      76, 105, 117,  74,   0,  45,   0,   0,  82,   0,  77,   0,   0,
120039      42,  12,  78,  15,   0, 116,  85,  54, 112,   0,  19,   0,   0,
120040     121,   0, 119, 115,   0,  22,  93,   0,   9,   0,   0,  70,  71,
120041       0,  69,   6,   0,  48,  90, 102,   0, 118, 101,   0,   0,  44,
120042       0, 103,  24,   0,  17,   0, 122,  53,  23,   0,   5, 110,  25,
120043      96,   0,   0, 124, 106,  60, 123,  57,  28,  55,   0,  91,   0,
120044     100,  26,   0,  99,   0,   0,   0,  95,  92,  97,  88, 109,  14,
120045      39, 108,   0,  81,   0,  18,  89, 111,  32,   0, 120,  80, 113,
120046      62,  46,  84,   0,   0,  94,  40,  59, 114,   0,  36,   0,   0,
120047      29,   0,  86,  63,  64,   0,  20,  61,   0,  56,
120048  };
120049  static const unsigned char aNext[124] = {
120050       0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
120051       0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
120052       0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
120053       0,   0,   0,   0,  33,   0,  21,   0,   0,   0,   0,   0,  50,
120054       0,  43,   3,  47,   0,   0,   0,   0,  30,   0,  58,   0,  38,
120055       0,   0,   0,   1,  66,   0,   0,  67,   0,  41,   0,   0,   0,
120056       0,   0,   0,  49,  65,   0,   0,   0,   0,  31,  52,  16,  34,
120057      10,   0,   0,   0,   0,   0,   0,   0,  11,  72,  79,   0,   8,
120058       0, 104,  98,   0, 107,   0,  87,   0,  75,  51,   0,  27,  37,
120059      73,  83,   0,  35,  68,   0,   0,
120060  };
120061  static const unsigned char aLen[124] = {
120062       7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
120063       7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
120064      11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
120065       4,   6,   2,   3,   9,   4,   2,   6,   5,   7,   4,   5,   7,
120066       6,   6,   5,   6,   5,   5,   9,   7,   7,   3,   2,   4,   4,
120067       7,   3,   6,   4,   7,   6,  12,   6,   9,   4,   6,   5,   4,
120068       7,   6,   5,   6,   7,   5,   4,   5,   6,   5,   7,   3,   7,
120069      13,   2,   2,   4,   6,   6,   8,   5,  17,  12,   7,   8,   8,
120070       2,   4,   4,   4,   4,   4,   2,   2,   6,   5,   8,   5,   8,
120071       3,   5,   5,   6,   4,   9,   3,
120072  };
120073  static const unsigned short int aOffset[124] = {
120074       0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
120075      36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
120076      86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
120077     159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
120078     199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
120079     250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
120080     320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
120081     387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
120082     460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
120083     521, 524, 529, 534, 540, 544, 549,
120084  };
120085  static const unsigned char aCode[124] = {
120086    TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
120087    TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
120088    TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
120089    TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
120090    TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
120091    TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,
120092    TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,
120093    TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
120094    TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,
120095    TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_WITHOUT,    TK_WITH,
120096    TK_JOIN_KW,    TK_RELEASE,    TK_ATTACH,     TK_HAVING,     TK_GROUP,
120097    TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RECURSIVE,  TK_BETWEEN,
120098    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       TK_LIKE_KW,
120099    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       TK_COLLATE,
120100    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  TK_JOIN,
120101    TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    TK_PRAGMA,
120102    TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      TK_WHEN,
120103    TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    TK_AND,
120104    TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         TK_CAST,
120105    TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    TK_CTIME_KW,
120106    TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   TK_IS,
120107    TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    TK_LIKE_KW,
120108    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      TK_RESTRICT,
120109    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        TK_UNION,      TK_USING,
120110    TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  TK_ALL,
120111  };
120112  int h, i;
120113  if( n<2 ) return TK_ID;
120114  h = ((charMap(z[0])*4) ^
120115      (charMap(z[n-1])*3) ^
120116      n) % 127;
120117  for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
120118    if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
120119      testcase( i==0 ); /* REINDEX */
120120      testcase( i==1 ); /* INDEXED */
120121      testcase( i==2 ); /* INDEX */
120122      testcase( i==3 ); /* DESC */
120123      testcase( i==4 ); /* ESCAPE */
120124      testcase( i==5 ); /* EACH */
120125      testcase( i==6 ); /* CHECK */
120126      testcase( i==7 ); /* KEY */
120127      testcase( i==8 ); /* BEFORE */
120128      testcase( i==9 ); /* FOREIGN */
120129      testcase( i==10 ); /* FOR */
120130      testcase( i==11 ); /* IGNORE */
120131      testcase( i==12 ); /* REGEXP */
120132      testcase( i==13 ); /* EXPLAIN */
120133      testcase( i==14 ); /* INSTEAD */
120134      testcase( i==15 ); /* ADD */
120135      testcase( i==16 ); /* DATABASE */
120136      testcase( i==17 ); /* AS */
120137      testcase( i==18 ); /* SELECT */
120138      testcase( i==19 ); /* TABLE */
120139      testcase( i==20 ); /* LEFT */
120140      testcase( i==21 ); /* THEN */
120141      testcase( i==22 ); /* END */
120142      testcase( i==23 ); /* DEFERRABLE */
120143      testcase( i==24 ); /* ELSE */
120144      testcase( i==25 ); /* EXCEPT */
120145      testcase( i==26 ); /* TRANSACTION */
120146      testcase( i==27 ); /* ACTION */
120147      testcase( i==28 ); /* ON */
120148      testcase( i==29 ); /* NATURAL */
120149      testcase( i==30 ); /* ALTER */
120150      testcase( i==31 ); /* RAISE */
120151      testcase( i==32 ); /* EXCLUSIVE */
120152      testcase( i==33 ); /* EXISTS */
120153      testcase( i==34 ); /* SAVEPOINT */
120154      testcase( i==35 ); /* INTERSECT */
120155      testcase( i==36 ); /* TRIGGER */
120156      testcase( i==37 ); /* REFERENCES */
120157      testcase( i==38 ); /* CONSTRAINT */
120158      testcase( i==39 ); /* INTO */
120159      testcase( i==40 ); /* OFFSET */
120160      testcase( i==41 ); /* OF */
120161      testcase( i==42 ); /* SET */
120162      testcase( i==43 ); /* TEMPORARY */
120163      testcase( i==44 ); /* TEMP */
120164      testcase( i==45 ); /* OR */
120165      testcase( i==46 ); /* UNIQUE */
120166      testcase( i==47 ); /* QUERY */
120167      testcase( i==48 ); /* WITHOUT */
120168      testcase( i==49 ); /* WITH */
120169      testcase( i==50 ); /* OUTER */
120170      testcase( i==51 ); /* RELEASE */
120171      testcase( i==52 ); /* ATTACH */
120172      testcase( i==53 ); /* HAVING */
120173      testcase( i==54 ); /* GROUP */
120174      testcase( i==55 ); /* UPDATE */
120175      testcase( i==56 ); /* BEGIN */
120176      testcase( i==57 ); /* INNER */
120177      testcase( i==58 ); /* RECURSIVE */
120178      testcase( i==59 ); /* BETWEEN */
120179      testcase( i==60 ); /* NOTNULL */
120180      testcase( i==61 ); /* NOT */
120181      testcase( i==62 ); /* NO */
120182      testcase( i==63 ); /* NULL */
120183      testcase( i==64 ); /* LIKE */
120184      testcase( i==65 ); /* CASCADE */
120185      testcase( i==66 ); /* ASC */
120186      testcase( i==67 ); /* DELETE */
120187      testcase( i==68 ); /* CASE */
120188      testcase( i==69 ); /* COLLATE */
120189      testcase( i==70 ); /* CREATE */
120190      testcase( i==71 ); /* CURRENT_DATE */
120191      testcase( i==72 ); /* DETACH */
120192      testcase( i==73 ); /* IMMEDIATE */
120193      testcase( i==74 ); /* JOIN */
120194      testcase( i==75 ); /* INSERT */
120195      testcase( i==76 ); /* MATCH */
120196      testcase( i==77 ); /* PLAN */
120197      testcase( i==78 ); /* ANALYZE */
120198      testcase( i==79 ); /* PRAGMA */
120199      testcase( i==80 ); /* ABORT */
120200      testcase( i==81 ); /* VALUES */
120201      testcase( i==82 ); /* VIRTUAL */
120202      testcase( i==83 ); /* LIMIT */
120203      testcase( i==84 ); /* WHEN */
120204      testcase( i==85 ); /* WHERE */
120205      testcase( i==86 ); /* RENAME */
120206      testcase( i==87 ); /* AFTER */
120207      testcase( i==88 ); /* REPLACE */
120208      testcase( i==89 ); /* AND */
120209      testcase( i==90 ); /* DEFAULT */
120210      testcase( i==91 ); /* AUTOINCREMENT */
120211      testcase( i==92 ); /* TO */
120212      testcase( i==93 ); /* IN */
120213      testcase( i==94 ); /* CAST */
120214      testcase( i==95 ); /* COLUMN */
120215      testcase( i==96 ); /* COMMIT */
120216      testcase( i==97 ); /* CONFLICT */
120217      testcase( i==98 ); /* CROSS */
120218      testcase( i==99 ); /* CURRENT_TIMESTAMP */
120219      testcase( i==100 ); /* CURRENT_TIME */
120220      testcase( i==101 ); /* PRIMARY */
120221      testcase( i==102 ); /* DEFERRED */
120222      testcase( i==103 ); /* DISTINCT */
120223      testcase( i==104 ); /* IS */
120224      testcase( i==105 ); /* DROP */
120225      testcase( i==106 ); /* FAIL */
120226      testcase( i==107 ); /* FROM */
120227      testcase( i==108 ); /* FULL */
120228      testcase( i==109 ); /* GLOB */
120229      testcase( i==110 ); /* BY */
120230      testcase( i==111 ); /* IF */
120231      testcase( i==112 ); /* ISNULL */
120232      testcase( i==113 ); /* ORDER */
120233      testcase( i==114 ); /* RESTRICT */
120234      testcase( i==115 ); /* RIGHT */
120235      testcase( i==116 ); /* ROLLBACK */
120236      testcase( i==117 ); /* ROW */
120237      testcase( i==118 ); /* UNION */
120238      testcase( i==119 ); /* USING */
120239      testcase( i==120 ); /* VACUUM */
120240      testcase( i==121 ); /* VIEW */
120241      testcase( i==122 ); /* INITIALLY */
120242      testcase( i==123 ); /* ALL */
120243      return aCode[i];
120244    }
120245  }
120246  return TK_ID;
120247}
120248SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
120249  return keywordCode((char*)z, n);
120250}
120251#define SQLITE_N_KEYWORD 124
120252
120253/************** End of keywordhash.h *****************************************/
120254/************** Continuing where we left off in tokenize.c *******************/
120255
120256
120257/*
120258** If X is a character that can be used in an identifier then
120259** IdChar(X) will be true.  Otherwise it is false.
120260**
120261** For ASCII, any character with the high-order bit set is
120262** allowed in an identifier.  For 7-bit characters,
120263** sqlite3IsIdChar[X] must be 1.
120264**
120265** For EBCDIC, the rules are more complex but have the same
120266** end result.
120267**
120268** Ticket #1066.  the SQL standard does not allow '$' in the
120269** middle of identfiers.  But many SQL implementations do.
120270** SQLite will allow '$' in identifiers for compatibility.
120271** But the feature is undocumented.
120272*/
120273#ifdef SQLITE_ASCII
120274#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
120275#endif
120276#ifdef SQLITE_EBCDIC
120277SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
120278/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
120279    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
120280    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
120281    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
120282    0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
120283    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
120284    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
120285    1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
120286    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
120287    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
120288    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
120289    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
120290    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
120291};
120292#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
120293#endif
120294
120295
120296/*
120297** Return the length of the token that begins at z[0].
120298** Store the token type in *tokenType before returning.
120299*/
120300SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
120301  int i, c;
120302  switch( *z ){
120303    case ' ': case '\t': case '\n': case '\f': case '\r': {
120304      testcase( z[0]==' ' );
120305      testcase( z[0]=='\t' );
120306      testcase( z[0]=='\n' );
120307      testcase( z[0]=='\f' );
120308      testcase( z[0]=='\r' );
120309      for(i=1; sqlite3Isspace(z[i]); i++){}
120310      *tokenType = TK_SPACE;
120311      return i;
120312    }
120313    case '-': {
120314      if( z[1]=='-' ){
120315        for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
120316        *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
120317        return i;
120318      }
120319      *tokenType = TK_MINUS;
120320      return 1;
120321    }
120322    case '(': {
120323      *tokenType = TK_LP;
120324      return 1;
120325    }
120326    case ')': {
120327      *tokenType = TK_RP;
120328      return 1;
120329    }
120330    case ';': {
120331      *tokenType = TK_SEMI;
120332      return 1;
120333    }
120334    case '+': {
120335      *tokenType = TK_PLUS;
120336      return 1;
120337    }
120338    case '*': {
120339      *tokenType = TK_STAR;
120340      return 1;
120341    }
120342    case '/': {
120343      if( z[1]!='*' || z[2]==0 ){
120344        *tokenType = TK_SLASH;
120345        return 1;
120346      }
120347      for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
120348      if( c ) i++;
120349      *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
120350      return i;
120351    }
120352    case '%': {
120353      *tokenType = TK_REM;
120354      return 1;
120355    }
120356    case '=': {
120357      *tokenType = TK_EQ;
120358      return 1 + (z[1]=='=');
120359    }
120360    case '<': {
120361      if( (c=z[1])=='=' ){
120362        *tokenType = TK_LE;
120363        return 2;
120364      }else if( c=='>' ){
120365        *tokenType = TK_NE;
120366        return 2;
120367      }else if( c=='<' ){
120368        *tokenType = TK_LSHIFT;
120369        return 2;
120370      }else{
120371        *tokenType = TK_LT;
120372        return 1;
120373      }
120374    }
120375    case '>': {
120376      if( (c=z[1])=='=' ){
120377        *tokenType = TK_GE;
120378        return 2;
120379      }else if( c=='>' ){
120380        *tokenType = TK_RSHIFT;
120381        return 2;
120382      }else{
120383        *tokenType = TK_GT;
120384        return 1;
120385      }
120386    }
120387    case '!': {
120388      if( z[1]!='=' ){
120389        *tokenType = TK_ILLEGAL;
120390        return 2;
120391      }else{
120392        *tokenType = TK_NE;
120393        return 2;
120394      }
120395    }
120396    case '|': {
120397      if( z[1]!='|' ){
120398        *tokenType = TK_BITOR;
120399        return 1;
120400      }else{
120401        *tokenType = TK_CONCAT;
120402        return 2;
120403      }
120404    }
120405    case ',': {
120406      *tokenType = TK_COMMA;
120407      return 1;
120408    }
120409    case '&': {
120410      *tokenType = TK_BITAND;
120411      return 1;
120412    }
120413    case '~': {
120414      *tokenType = TK_BITNOT;
120415      return 1;
120416    }
120417    case '`':
120418    case '\'':
120419    case '"': {
120420      int delim = z[0];
120421      testcase( delim=='`' );
120422      testcase( delim=='\'' );
120423      testcase( delim=='"' );
120424      for(i=1; (c=z[i])!=0; i++){
120425        if( c==delim ){
120426          if( z[i+1]==delim ){
120427            i++;
120428          }else{
120429            break;
120430          }
120431        }
120432      }
120433      if( c=='\'' ){
120434        *tokenType = TK_STRING;
120435        return i+1;
120436      }else if( c!=0 ){
120437        *tokenType = TK_ID;
120438        return i+1;
120439      }else{
120440        *tokenType = TK_ILLEGAL;
120441        return i;
120442      }
120443    }
120444    case '.': {
120445#ifndef SQLITE_OMIT_FLOATING_POINT
120446      if( !sqlite3Isdigit(z[1]) )
120447#endif
120448      {
120449        *tokenType = TK_DOT;
120450        return 1;
120451      }
120452      /* If the next character is a digit, this is a floating point
120453      ** number that begins with ".".  Fall thru into the next case */
120454    }
120455    case '0': case '1': case '2': case '3': case '4':
120456    case '5': case '6': case '7': case '8': case '9': {
120457      testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
120458      testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
120459      testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
120460      testcase( z[0]=='9' );
120461      *tokenType = TK_INTEGER;
120462      for(i=0; sqlite3Isdigit(z[i]); i++){}
120463#ifndef SQLITE_OMIT_FLOATING_POINT
120464      if( z[i]=='.' ){
120465        i++;
120466        while( sqlite3Isdigit(z[i]) ){ i++; }
120467        *tokenType = TK_FLOAT;
120468      }
120469      if( (z[i]=='e' || z[i]=='E') &&
120470           ( sqlite3Isdigit(z[i+1])
120471            || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
120472           )
120473      ){
120474        i += 2;
120475        while( sqlite3Isdigit(z[i]) ){ i++; }
120476        *tokenType = TK_FLOAT;
120477      }
120478#endif
120479      while( IdChar(z[i]) ){
120480        *tokenType = TK_ILLEGAL;
120481        i++;
120482      }
120483      return i;
120484    }
120485    case '[': {
120486      for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
120487      *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
120488      return i;
120489    }
120490    case '?': {
120491      *tokenType = TK_VARIABLE;
120492      for(i=1; sqlite3Isdigit(z[i]); i++){}
120493      return i;
120494    }
120495#ifndef SQLITE_OMIT_TCL_VARIABLE
120496    case '$':
120497#endif
120498    case '@':  /* For compatibility with MS SQL Server */
120499    case '#':
120500    case ':': {
120501      int n = 0;
120502      testcase( z[0]=='$' );  testcase( z[0]=='@' );
120503      testcase( z[0]==':' );  testcase( z[0]=='#' );
120504      *tokenType = TK_VARIABLE;
120505      for(i=1; (c=z[i])!=0; i++){
120506        if( IdChar(c) ){
120507          n++;
120508#ifndef SQLITE_OMIT_TCL_VARIABLE
120509        }else if( c=='(' && n>0 ){
120510          do{
120511            i++;
120512          }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
120513          if( c==')' ){
120514            i++;
120515          }else{
120516            *tokenType = TK_ILLEGAL;
120517          }
120518          break;
120519        }else if( c==':' && z[i+1]==':' ){
120520          i++;
120521#endif
120522        }else{
120523          break;
120524        }
120525      }
120526      if( n==0 ) *tokenType = TK_ILLEGAL;
120527      return i;
120528    }
120529#ifndef SQLITE_OMIT_BLOB_LITERAL
120530    case 'x': case 'X': {
120531      testcase( z[0]=='x' ); testcase( z[0]=='X' );
120532      if( z[1]=='\'' ){
120533        *tokenType = TK_BLOB;
120534        for(i=2; sqlite3Isxdigit(z[i]); i++){}
120535        if( z[i]!='\'' || i%2 ){
120536          *tokenType = TK_ILLEGAL;
120537          while( z[i] && z[i]!='\'' ){ i++; }
120538        }
120539        if( z[i] ) i++;
120540        return i;
120541      }
120542      /* Otherwise fall through to the next case */
120543    }
120544#endif
120545    default: {
120546      if( !IdChar(*z) ){
120547        break;
120548      }
120549      for(i=1; IdChar(z[i]); i++){}
120550      *tokenType = keywordCode((char*)z, i);
120551      return i;
120552    }
120553  }
120554  *tokenType = TK_ILLEGAL;
120555  return 1;
120556}
120557
120558/*
120559** Run the parser on the given SQL string.  The parser structure is
120560** passed in.  An SQLITE_ status code is returned.  If an error occurs
120561** then an and attempt is made to write an error message into
120562** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
120563** error message.
120564*/
120565SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
120566  int nErr = 0;                   /* Number of errors encountered */
120567  int i;                          /* Loop counter */
120568  void *pEngine;                  /* The LEMON-generated LALR(1) parser */
120569  int tokenType;                  /* type of the next token */
120570  int lastTokenParsed = -1;       /* type of the previous token */
120571  u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
120572  sqlite3 *db = pParse->db;       /* The database connection */
120573  int mxSqlLen;                   /* Max length of an SQL string */
120574
120575
120576  mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
120577  if( db->nVdbeActive==0 ){
120578    db->u1.isInterrupted = 0;
120579  }
120580  pParse->rc = SQLITE_OK;
120581  pParse->zTail = zSql;
120582  i = 0;
120583  assert( pzErrMsg!=0 );
120584  pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
120585  if( pEngine==0 ){
120586    db->mallocFailed = 1;
120587    return SQLITE_NOMEM;
120588  }
120589  assert( pParse->pNewTable==0 );
120590  assert( pParse->pNewTrigger==0 );
120591  assert( pParse->nVar==0 );
120592  assert( pParse->nzVar==0 );
120593  assert( pParse->azVar==0 );
120594  enableLookaside = db->lookaside.bEnabled;
120595  if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
120596  while( !db->mallocFailed && zSql[i]!=0 ){
120597    assert( i>=0 );
120598    pParse->sLastToken.z = &zSql[i];
120599    pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
120600    i += pParse->sLastToken.n;
120601    if( i>mxSqlLen ){
120602      pParse->rc = SQLITE_TOOBIG;
120603      break;
120604    }
120605    switch( tokenType ){
120606      case TK_SPACE: {
120607        if( db->u1.isInterrupted ){
120608          sqlite3ErrorMsg(pParse, "interrupt");
120609          pParse->rc = SQLITE_INTERRUPT;
120610          goto abort_parse;
120611        }
120612        break;
120613      }
120614      case TK_ILLEGAL: {
120615        sqlite3DbFree(db, *pzErrMsg);
120616        *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
120617                        &pParse->sLastToken);
120618        nErr++;
120619        goto abort_parse;
120620      }
120621      case TK_SEMI: {
120622        pParse->zTail = &zSql[i];
120623        /* Fall thru into the default case */
120624      }
120625      default: {
120626        sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
120627        lastTokenParsed = tokenType;
120628        if( pParse->rc!=SQLITE_OK ){
120629          goto abort_parse;
120630        }
120631        break;
120632      }
120633    }
120634  }
120635abort_parse:
120636  if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
120637    if( lastTokenParsed!=TK_SEMI ){
120638      sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
120639      pParse->zTail = &zSql[i];
120640    }
120641    sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
120642  }
120643#ifdef YYTRACKMAXSTACKDEPTH
120644  sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
120645      sqlite3ParserStackPeak(pEngine)
120646  );
120647#endif /* YYDEBUG */
120648  sqlite3ParserFree(pEngine, sqlite3_free);
120649  db->lookaside.bEnabled = enableLookaside;
120650  if( db->mallocFailed ){
120651    pParse->rc = SQLITE_NOMEM;
120652  }
120653  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
120654    sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
120655  }
120656  assert( pzErrMsg!=0 );
120657  if( pParse->zErrMsg ){
120658    *pzErrMsg = pParse->zErrMsg;
120659    sqlite3_log(pParse->rc, "%s", *pzErrMsg);
120660    pParse->zErrMsg = 0;
120661    nErr++;
120662  }
120663  if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
120664    sqlite3VdbeDelete(pParse->pVdbe);
120665    pParse->pVdbe = 0;
120666  }
120667#ifndef SQLITE_OMIT_SHARED_CACHE
120668  if( pParse->nested==0 ){
120669    sqlite3DbFree(db, pParse->aTableLock);
120670    pParse->aTableLock = 0;
120671    pParse->nTableLock = 0;
120672  }
120673#endif
120674#ifndef SQLITE_OMIT_VIRTUALTABLE
120675  sqlite3_free(pParse->apVtabLock);
120676#endif
120677
120678  if( !IN_DECLARE_VTAB ){
120679    /* If the pParse->declareVtab flag is set, do not delete any table
120680    ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
120681    ** will take responsibility for freeing the Table structure.
120682    */
120683    sqlite3DeleteTable(db, pParse->pNewTable);
120684  }
120685
120686  if( pParse->bFreeWith ) sqlite3WithDelete(db, pParse->pWith);
120687  sqlite3DeleteTrigger(db, pParse->pNewTrigger);
120688  for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
120689  sqlite3DbFree(db, pParse->azVar);
120690  while( pParse->pAinc ){
120691    AutoincInfo *p = pParse->pAinc;
120692    pParse->pAinc = p->pNext;
120693    sqlite3DbFree(db, p);
120694  }
120695  while( pParse->pZombieTab ){
120696    Table *p = pParse->pZombieTab;
120697    pParse->pZombieTab = p->pNextZombie;
120698    sqlite3DeleteTable(db, p);
120699  }
120700  if( nErr>0 && pParse->rc==SQLITE_OK ){
120701    pParse->rc = SQLITE_ERROR;
120702  }
120703  return nErr;
120704}
120705
120706/************** End of tokenize.c ********************************************/
120707/************** Begin file complete.c ****************************************/
120708/*
120709** 2001 September 15
120710**
120711** The author disclaims copyright to this source code.  In place of
120712** a legal notice, here is a blessing:
120713**
120714**    May you do good and not evil.
120715**    May you find forgiveness for yourself and forgive others.
120716**    May you share freely, never taking more than you give.
120717**
120718*************************************************************************
120719** An tokenizer for SQL
120720**
120721** This file contains C code that implements the sqlite3_complete() API.
120722** This code used to be part of the tokenizer.c source file.  But by
120723** separating it out, the code will be automatically omitted from
120724** static links that do not use it.
120725*/
120726#ifndef SQLITE_OMIT_COMPLETE
120727
120728/*
120729** This is defined in tokenize.c.  We just have to import the definition.
120730*/
120731#ifndef SQLITE_AMALGAMATION
120732#ifdef SQLITE_ASCII
120733#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
120734#endif
120735#ifdef SQLITE_EBCDIC
120736SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
120737#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
120738#endif
120739#endif /* SQLITE_AMALGAMATION */
120740
120741
120742/*
120743** Token types used by the sqlite3_complete() routine.  See the header
120744** comments on that procedure for additional information.
120745*/
120746#define tkSEMI    0
120747#define tkWS      1
120748#define tkOTHER   2
120749#ifndef SQLITE_OMIT_TRIGGER
120750#define tkEXPLAIN 3
120751#define tkCREATE  4
120752#define tkTEMP    5
120753#define tkTRIGGER 6
120754#define tkEND     7
120755#endif
120756
120757/*
120758** Return TRUE if the given SQL string ends in a semicolon.
120759**
120760** Special handling is require for CREATE TRIGGER statements.
120761** Whenever the CREATE TRIGGER keywords are seen, the statement
120762** must end with ";END;".
120763**
120764** This implementation uses a state machine with 8 states:
120765**
120766**   (0) INVALID   We have not yet seen a non-whitespace character.
120767**
120768**   (1) START     At the beginning or end of an SQL statement.  This routine
120769**                 returns 1 if it ends in the START state and 0 if it ends
120770**                 in any other state.
120771**
120772**   (2) NORMAL    We are in the middle of statement which ends with a single
120773**                 semicolon.
120774**
120775**   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of
120776**                 a statement.
120777**
120778**   (4) CREATE    The keyword CREATE has been seen at the beginning of a
120779**                 statement, possibly preceeded by EXPLAIN and/or followed by
120780**                 TEMP or TEMPORARY
120781**
120782**   (5) TRIGGER   We are in the middle of a trigger definition that must be
120783**                 ended by a semicolon, the keyword END, and another semicolon.
120784**
120785**   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
120786**                 the end of a trigger definition.
120787**
120788**   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
120789**                 of a trigger difinition.
120790**
120791** Transitions between states above are determined by tokens extracted
120792** from the input.  The following tokens are significant:
120793**
120794**   (0) tkSEMI      A semicolon.
120795**   (1) tkWS        Whitespace.
120796**   (2) tkOTHER     Any other SQL token.
120797**   (3) tkEXPLAIN   The "explain" keyword.
120798**   (4) tkCREATE    The "create" keyword.
120799**   (5) tkTEMP      The "temp" or "temporary" keyword.
120800**   (6) tkTRIGGER   The "trigger" keyword.
120801**   (7) tkEND       The "end" keyword.
120802**
120803** Whitespace never causes a state transition and is always ignored.
120804** This means that a SQL string of all whitespace is invalid.
120805**
120806** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
120807** to recognize the end of a trigger can be omitted.  All we have to do
120808** is look for a semicolon that is not part of an string or comment.
120809*/
120810SQLITE_API int sqlite3_complete(const char *zSql){
120811  u8 state = 0;   /* Current state, using numbers defined in header comment */
120812  u8 token;       /* Value of the next token */
120813
120814#ifndef SQLITE_OMIT_TRIGGER
120815  /* A complex statement machine used to detect the end of a CREATE TRIGGER
120816  ** statement.  This is the normal case.
120817  */
120818  static const u8 trans[8][8] = {
120819                     /* Token:                                                */
120820     /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
120821     /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
120822     /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
120823     /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
120824     /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
120825     /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
120826     /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
120827     /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
120828     /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
120829  };
120830#else
120831  /* If triggers are not supported by this compile then the statement machine
120832  ** used to detect the end of a statement is much simplier
120833  */
120834  static const u8 trans[3][3] = {
120835                     /* Token:           */
120836     /* State:       **  SEMI  WS  OTHER */
120837     /* 0 INVALID: */ {    1,  0,     2, },
120838     /* 1   START: */ {    1,  1,     2, },
120839     /* 2  NORMAL: */ {    1,  2,     2, },
120840  };
120841#endif /* SQLITE_OMIT_TRIGGER */
120842
120843  while( *zSql ){
120844    switch( *zSql ){
120845      case ';': {  /* A semicolon */
120846        token = tkSEMI;
120847        break;
120848      }
120849      case ' ':
120850      case '\r':
120851      case '\t':
120852      case '\n':
120853      case '\f': {  /* White space is ignored */
120854        token = tkWS;
120855        break;
120856      }
120857      case '/': {   /* C-style comments */
120858        if( zSql[1]!='*' ){
120859          token = tkOTHER;
120860          break;
120861        }
120862        zSql += 2;
120863        while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
120864        if( zSql[0]==0 ) return 0;
120865        zSql++;
120866        token = tkWS;
120867        break;
120868      }
120869      case '-': {   /* SQL-style comments from "--" to end of line */
120870        if( zSql[1]!='-' ){
120871          token = tkOTHER;
120872          break;
120873        }
120874        while( *zSql && *zSql!='\n' ){ zSql++; }
120875        if( *zSql==0 ) return state==1;
120876        token = tkWS;
120877        break;
120878      }
120879      case '[': {   /* Microsoft-style identifiers in [...] */
120880        zSql++;
120881        while( *zSql && *zSql!=']' ){ zSql++; }
120882        if( *zSql==0 ) return 0;
120883        token = tkOTHER;
120884        break;
120885      }
120886      case '`':     /* Grave-accent quoted symbols used by MySQL */
120887      case '"':     /* single- and double-quoted strings */
120888      case '\'': {
120889        int c = *zSql;
120890        zSql++;
120891        while( *zSql && *zSql!=c ){ zSql++; }
120892        if( *zSql==0 ) return 0;
120893        token = tkOTHER;
120894        break;
120895      }
120896      default: {
120897#ifdef SQLITE_EBCDIC
120898        unsigned char c;
120899#endif
120900        if( IdChar((u8)*zSql) ){
120901          /* Keywords and unquoted identifiers */
120902          int nId;
120903          for(nId=1; IdChar(zSql[nId]); nId++){}
120904#ifdef SQLITE_OMIT_TRIGGER
120905          token = tkOTHER;
120906#else
120907          switch( *zSql ){
120908            case 'c': case 'C': {
120909              if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
120910                token = tkCREATE;
120911              }else{
120912                token = tkOTHER;
120913              }
120914              break;
120915            }
120916            case 't': case 'T': {
120917              if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
120918                token = tkTRIGGER;
120919              }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
120920                token = tkTEMP;
120921              }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
120922                token = tkTEMP;
120923              }else{
120924                token = tkOTHER;
120925              }
120926              break;
120927            }
120928            case 'e':  case 'E': {
120929              if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
120930                token = tkEND;
120931              }else
120932#ifndef SQLITE_OMIT_EXPLAIN
120933              if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
120934                token = tkEXPLAIN;
120935              }else
120936#endif
120937              {
120938                token = tkOTHER;
120939              }
120940              break;
120941            }
120942            default: {
120943              token = tkOTHER;
120944              break;
120945            }
120946          }
120947#endif /* SQLITE_OMIT_TRIGGER */
120948          zSql += nId-1;
120949        }else{
120950          /* Operators and special symbols */
120951          token = tkOTHER;
120952        }
120953        break;
120954      }
120955    }
120956    state = trans[state][token];
120957    zSql++;
120958  }
120959  return state==1;
120960}
120961
120962#ifndef SQLITE_OMIT_UTF16
120963/*
120964** This routine is the same as the sqlite3_complete() routine described
120965** above, except that the parameter is required to be UTF-16 encoded, not
120966** UTF-8.
120967*/
120968SQLITE_API int sqlite3_complete16(const void *zSql){
120969  sqlite3_value *pVal;
120970  char const *zSql8;
120971  int rc = SQLITE_NOMEM;
120972
120973#ifndef SQLITE_OMIT_AUTOINIT
120974  rc = sqlite3_initialize();
120975  if( rc ) return rc;
120976#endif
120977  pVal = sqlite3ValueNew(0);
120978  sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
120979  zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
120980  if( zSql8 ){
120981    rc = sqlite3_complete(zSql8);
120982  }else{
120983    rc = SQLITE_NOMEM;
120984  }
120985  sqlite3ValueFree(pVal);
120986  return sqlite3ApiExit(0, rc);
120987}
120988#endif /* SQLITE_OMIT_UTF16 */
120989#endif /* SQLITE_OMIT_COMPLETE */
120990
120991/************** End of complete.c ********************************************/
120992/************** Begin file main.c ********************************************/
120993/*
120994** 2001 September 15
120995**
120996** The author disclaims copyright to this source code.  In place of
120997** a legal notice, here is a blessing:
120998**
120999**    May you do good and not evil.
121000**    May you find forgiveness for yourself and forgive others.
121001**    May you share freely, never taking more than you give.
121002**
121003*************************************************************************
121004** Main file for the SQLite library.  The routines in this file
121005** implement the programmer interface to the library.  Routines in
121006** other files are for internal use by SQLite and should not be
121007** accessed by users of the library.
121008*/
121009
121010#ifdef SQLITE_ENABLE_FTS3
121011/************** Include fts3.h in the middle of main.c ***********************/
121012/************** Begin file fts3.h ********************************************/
121013/*
121014** 2006 Oct 10
121015**
121016** The author disclaims copyright to this source code.  In place of
121017** a legal notice, here is a blessing:
121018**
121019**    May you do good and not evil.
121020**    May you find forgiveness for yourself and forgive others.
121021**    May you share freely, never taking more than you give.
121022**
121023******************************************************************************
121024**
121025** This header file is used by programs that want to link against the
121026** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
121027*/
121028
121029#if 0
121030extern "C" {
121031#endif  /* __cplusplus */
121032
121033SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
121034
121035#if 0
121036}  /* extern "C" */
121037#endif  /* __cplusplus */
121038
121039/************** End of fts3.h ************************************************/
121040/************** Continuing where we left off in main.c ***********************/
121041#endif
121042#ifdef SQLITE_ENABLE_RTREE
121043/************** Include rtree.h in the middle of main.c **********************/
121044/************** Begin file rtree.h *******************************************/
121045/*
121046** 2008 May 26
121047**
121048** The author disclaims copyright to this source code.  In place of
121049** a legal notice, here is a blessing:
121050**
121051**    May you do good and not evil.
121052**    May you find forgiveness for yourself and forgive others.
121053**    May you share freely, never taking more than you give.
121054**
121055******************************************************************************
121056**
121057** This header file is used by programs that want to link against the
121058** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
121059*/
121060
121061#if 0
121062extern "C" {
121063#endif  /* __cplusplus */
121064
121065SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
121066
121067#if 0
121068}  /* extern "C" */
121069#endif  /* __cplusplus */
121070
121071/************** End of rtree.h ***********************************************/
121072/************** Continuing where we left off in main.c ***********************/
121073#endif
121074#ifdef SQLITE_ENABLE_ICU
121075/************** Include sqliteicu.h in the middle of main.c ******************/
121076/************** Begin file sqliteicu.h ***************************************/
121077/*
121078** 2008 May 26
121079**
121080** The author disclaims copyright to this source code.  In place of
121081** a legal notice, here is a blessing:
121082**
121083**    May you do good and not evil.
121084**    May you find forgiveness for yourself and forgive others.
121085**    May you share freely, never taking more than you give.
121086**
121087******************************************************************************
121088**
121089** This header file is used by programs that want to link against the
121090** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
121091*/
121092
121093#if 0
121094extern "C" {
121095#endif  /* __cplusplus */
121096
121097SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
121098
121099#if 0
121100}  /* extern "C" */
121101#endif  /* __cplusplus */
121102
121103
121104/************** End of sqliteicu.h *******************************************/
121105/************** Continuing where we left off in main.c ***********************/
121106#endif
121107
121108#ifndef SQLITE_AMALGAMATION
121109/* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
121110** contains the text of SQLITE_VERSION macro.
121111*/
121112SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
121113#endif
121114
121115/* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
121116** a pointer to the to the sqlite3_version[] string constant.
121117*/
121118SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
121119
121120/* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
121121** pointer to a string constant whose value is the same as the
121122** SQLITE_SOURCE_ID C preprocessor macro.
121123*/
121124SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
121125
121126/* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
121127** returns an integer equal to SQLITE_VERSION_NUMBER.
121128*/
121129SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
121130
121131/* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
121132** zero if and only if SQLite was compiled with mutexing code omitted due to
121133** the SQLITE_THREADSAFE compile-time option being set to 0.
121134*/
121135SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
121136
121137#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
121138/*
121139** If the following function pointer is not NULL and if
121140** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
121141** I/O active are written using this function.  These messages
121142** are intended for debugging activity only.
121143*/
121144SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
121145#endif
121146
121147/*
121148** If the following global variable points to a string which is the
121149** name of a directory, then that directory will be used to store
121150** temporary files.
121151**
121152** See also the "PRAGMA temp_store_directory" SQL command.
121153*/
121154SQLITE_API char *sqlite3_temp_directory = 0;
121155
121156/*
121157** If the following global variable points to a string which is the
121158** name of a directory, then that directory will be used to store
121159** all database files specified with a relative pathname.
121160**
121161** See also the "PRAGMA data_store_directory" SQL command.
121162*/
121163SQLITE_API char *sqlite3_data_directory = 0;
121164
121165/*
121166** Initialize SQLite.
121167**
121168** This routine must be called to initialize the memory allocation,
121169** VFS, and mutex subsystems prior to doing any serious work with
121170** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
121171** this routine will be called automatically by key routines such as
121172** sqlite3_open().
121173**
121174** This routine is a no-op except on its very first call for the process,
121175** or for the first call after a call to sqlite3_shutdown.
121176**
121177** The first thread to call this routine runs the initialization to
121178** completion.  If subsequent threads call this routine before the first
121179** thread has finished the initialization process, then the subsequent
121180** threads must block until the first thread finishes with the initialization.
121181**
121182** The first thread might call this routine recursively.  Recursive
121183** calls to this routine should not block, of course.  Otherwise the
121184** initialization process would never complete.
121185**
121186** Let X be the first thread to enter this routine.  Let Y be some other
121187** thread.  Then while the initial invocation of this routine by X is
121188** incomplete, it is required that:
121189**
121190**    *  Calls to this routine from Y must block until the outer-most
121191**       call by X completes.
121192**
121193**    *  Recursive calls to this routine from thread X return immediately
121194**       without blocking.
121195*/
121196SQLITE_API int sqlite3_initialize(void){
121197  MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
121198  int rc;                                      /* Result code */
121199#ifdef SQLITE_EXTRA_INIT
121200  int bRunExtraInit = 0;                       /* Extra initialization needed */
121201#endif
121202
121203#ifdef SQLITE_OMIT_WSD
121204  rc = sqlite3_wsd_init(4096, 24);
121205  if( rc!=SQLITE_OK ){
121206    return rc;
121207  }
121208#endif
121209
121210  /* If SQLite is already completely initialized, then this call
121211  ** to sqlite3_initialize() should be a no-op.  But the initialization
121212  ** must be complete.  So isInit must not be set until the very end
121213  ** of this routine.
121214  */
121215  if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
121216
121217  /* Make sure the mutex subsystem is initialized.  If unable to
121218  ** initialize the mutex subsystem, return early with the error.
121219  ** If the system is so sick that we are unable to allocate a mutex,
121220  ** there is not much SQLite is going to be able to do.
121221  **
121222  ** The mutex subsystem must take care of serializing its own
121223  ** initialization.
121224  */
121225  rc = sqlite3MutexInit();
121226  if( rc ) return rc;
121227
121228  /* Initialize the malloc() system and the recursive pInitMutex mutex.
121229  ** This operation is protected by the STATIC_MASTER mutex.  Note that
121230  ** MutexAlloc() is called for a static mutex prior to initializing the
121231  ** malloc subsystem - this implies that the allocation of a static
121232  ** mutex must not require support from the malloc subsystem.
121233  */
121234  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
121235  sqlite3_mutex_enter(pMaster);
121236  sqlite3GlobalConfig.isMutexInit = 1;
121237  if( !sqlite3GlobalConfig.isMallocInit ){
121238    rc = sqlite3MallocInit();
121239  }
121240  if( rc==SQLITE_OK ){
121241    sqlite3GlobalConfig.isMallocInit = 1;
121242    if( !sqlite3GlobalConfig.pInitMutex ){
121243      sqlite3GlobalConfig.pInitMutex =
121244           sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
121245      if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
121246        rc = SQLITE_NOMEM;
121247      }
121248    }
121249  }
121250  if( rc==SQLITE_OK ){
121251    sqlite3GlobalConfig.nRefInitMutex++;
121252  }
121253  sqlite3_mutex_leave(pMaster);
121254
121255  /* If rc is not SQLITE_OK at this point, then either the malloc
121256  ** subsystem could not be initialized or the system failed to allocate
121257  ** the pInitMutex mutex. Return an error in either case.  */
121258  if( rc!=SQLITE_OK ){
121259    return rc;
121260  }
121261
121262  /* Do the rest of the initialization under the recursive mutex so
121263  ** that we will be able to handle recursive calls into
121264  ** sqlite3_initialize().  The recursive calls normally come through
121265  ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
121266  ** recursive calls might also be possible.
121267  **
121268  ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
121269  ** to the xInit method, so the xInit method need not be threadsafe.
121270  **
121271  ** The following mutex is what serializes access to the appdef pcache xInit
121272  ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
121273  ** call to sqlite3PcacheInitialize().
121274  */
121275  sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
121276  if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
121277    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
121278    sqlite3GlobalConfig.inProgress = 1;
121279    memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
121280    sqlite3RegisterGlobalFunctions();
121281    if( sqlite3GlobalConfig.isPCacheInit==0 ){
121282      rc = sqlite3PcacheInitialize();
121283    }
121284    if( rc==SQLITE_OK ){
121285      sqlite3GlobalConfig.isPCacheInit = 1;
121286      rc = sqlite3OsInit();
121287    }
121288    if( rc==SQLITE_OK ){
121289      sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
121290          sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
121291      sqlite3GlobalConfig.isInit = 1;
121292#ifdef SQLITE_EXTRA_INIT
121293      bRunExtraInit = 1;
121294#endif
121295    }
121296    sqlite3GlobalConfig.inProgress = 0;
121297  }
121298  sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
121299
121300  /* Go back under the static mutex and clean up the recursive
121301  ** mutex to prevent a resource leak.
121302  */
121303  sqlite3_mutex_enter(pMaster);
121304  sqlite3GlobalConfig.nRefInitMutex--;
121305  if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
121306    assert( sqlite3GlobalConfig.nRefInitMutex==0 );
121307    sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
121308    sqlite3GlobalConfig.pInitMutex = 0;
121309  }
121310  sqlite3_mutex_leave(pMaster);
121311
121312  /* The following is just a sanity check to make sure SQLite has
121313  ** been compiled correctly.  It is important to run this code, but
121314  ** we don't want to run it too often and soak up CPU cycles for no
121315  ** reason.  So we run it once during initialization.
121316  */
121317#ifndef NDEBUG
121318#ifndef SQLITE_OMIT_FLOATING_POINT
121319  /* This section of code's only "output" is via assert() statements. */
121320  if ( rc==SQLITE_OK ){
121321    u64 x = (((u64)1)<<63)-1;
121322    double y;
121323    assert(sizeof(x)==8);
121324    assert(sizeof(x)==sizeof(y));
121325    memcpy(&y, &x, 8);
121326    assert( sqlite3IsNaN(y) );
121327  }
121328#endif
121329#endif
121330
121331  /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
121332  ** compile-time option.
121333  */
121334#ifdef SQLITE_EXTRA_INIT
121335  if( bRunExtraInit ){
121336    int SQLITE_EXTRA_INIT(const char*);
121337    rc = SQLITE_EXTRA_INIT(0);
121338  }
121339#endif
121340
121341  return rc;
121342}
121343
121344/*
121345** Undo the effects of sqlite3_initialize().  Must not be called while
121346** there are outstanding database connections or memory allocations or
121347** while any part of SQLite is otherwise in use in any thread.  This
121348** routine is not threadsafe.  But it is safe to invoke this routine
121349** on when SQLite is already shut down.  If SQLite is already shut down
121350** when this routine is invoked, then this routine is a harmless no-op.
121351*/
121352SQLITE_API int sqlite3_shutdown(void){
121353  if( sqlite3GlobalConfig.isInit ){
121354#ifdef SQLITE_EXTRA_SHUTDOWN
121355    void SQLITE_EXTRA_SHUTDOWN(void);
121356    SQLITE_EXTRA_SHUTDOWN();
121357#endif
121358    sqlite3_os_end();
121359    sqlite3_reset_auto_extension();
121360    sqlite3GlobalConfig.isInit = 0;
121361  }
121362  if( sqlite3GlobalConfig.isPCacheInit ){
121363    sqlite3PcacheShutdown();
121364    sqlite3GlobalConfig.isPCacheInit = 0;
121365  }
121366  if( sqlite3GlobalConfig.isMallocInit ){
121367    sqlite3MallocEnd();
121368    sqlite3GlobalConfig.isMallocInit = 0;
121369
121370#ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
121371    /* The heap subsystem has now been shutdown and these values are supposed
121372    ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
121373    ** which would rely on that heap subsystem; therefore, make sure these
121374    ** values cannot refer to heap memory that was just invalidated when the
121375    ** heap subsystem was shutdown.  This is only done if the current call to
121376    ** this function resulted in the heap subsystem actually being shutdown.
121377    */
121378    sqlite3_data_directory = 0;
121379    sqlite3_temp_directory = 0;
121380#endif
121381  }
121382  if( sqlite3GlobalConfig.isMutexInit ){
121383    sqlite3MutexEnd();
121384    sqlite3GlobalConfig.isMutexInit = 0;
121385  }
121386
121387  return SQLITE_OK;
121388}
121389
121390/*
121391** This API allows applications to modify the global configuration of
121392** the SQLite library at run-time.
121393**
121394** This routine should only be called when there are no outstanding
121395** database connections or memory allocations.  This routine is not
121396** threadsafe.  Failure to heed these warnings can lead to unpredictable
121397** behavior.
121398*/
121399SQLITE_API int sqlite3_config(int op, ...){
121400  va_list ap;
121401  int rc = SQLITE_OK;
121402
121403  /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
121404  ** the SQLite library is in use. */
121405  if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
121406
121407  va_start(ap, op);
121408  switch( op ){
121409
121410    /* Mutex configuration options are only available in a threadsafe
121411    ** compile.
121412    */
121413#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
121414    case SQLITE_CONFIG_SINGLETHREAD: {
121415      /* Disable all mutexing */
121416      sqlite3GlobalConfig.bCoreMutex = 0;
121417      sqlite3GlobalConfig.bFullMutex = 0;
121418      break;
121419    }
121420    case SQLITE_CONFIG_MULTITHREAD: {
121421      /* Disable mutexing of database connections */
121422      /* Enable mutexing of core data structures */
121423      sqlite3GlobalConfig.bCoreMutex = 1;
121424      sqlite3GlobalConfig.bFullMutex = 0;
121425      break;
121426    }
121427    case SQLITE_CONFIG_SERIALIZED: {
121428      /* Enable all mutexing */
121429      sqlite3GlobalConfig.bCoreMutex = 1;
121430      sqlite3GlobalConfig.bFullMutex = 1;
121431      break;
121432    }
121433    case SQLITE_CONFIG_MUTEX: {
121434      /* Specify an alternative mutex implementation */
121435      sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
121436      break;
121437    }
121438    case SQLITE_CONFIG_GETMUTEX: {
121439      /* Retrieve the current mutex implementation */
121440      *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
121441      break;
121442    }
121443#endif
121444
121445
121446    case SQLITE_CONFIG_MALLOC: {
121447      /* Specify an alternative malloc implementation */
121448      sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
121449      break;
121450    }
121451    case SQLITE_CONFIG_GETMALLOC: {
121452      /* Retrieve the current malloc() implementation */
121453      if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
121454      *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
121455      break;
121456    }
121457    case SQLITE_CONFIG_MEMSTATUS: {
121458      /* Enable or disable the malloc status collection */
121459      sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
121460      break;
121461    }
121462    case SQLITE_CONFIG_SCRATCH: {
121463      /* Designate a buffer for scratch memory space */
121464      sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
121465      sqlite3GlobalConfig.szScratch = va_arg(ap, int);
121466      sqlite3GlobalConfig.nScratch = va_arg(ap, int);
121467      break;
121468    }
121469    case SQLITE_CONFIG_PAGECACHE: {
121470      /* Designate a buffer for page cache memory space */
121471      sqlite3GlobalConfig.pPage = va_arg(ap, void*);
121472      sqlite3GlobalConfig.szPage = va_arg(ap, int);
121473      sqlite3GlobalConfig.nPage = va_arg(ap, int);
121474      break;
121475    }
121476
121477    case SQLITE_CONFIG_PCACHE: {
121478      /* no-op */
121479      break;
121480    }
121481    case SQLITE_CONFIG_GETPCACHE: {
121482      /* now an error */
121483      rc = SQLITE_ERROR;
121484      break;
121485    }
121486
121487    case SQLITE_CONFIG_PCACHE2: {
121488      /* Specify an alternative page cache implementation */
121489      sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
121490      break;
121491    }
121492    case SQLITE_CONFIG_GETPCACHE2: {
121493      if( sqlite3GlobalConfig.pcache2.xInit==0 ){
121494        sqlite3PCacheSetDefault();
121495      }
121496      *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
121497      break;
121498    }
121499
121500#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
121501    case SQLITE_CONFIG_HEAP: {
121502      /* Designate a buffer for heap memory space */
121503      sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
121504      sqlite3GlobalConfig.nHeap = va_arg(ap, int);
121505      sqlite3GlobalConfig.mnReq = va_arg(ap, int);
121506
121507      if( sqlite3GlobalConfig.mnReq<1 ){
121508        sqlite3GlobalConfig.mnReq = 1;
121509      }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
121510        /* cap min request size at 2^12 */
121511        sqlite3GlobalConfig.mnReq = (1<<12);
121512      }
121513
121514      if( sqlite3GlobalConfig.pHeap==0 ){
121515        /* If the heap pointer is NULL, then restore the malloc implementation
121516        ** back to NULL pointers too.  This will cause the malloc to go
121517        ** back to its default implementation when sqlite3_initialize() is
121518        ** run.
121519        */
121520        memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
121521      }else{
121522        /* The heap pointer is not NULL, then install one of the
121523        ** mem5.c/mem3.c methods.  The enclosing #if guarantees at
121524        ** least one of these methods is currently enabled.
121525        */
121526#ifdef SQLITE_ENABLE_MEMSYS3
121527        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
121528#endif
121529#ifdef SQLITE_ENABLE_MEMSYS5
121530        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
121531#endif
121532      }
121533      break;
121534    }
121535#endif
121536
121537    case SQLITE_CONFIG_LOOKASIDE: {
121538      sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
121539      sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
121540      break;
121541    }
121542
121543    /* Record a pointer to the logger function and its first argument.
121544    ** The default is NULL.  Logging is disabled if the function pointer is
121545    ** NULL.
121546    */
121547    case SQLITE_CONFIG_LOG: {
121548      /* MSVC is picky about pulling func ptrs from va lists.
121549      ** http://support.microsoft.com/kb/47961
121550      ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
121551      */
121552      typedef void(*LOGFUNC_t)(void*,int,const char*);
121553      sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
121554      sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
121555      break;
121556    }
121557
121558    case SQLITE_CONFIG_URI: {
121559      sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
121560      break;
121561    }
121562
121563    case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
121564      sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
121565      break;
121566    }
121567
121568#ifdef SQLITE_ENABLE_SQLLOG
121569    case SQLITE_CONFIG_SQLLOG: {
121570      typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
121571      sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
121572      sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
121573      break;
121574    }
121575#endif
121576
121577    case SQLITE_CONFIG_MMAP_SIZE: {
121578      sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
121579      sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
121580      if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
121581        mxMmap = SQLITE_MAX_MMAP_SIZE;
121582      }
121583      sqlite3GlobalConfig.mxMmap = mxMmap;
121584      if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
121585      if( szMmap>mxMmap) szMmap = mxMmap;
121586      sqlite3GlobalConfig.szMmap = szMmap;
121587      break;
121588    }
121589
121590#if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC)
121591    case SQLITE_CONFIG_WIN32_HEAPSIZE: {
121592      sqlite3GlobalConfig.nHeap = va_arg(ap, int);
121593      break;
121594    }
121595#endif
121596
121597    default: {
121598      rc = SQLITE_ERROR;
121599      break;
121600    }
121601  }
121602  va_end(ap);
121603  return rc;
121604}
121605
121606/*
121607** Set up the lookaside buffers for a database connection.
121608** Return SQLITE_OK on success.
121609** If lookaside is already active, return SQLITE_BUSY.
121610**
121611** The sz parameter is the number of bytes in each lookaside slot.
121612** The cnt parameter is the number of slots.  If pStart is NULL the
121613** space for the lookaside memory is obtained from sqlite3_malloc().
121614** If pStart is not NULL then it is sz*cnt bytes of memory to use for
121615** the lookaside memory.
121616*/
121617static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
121618  void *pStart;
121619  if( db->lookaside.nOut ){
121620    return SQLITE_BUSY;
121621  }
121622  /* Free any existing lookaside buffer for this handle before
121623  ** allocating a new one so we don't have to have space for
121624  ** both at the same time.
121625  */
121626  if( db->lookaside.bMalloced ){
121627    sqlite3_free(db->lookaside.pStart);
121628  }
121629  /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
121630  ** than a pointer to be useful.
121631  */
121632  sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
121633  if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
121634  if( cnt<0 ) cnt = 0;
121635  if( sz==0 || cnt==0 ){
121636    sz = 0;
121637    pStart = 0;
121638  }else if( pBuf==0 ){
121639    sqlite3BeginBenignMalloc();
121640    pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
121641    sqlite3EndBenignMalloc();
121642    if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
121643  }else{
121644    pStart = pBuf;
121645  }
121646  db->lookaside.pStart = pStart;
121647  db->lookaside.pFree = 0;
121648  db->lookaside.sz = (u16)sz;
121649  if( pStart ){
121650    int i;
121651    LookasideSlot *p;
121652    assert( sz > (int)sizeof(LookasideSlot*) );
121653    p = (LookasideSlot*)pStart;
121654    for(i=cnt-1; i>=0; i--){
121655      p->pNext = db->lookaside.pFree;
121656      db->lookaside.pFree = p;
121657      p = (LookasideSlot*)&((u8*)p)[sz];
121658    }
121659    db->lookaside.pEnd = p;
121660    db->lookaside.bEnabled = 1;
121661    db->lookaside.bMalloced = pBuf==0 ?1:0;
121662  }else{
121663    db->lookaside.pStart = db;
121664    db->lookaside.pEnd = db;
121665    db->lookaside.bEnabled = 0;
121666    db->lookaside.bMalloced = 0;
121667  }
121668  return SQLITE_OK;
121669}
121670
121671/*
121672** Return the mutex associated with a database connection.
121673*/
121674SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
121675  return db->mutex;
121676}
121677
121678/*
121679** Free up as much memory as we can from the given database
121680** connection.
121681*/
121682SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
121683  int i;
121684  sqlite3_mutex_enter(db->mutex);
121685  sqlite3BtreeEnterAll(db);
121686  for(i=0; i<db->nDb; i++){
121687    Btree *pBt = db->aDb[i].pBt;
121688    if( pBt ){
121689      Pager *pPager = sqlite3BtreePager(pBt);
121690      sqlite3PagerShrink(pPager);
121691    }
121692  }
121693  sqlite3BtreeLeaveAll(db);
121694  sqlite3_mutex_leave(db->mutex);
121695  return SQLITE_OK;
121696}
121697
121698/*
121699** Configuration settings for an individual database connection
121700*/
121701SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
121702  va_list ap;
121703  int rc;
121704  va_start(ap, op);
121705  switch( op ){
121706    case SQLITE_DBCONFIG_LOOKASIDE: {
121707      void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
121708      int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
121709      int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
121710      rc = setupLookaside(db, pBuf, sz, cnt);
121711      break;
121712    }
121713    default: {
121714      static const struct {
121715        int op;      /* The opcode */
121716        u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
121717      } aFlagOp[] = {
121718        { SQLITE_DBCONFIG_ENABLE_FKEY,    SQLITE_ForeignKeys    },
121719        { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger  },
121720      };
121721      unsigned int i;
121722      rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
121723      for(i=0; i<ArraySize(aFlagOp); i++){
121724        if( aFlagOp[i].op==op ){
121725          int onoff = va_arg(ap, int);
121726          int *pRes = va_arg(ap, int*);
121727          int oldFlags = db->flags;
121728          if( onoff>0 ){
121729            db->flags |= aFlagOp[i].mask;
121730          }else if( onoff==0 ){
121731            db->flags &= ~aFlagOp[i].mask;
121732          }
121733          if( oldFlags!=db->flags ){
121734            sqlite3ExpirePreparedStatements(db);
121735          }
121736          if( pRes ){
121737            *pRes = (db->flags & aFlagOp[i].mask)!=0;
121738          }
121739          rc = SQLITE_OK;
121740          break;
121741        }
121742      }
121743      break;
121744    }
121745  }
121746  va_end(ap);
121747  return rc;
121748}
121749
121750
121751/*
121752** Return true if the buffer z[0..n-1] contains all spaces.
121753*/
121754static int allSpaces(const char *z, int n){
121755  while( n>0 && z[n-1]==' ' ){ n--; }
121756  return n==0;
121757}
121758
121759/*
121760** This is the default collating function named "BINARY" which is always
121761** available.
121762**
121763** If the padFlag argument is not NULL then space padding at the end
121764** of strings is ignored.  This implements the RTRIM collation.
121765*/
121766static int binCollFunc(
121767  void *padFlag,
121768  int nKey1, const void *pKey1,
121769  int nKey2, const void *pKey2
121770){
121771  int rc, n;
121772  n = nKey1<nKey2 ? nKey1 : nKey2;
121773  rc = memcmp(pKey1, pKey2, n);
121774  if( rc==0 ){
121775    if( padFlag
121776     && allSpaces(((char*)pKey1)+n, nKey1-n)
121777     && allSpaces(((char*)pKey2)+n, nKey2-n)
121778    ){
121779      /* Leave rc unchanged at 0 */
121780    }else{
121781      rc = nKey1 - nKey2;
121782    }
121783  }
121784  return rc;
121785}
121786
121787/*
121788** Another built-in collating sequence: NOCASE.
121789**
121790** This collating sequence is intended to be used for "case independent
121791** comparison". SQLite's knowledge of upper and lower case equivalents
121792** extends only to the 26 characters used in the English language.
121793**
121794** At the moment there is only a UTF-8 implementation.
121795*/
121796static int nocaseCollatingFunc(
121797  void *NotUsed,
121798  int nKey1, const void *pKey1,
121799  int nKey2, const void *pKey2
121800){
121801  int r = sqlite3StrNICmp(
121802      (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
121803  UNUSED_PARAMETER(NotUsed);
121804  if( 0==r ){
121805    r = nKey1-nKey2;
121806  }
121807  return r;
121808}
121809
121810/*
121811** Return the ROWID of the most recent insert
121812*/
121813SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
121814  return db->lastRowid;
121815}
121816
121817/*
121818** Return the number of changes in the most recent call to sqlite3_exec().
121819*/
121820SQLITE_API int sqlite3_changes(sqlite3 *db){
121821  return db->nChange;
121822}
121823
121824/*
121825** Return the number of changes since the database handle was opened.
121826*/
121827SQLITE_API int sqlite3_total_changes(sqlite3 *db){
121828  return db->nTotalChange;
121829}
121830
121831/*
121832** Close all open savepoints. This function only manipulates fields of the
121833** database handle object, it does not close any savepoints that may be open
121834** at the b-tree/pager level.
121835*/
121836SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
121837  while( db->pSavepoint ){
121838    Savepoint *pTmp = db->pSavepoint;
121839    db->pSavepoint = pTmp->pNext;
121840    sqlite3DbFree(db, pTmp);
121841  }
121842  db->nSavepoint = 0;
121843  db->nStatement = 0;
121844  db->isTransactionSavepoint = 0;
121845}
121846
121847/*
121848** Invoke the destructor function associated with FuncDef p, if any. Except,
121849** if this is not the last copy of the function, do not invoke it. Multiple
121850** copies of a single function are created when create_function() is called
121851** with SQLITE_ANY as the encoding.
121852*/
121853static void functionDestroy(sqlite3 *db, FuncDef *p){
121854  FuncDestructor *pDestructor = p->pDestructor;
121855  if( pDestructor ){
121856    pDestructor->nRef--;
121857    if( pDestructor->nRef==0 ){
121858      pDestructor->xDestroy(pDestructor->pUserData);
121859      sqlite3DbFree(db, pDestructor);
121860    }
121861  }
121862}
121863
121864/*
121865** Disconnect all sqlite3_vtab objects that belong to database connection
121866** db. This is called when db is being closed.
121867*/
121868static void disconnectAllVtab(sqlite3 *db){
121869#ifndef SQLITE_OMIT_VIRTUALTABLE
121870  int i;
121871  sqlite3BtreeEnterAll(db);
121872  for(i=0; i<db->nDb; i++){
121873    Schema *pSchema = db->aDb[i].pSchema;
121874    if( db->aDb[i].pSchema ){
121875      HashElem *p;
121876      for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
121877        Table *pTab = (Table *)sqliteHashData(p);
121878        if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
121879      }
121880    }
121881  }
121882  sqlite3VtabUnlockList(db);
121883  sqlite3BtreeLeaveAll(db);
121884#else
121885  UNUSED_PARAMETER(db);
121886#endif
121887}
121888
121889/*
121890** Return TRUE if database connection db has unfinalized prepared
121891** statements or unfinished sqlite3_backup objects.
121892*/
121893static int connectionIsBusy(sqlite3 *db){
121894  int j;
121895  assert( sqlite3_mutex_held(db->mutex) );
121896  if( db->pVdbe ) return 1;
121897  for(j=0; j<db->nDb; j++){
121898    Btree *pBt = db->aDb[j].pBt;
121899    if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
121900  }
121901  return 0;
121902}
121903
121904/*
121905** Close an existing SQLite database
121906*/
121907static int sqlite3Close(sqlite3 *db, int forceZombie){
121908  if( !db ){
121909    return SQLITE_OK;
121910  }
121911  if( !sqlite3SafetyCheckSickOrOk(db) ){
121912    return SQLITE_MISUSE_BKPT;
121913  }
121914  sqlite3_mutex_enter(db->mutex);
121915
121916  /* Force xDisconnect calls on all virtual tables */
121917  disconnectAllVtab(db);
121918
121919  /* If a transaction is open, the disconnectAllVtab() call above
121920  ** will not have called the xDisconnect() method on any virtual
121921  ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
121922  ** call will do so. We need to do this before the check for active
121923  ** SQL statements below, as the v-table implementation may be storing
121924  ** some prepared statements internally.
121925  */
121926  sqlite3VtabRollback(db);
121927
121928  /* Legacy behavior (sqlite3_close() behavior) is to return
121929  ** SQLITE_BUSY if the connection can not be closed immediately.
121930  */
121931  if( !forceZombie && connectionIsBusy(db) ){
121932    sqlite3Error(db, SQLITE_BUSY, "unable to close due to unfinalized "
121933       "statements or unfinished backups");
121934    sqlite3_mutex_leave(db->mutex);
121935    return SQLITE_BUSY;
121936  }
121937
121938#ifdef SQLITE_ENABLE_SQLLOG
121939  if( sqlite3GlobalConfig.xSqllog ){
121940    /* Closing the handle. Fourth parameter is passed the value 2. */
121941    sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
121942  }
121943#endif
121944
121945  /* Convert the connection into a zombie and then close it.
121946  */
121947  db->magic = SQLITE_MAGIC_ZOMBIE;
121948  sqlite3LeaveMutexAndCloseZombie(db);
121949  return SQLITE_OK;
121950}
121951
121952/*
121953** Two variations on the public interface for closing a database
121954** connection. The sqlite3_close() version returns SQLITE_BUSY and
121955** leaves the connection option if there are unfinalized prepared
121956** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
121957** version forces the connection to become a zombie if there are
121958** unclosed resources, and arranges for deallocation when the last
121959** prepare statement or sqlite3_backup closes.
121960*/
121961SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
121962SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
121963
121964
121965/*
121966** Close the mutex on database connection db.
121967**
121968** Furthermore, if database connection db is a zombie (meaning that there
121969** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
121970** every sqlite3_stmt has now been finalized and every sqlite3_backup has
121971** finished, then free all resources.
121972*/
121973SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
121974  HashElem *i;                    /* Hash table iterator */
121975  int j;
121976
121977  /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
121978  ** or if the connection has not yet been closed by sqlite3_close_v2(),
121979  ** then just leave the mutex and return.
121980  */
121981  if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
121982    sqlite3_mutex_leave(db->mutex);
121983    return;
121984  }
121985
121986  /* If we reach this point, it means that the database connection has
121987  ** closed all sqlite3_stmt and sqlite3_backup objects and has been
121988  ** passed to sqlite3_close (meaning that it is a zombie).  Therefore,
121989  ** go ahead and free all resources.
121990  */
121991
121992  /* If a transaction is open, roll it back. This also ensures that if
121993  ** any database schemas have been modified by an uncommitted transaction
121994  ** they are reset. And that the required b-tree mutex is held to make
121995  ** the pager rollback and schema reset an atomic operation. */
121996  sqlite3RollbackAll(db, SQLITE_OK);
121997
121998  /* Free any outstanding Savepoint structures. */
121999  sqlite3CloseSavepoints(db);
122000
122001  /* Close all database connections */
122002  for(j=0; j<db->nDb; j++){
122003    struct Db *pDb = &db->aDb[j];
122004    if( pDb->pBt ){
122005      sqlite3BtreeClose(pDb->pBt);
122006      pDb->pBt = 0;
122007      if( j!=1 ){
122008        pDb->pSchema = 0;
122009      }
122010    }
122011  }
122012  /* Clear the TEMP schema separately and last */
122013  if( db->aDb[1].pSchema ){
122014    sqlite3SchemaClear(db->aDb[1].pSchema);
122015  }
122016  sqlite3VtabUnlockList(db);
122017
122018  /* Free up the array of auxiliary databases */
122019  sqlite3CollapseDatabaseArray(db);
122020  assert( db->nDb<=2 );
122021  assert( db->aDb==db->aDbStatic );
122022
122023  /* Tell the code in notify.c that the connection no longer holds any
122024  ** locks and does not require any further unlock-notify callbacks.
122025  */
122026  sqlite3ConnectionClosed(db);
122027
122028  for(j=0; j<ArraySize(db->aFunc.a); j++){
122029    FuncDef *pNext, *pHash, *p;
122030    for(p=db->aFunc.a[j]; p; p=pHash){
122031      pHash = p->pHash;
122032      while( p ){
122033        functionDestroy(db, p);
122034        pNext = p->pNext;
122035        sqlite3DbFree(db, p);
122036        p = pNext;
122037      }
122038    }
122039  }
122040  for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
122041    CollSeq *pColl = (CollSeq *)sqliteHashData(i);
122042    /* Invoke any destructors registered for collation sequence user data. */
122043    for(j=0; j<3; j++){
122044      if( pColl[j].xDel ){
122045        pColl[j].xDel(pColl[j].pUser);
122046      }
122047    }
122048    sqlite3DbFree(db, pColl);
122049  }
122050  sqlite3HashClear(&db->aCollSeq);
122051#ifndef SQLITE_OMIT_VIRTUALTABLE
122052  for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
122053    Module *pMod = (Module *)sqliteHashData(i);
122054    if( pMod->xDestroy ){
122055      pMod->xDestroy(pMod->pAux);
122056    }
122057    sqlite3DbFree(db, pMod);
122058  }
122059  sqlite3HashClear(&db->aModule);
122060#endif
122061
122062  sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
122063  sqlite3ValueFree(db->pErr);
122064  sqlite3CloseExtensions(db);
122065
122066  db->magic = SQLITE_MAGIC_ERROR;
122067
122068  /* The temp-database schema is allocated differently from the other schema
122069  ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
122070  ** So it needs to be freed here. Todo: Why not roll the temp schema into
122071  ** the same sqliteMalloc() as the one that allocates the database
122072  ** structure?
122073  */
122074  sqlite3DbFree(db, db->aDb[1].pSchema);
122075  sqlite3_mutex_leave(db->mutex);
122076  db->magic = SQLITE_MAGIC_CLOSED;
122077  sqlite3_mutex_free(db->mutex);
122078  assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
122079  if( db->lookaside.bMalloced ){
122080    sqlite3_free(db->lookaside.pStart);
122081  }
122082  sqlite3_free(db);
122083}
122084
122085/*
122086** Rollback all database files.  If tripCode is not SQLITE_OK, then
122087** any open cursors are invalidated ("tripped" - as in "tripping a circuit
122088** breaker") and made to return tripCode if there are any further
122089** attempts to use that cursor.
122090*/
122091SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
122092  int i;
122093  int inTrans = 0;
122094  assert( sqlite3_mutex_held(db->mutex) );
122095  sqlite3BeginBenignMalloc();
122096
122097  /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
122098  ** This is important in case the transaction being rolled back has
122099  ** modified the database schema. If the b-tree mutexes are not taken
122100  ** here, then another shared-cache connection might sneak in between
122101  ** the database rollback and schema reset, which can cause false
122102  ** corruption reports in some cases.  */
122103  sqlite3BtreeEnterAll(db);
122104
122105  for(i=0; i<db->nDb; i++){
122106    Btree *p = db->aDb[i].pBt;
122107    if( p ){
122108      if( sqlite3BtreeIsInTrans(p) ){
122109        inTrans = 1;
122110      }
122111      sqlite3BtreeRollback(p, tripCode);
122112    }
122113  }
122114  sqlite3VtabRollback(db);
122115  sqlite3EndBenignMalloc();
122116
122117  if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
122118    sqlite3ExpirePreparedStatements(db);
122119    sqlite3ResetAllSchemasOfConnection(db);
122120  }
122121  sqlite3BtreeLeaveAll(db);
122122
122123  /* Any deferred constraint violations have now been resolved. */
122124  db->nDeferredCons = 0;
122125  db->nDeferredImmCons = 0;
122126  db->flags &= ~SQLITE_DeferFKs;
122127
122128  /* If one has been configured, invoke the rollback-hook callback */
122129  if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
122130    db->xRollbackCallback(db->pRollbackArg);
122131  }
122132}
122133
122134/*
122135** Return a static string containing the name corresponding to the error code
122136** specified in the argument.
122137*/
122138#if defined(SQLITE_TEST)
122139SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
122140  const char *zName = 0;
122141  int i, origRc = rc;
122142  for(i=0; i<2 && zName==0; i++, rc &= 0xff){
122143    switch( rc ){
122144      case SQLITE_OK:                 zName = "SQLITE_OK";                break;
122145      case SQLITE_ERROR:              zName = "SQLITE_ERROR";             break;
122146      case SQLITE_INTERNAL:           zName = "SQLITE_INTERNAL";          break;
122147      case SQLITE_PERM:               zName = "SQLITE_PERM";              break;
122148      case SQLITE_ABORT:              zName = "SQLITE_ABORT";             break;
122149      case SQLITE_ABORT_ROLLBACK:     zName = "SQLITE_ABORT_ROLLBACK";    break;
122150      case SQLITE_BUSY:               zName = "SQLITE_BUSY";              break;
122151      case SQLITE_BUSY_RECOVERY:      zName = "SQLITE_BUSY_RECOVERY";     break;
122152      case SQLITE_BUSY_SNAPSHOT:      zName = "SQLITE_BUSY_SNAPSHOT";     break;
122153      case SQLITE_LOCKED:             zName = "SQLITE_LOCKED";            break;
122154      case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
122155      case SQLITE_NOMEM:              zName = "SQLITE_NOMEM";             break;
122156      case SQLITE_READONLY:           zName = "SQLITE_READONLY";          break;
122157      case SQLITE_READONLY_RECOVERY:  zName = "SQLITE_READONLY_RECOVERY"; break;
122158      case SQLITE_READONLY_CANTLOCK:  zName = "SQLITE_READONLY_CANTLOCK"; break;
122159      case SQLITE_READONLY_ROLLBACK:  zName = "SQLITE_READONLY_ROLLBACK"; break;
122160      case SQLITE_READONLY_DBMOVED:   zName = "SQLITE_READONLY_DBMOVED";  break;
122161      case SQLITE_INTERRUPT:          zName = "SQLITE_INTERRUPT";         break;
122162      case SQLITE_IOERR:              zName = "SQLITE_IOERR";             break;
122163      case SQLITE_IOERR_READ:         zName = "SQLITE_IOERR_READ";        break;
122164      case SQLITE_IOERR_SHORT_READ:   zName = "SQLITE_IOERR_SHORT_READ";  break;
122165      case SQLITE_IOERR_WRITE:        zName = "SQLITE_IOERR_WRITE";       break;
122166      case SQLITE_IOERR_FSYNC:        zName = "SQLITE_IOERR_FSYNC";       break;
122167      case SQLITE_IOERR_DIR_FSYNC:    zName = "SQLITE_IOERR_DIR_FSYNC";   break;
122168      case SQLITE_IOERR_TRUNCATE:     zName = "SQLITE_IOERR_TRUNCATE";    break;
122169      case SQLITE_IOERR_FSTAT:        zName = "SQLITE_IOERR_FSTAT";       break;
122170      case SQLITE_IOERR_UNLOCK:       zName = "SQLITE_IOERR_UNLOCK";      break;
122171      case SQLITE_IOERR_RDLOCK:       zName = "SQLITE_IOERR_RDLOCK";      break;
122172      case SQLITE_IOERR_DELETE:       zName = "SQLITE_IOERR_DELETE";      break;
122173      case SQLITE_IOERR_BLOCKED:      zName = "SQLITE_IOERR_BLOCKED";     break;
122174      case SQLITE_IOERR_NOMEM:        zName = "SQLITE_IOERR_NOMEM";       break;
122175      case SQLITE_IOERR_ACCESS:       zName = "SQLITE_IOERR_ACCESS";      break;
122176      case SQLITE_IOERR_CHECKRESERVEDLOCK:
122177                                zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
122178      case SQLITE_IOERR_LOCK:         zName = "SQLITE_IOERR_LOCK";        break;
122179      case SQLITE_IOERR_CLOSE:        zName = "SQLITE_IOERR_CLOSE";       break;
122180      case SQLITE_IOERR_DIR_CLOSE:    zName = "SQLITE_IOERR_DIR_CLOSE";   break;
122181      case SQLITE_IOERR_SHMOPEN:      zName = "SQLITE_IOERR_SHMOPEN";     break;
122182      case SQLITE_IOERR_SHMSIZE:      zName = "SQLITE_IOERR_SHMSIZE";     break;
122183      case SQLITE_IOERR_SHMLOCK:      zName = "SQLITE_IOERR_SHMLOCK";     break;
122184      case SQLITE_IOERR_SHMMAP:       zName = "SQLITE_IOERR_SHMMAP";      break;
122185      case SQLITE_IOERR_SEEK:         zName = "SQLITE_IOERR_SEEK";        break;
122186      case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
122187      case SQLITE_IOERR_MMAP:         zName = "SQLITE_IOERR_MMAP";        break;
122188      case SQLITE_IOERR_GETTEMPPATH:  zName = "SQLITE_IOERR_GETTEMPPATH"; break;
122189      case SQLITE_IOERR_CONVPATH:     zName = "SQLITE_IOERR_CONVPATH";    break;
122190      case SQLITE_CORRUPT:            zName = "SQLITE_CORRUPT";           break;
122191      case SQLITE_CORRUPT_VTAB:       zName = "SQLITE_CORRUPT_VTAB";      break;
122192      case SQLITE_NOTFOUND:           zName = "SQLITE_NOTFOUND";          break;
122193      case SQLITE_FULL:               zName = "SQLITE_FULL";              break;
122194      case SQLITE_CANTOPEN:           zName = "SQLITE_CANTOPEN";          break;
122195      case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
122196      case SQLITE_CANTOPEN_ISDIR:     zName = "SQLITE_CANTOPEN_ISDIR";    break;
122197      case SQLITE_CANTOPEN_FULLPATH:  zName = "SQLITE_CANTOPEN_FULLPATH"; break;
122198      case SQLITE_CANTOPEN_CONVPATH:  zName = "SQLITE_CANTOPEN_CONVPATH"; break;
122199      case SQLITE_PROTOCOL:           zName = "SQLITE_PROTOCOL";          break;
122200      case SQLITE_EMPTY:              zName = "SQLITE_EMPTY";             break;
122201      case SQLITE_SCHEMA:             zName = "SQLITE_SCHEMA";            break;
122202      case SQLITE_TOOBIG:             zName = "SQLITE_TOOBIG";            break;
122203      case SQLITE_CONSTRAINT:         zName = "SQLITE_CONSTRAINT";        break;
122204      case SQLITE_CONSTRAINT_UNIQUE:  zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
122205      case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
122206      case SQLITE_CONSTRAINT_FOREIGNKEY:
122207                                zName = "SQLITE_CONSTRAINT_FOREIGNKEY";   break;
122208      case SQLITE_CONSTRAINT_CHECK:   zName = "SQLITE_CONSTRAINT_CHECK";  break;
122209      case SQLITE_CONSTRAINT_PRIMARYKEY:
122210                                zName = "SQLITE_CONSTRAINT_PRIMARYKEY";   break;
122211      case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
122212      case SQLITE_CONSTRAINT_COMMITHOOK:
122213                                zName = "SQLITE_CONSTRAINT_COMMITHOOK";   break;
122214      case SQLITE_CONSTRAINT_VTAB:    zName = "SQLITE_CONSTRAINT_VTAB";   break;
122215      case SQLITE_CONSTRAINT_FUNCTION:
122216                                zName = "SQLITE_CONSTRAINT_FUNCTION";     break;
122217      case SQLITE_CONSTRAINT_ROWID:   zName = "SQLITE_CONSTRAINT_ROWID";  break;
122218      case SQLITE_MISMATCH:           zName = "SQLITE_MISMATCH";          break;
122219      case SQLITE_MISUSE:             zName = "SQLITE_MISUSE";            break;
122220      case SQLITE_NOLFS:              zName = "SQLITE_NOLFS";             break;
122221      case SQLITE_AUTH:               zName = "SQLITE_AUTH";              break;
122222      case SQLITE_FORMAT:             zName = "SQLITE_FORMAT";            break;
122223      case SQLITE_RANGE:              zName = "SQLITE_RANGE";             break;
122224      case SQLITE_NOTADB:             zName = "SQLITE_NOTADB";            break;
122225      case SQLITE_ROW:                zName = "SQLITE_ROW";               break;
122226      case SQLITE_NOTICE:             zName = "SQLITE_NOTICE";            break;
122227      case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
122228      case SQLITE_NOTICE_RECOVER_ROLLBACK:
122229                                zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
122230      case SQLITE_WARNING:            zName = "SQLITE_WARNING";           break;
122231      case SQLITE_WARNING_AUTOINDEX:  zName = "SQLITE_WARNING_AUTOINDEX"; break;
122232      case SQLITE_DONE:               zName = "SQLITE_DONE";              break;
122233    }
122234  }
122235  if( zName==0 ){
122236    static char zBuf[50];
122237    sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
122238    zName = zBuf;
122239  }
122240  return zName;
122241}
122242#endif
122243
122244/*
122245** Return a static string that describes the kind of error specified in the
122246** argument.
122247*/
122248SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
122249  static const char* const aMsg[] = {
122250    /* SQLITE_OK          */ "not an error",
122251    /* SQLITE_ERROR       */ "SQL logic error or missing database",
122252    /* SQLITE_INTERNAL    */ 0,
122253    /* SQLITE_PERM        */ "access permission denied",
122254    /* SQLITE_ABORT       */ "callback requested query abort",
122255    /* SQLITE_BUSY        */ "database is locked",
122256    /* SQLITE_LOCKED      */ "database table is locked",
122257    /* SQLITE_NOMEM       */ "out of memory",
122258    /* SQLITE_READONLY    */ "attempt to write a readonly database",
122259    /* SQLITE_INTERRUPT   */ "interrupted",
122260    /* SQLITE_IOERR       */ "disk I/O error",
122261    /* SQLITE_CORRUPT     */ "database disk image is malformed",
122262    /* SQLITE_NOTFOUND    */ "unknown operation",
122263    /* SQLITE_FULL        */ "database or disk is full",
122264    /* SQLITE_CANTOPEN    */ "unable to open database file",
122265    /* SQLITE_PROTOCOL    */ "locking protocol",
122266    /* SQLITE_EMPTY       */ "table contains no data",
122267    /* SQLITE_SCHEMA      */ "database schema has changed",
122268    /* SQLITE_TOOBIG      */ "string or blob too big",
122269    /* SQLITE_CONSTRAINT  */ "constraint failed",
122270    /* SQLITE_MISMATCH    */ "datatype mismatch",
122271    /* SQLITE_MISUSE      */ "library routine called out of sequence",
122272    /* SQLITE_NOLFS       */ "large file support is disabled",
122273    /* SQLITE_AUTH        */ "authorization denied",
122274    /* SQLITE_FORMAT      */ "auxiliary database format error",
122275    /* SQLITE_RANGE       */ "bind or column index out of range",
122276    /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
122277  };
122278  const char *zErr = "unknown error";
122279  switch( rc ){
122280    case SQLITE_ABORT_ROLLBACK: {
122281      zErr = "abort due to ROLLBACK";
122282      break;
122283    }
122284    default: {
122285      rc &= 0xff;
122286      if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
122287        zErr = aMsg[rc];
122288      }
122289      break;
122290    }
122291  }
122292  return zErr;
122293}
122294
122295/*
122296** This routine implements a busy callback that sleeps and tries
122297** again until a timeout value is reached.  The timeout value is
122298** an integer number of milliseconds passed in as the first
122299** argument.
122300*/
122301static int sqliteDefaultBusyCallback(
122302 void *ptr,               /* Database connection */
122303 int count                /* Number of times table has been busy */
122304){
122305#if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
122306  static const u8 delays[] =
122307     { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
122308  static const u8 totals[] =
122309     { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
122310# define NDELAY ArraySize(delays)
122311  sqlite3 *db = (sqlite3 *)ptr;
122312  int timeout = db->busyTimeout;
122313  int delay, prior;
122314
122315  assert( count>=0 );
122316  if( count < NDELAY ){
122317    delay = delays[count];
122318    prior = totals[count];
122319  }else{
122320    delay = delays[NDELAY-1];
122321    prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
122322  }
122323  if( prior + delay > timeout ){
122324    delay = timeout - prior;
122325    if( delay<=0 ) return 0;
122326  }
122327  sqlite3OsSleep(db->pVfs, delay*1000);
122328  return 1;
122329#else
122330  sqlite3 *db = (sqlite3 *)ptr;
122331  int timeout = ((sqlite3 *)ptr)->busyTimeout;
122332  if( (count+1)*1000 > timeout ){
122333    return 0;
122334  }
122335  sqlite3OsSleep(db->pVfs, 1000000);
122336  return 1;
122337#endif
122338}
122339
122340/*
122341** Invoke the given busy handler.
122342**
122343** This routine is called when an operation failed with a lock.
122344** If this routine returns non-zero, the lock is retried.  If it
122345** returns 0, the operation aborts with an SQLITE_BUSY error.
122346*/
122347SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
122348  int rc;
122349  if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
122350  rc = p->xFunc(p->pArg, p->nBusy);
122351  if( rc==0 ){
122352    p->nBusy = -1;
122353  }else{
122354    p->nBusy++;
122355  }
122356  return rc;
122357}
122358
122359/*
122360** This routine sets the busy callback for an Sqlite database to the
122361** given callback function with the given argument.
122362*/
122363SQLITE_API int sqlite3_busy_handler(
122364  sqlite3 *db,
122365  int (*xBusy)(void*,int),
122366  void *pArg
122367){
122368  sqlite3_mutex_enter(db->mutex);
122369  db->busyHandler.xFunc = xBusy;
122370  db->busyHandler.pArg = pArg;
122371  db->busyHandler.nBusy = 0;
122372  db->busyTimeout = 0;
122373  sqlite3_mutex_leave(db->mutex);
122374  return SQLITE_OK;
122375}
122376
122377#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
122378/*
122379** This routine sets the progress callback for an Sqlite database to the
122380** given callback function with the given argument. The progress callback will
122381** be invoked every nOps opcodes.
122382*/
122383SQLITE_API void sqlite3_progress_handler(
122384  sqlite3 *db,
122385  int nOps,
122386  int (*xProgress)(void*),
122387  void *pArg
122388){
122389  sqlite3_mutex_enter(db->mutex);
122390  if( nOps>0 ){
122391    db->xProgress = xProgress;
122392    db->nProgressOps = (unsigned)nOps;
122393    db->pProgressArg = pArg;
122394  }else{
122395    db->xProgress = 0;
122396    db->nProgressOps = 0;
122397    db->pProgressArg = 0;
122398  }
122399  sqlite3_mutex_leave(db->mutex);
122400}
122401#endif
122402
122403
122404/*
122405** This routine installs a default busy handler that waits for the
122406** specified number of milliseconds before returning 0.
122407*/
122408SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
122409  if( ms>0 ){
122410    sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
122411    db->busyTimeout = ms;
122412  }else{
122413    sqlite3_busy_handler(db, 0, 0);
122414  }
122415  return SQLITE_OK;
122416}
122417
122418/*
122419** Cause any pending operation to stop at its earliest opportunity.
122420*/
122421SQLITE_API void sqlite3_interrupt(sqlite3 *db){
122422  db->u1.isInterrupted = 1;
122423}
122424
122425
122426/*
122427** This function is exactly the same as sqlite3_create_function(), except
122428** that it is designed to be called by internal code. The difference is
122429** that if a malloc() fails in sqlite3_create_function(), an error code
122430** is returned and the mallocFailed flag cleared.
122431*/
122432SQLITE_PRIVATE int sqlite3CreateFunc(
122433  sqlite3 *db,
122434  const char *zFunctionName,
122435  int nArg,
122436  int enc,
122437  void *pUserData,
122438  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
122439  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
122440  void (*xFinal)(sqlite3_context*),
122441  FuncDestructor *pDestructor
122442){
122443  FuncDef *p;
122444  int nName;
122445  int extraFlags;
122446
122447  assert( sqlite3_mutex_held(db->mutex) );
122448  if( zFunctionName==0 ||
122449      (xFunc && (xFinal || xStep)) ||
122450      (!xFunc && (xFinal && !xStep)) ||
122451      (!xFunc && (!xFinal && xStep)) ||
122452      (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
122453      (255<(nName = sqlite3Strlen30( zFunctionName))) ){
122454    return SQLITE_MISUSE_BKPT;
122455  }
122456
122457  assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
122458  extraFlags = enc &  SQLITE_DETERMINISTIC;
122459  enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
122460
122461#ifndef SQLITE_OMIT_UTF16
122462  /* If SQLITE_UTF16 is specified as the encoding type, transform this
122463  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
122464  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
122465  **
122466  ** If SQLITE_ANY is specified, add three versions of the function
122467  ** to the hash table.
122468  */
122469  if( enc==SQLITE_UTF16 ){
122470    enc = SQLITE_UTF16NATIVE;
122471  }else if( enc==SQLITE_ANY ){
122472    int rc;
122473    rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
122474         pUserData, xFunc, xStep, xFinal, pDestructor);
122475    if( rc==SQLITE_OK ){
122476      rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
122477          pUserData, xFunc, xStep, xFinal, pDestructor);
122478    }
122479    if( rc!=SQLITE_OK ){
122480      return rc;
122481    }
122482    enc = SQLITE_UTF16BE;
122483  }
122484#else
122485  enc = SQLITE_UTF8;
122486#endif
122487
122488  /* Check if an existing function is being overridden or deleted. If so,
122489  ** and there are active VMs, then return SQLITE_BUSY. If a function
122490  ** is being overridden/deleted but there are no active VMs, allow the
122491  ** operation to continue but invalidate all precompiled statements.
122492  */
122493  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
122494  if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
122495    if( db->nVdbeActive ){
122496      sqlite3Error(db, SQLITE_BUSY,
122497        "unable to delete/modify user-function due to active statements");
122498      assert( !db->mallocFailed );
122499      return SQLITE_BUSY;
122500    }else{
122501      sqlite3ExpirePreparedStatements(db);
122502    }
122503  }
122504
122505  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
122506  assert(p || db->mallocFailed);
122507  if( !p ){
122508    return SQLITE_NOMEM;
122509  }
122510
122511  /* If an older version of the function with a configured destructor is
122512  ** being replaced invoke the destructor function here. */
122513  functionDestroy(db, p);
122514
122515  if( pDestructor ){
122516    pDestructor->nRef++;
122517  }
122518  p->pDestructor = pDestructor;
122519  p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
122520  testcase( p->funcFlags & SQLITE_DETERMINISTIC );
122521  p->xFunc = xFunc;
122522  p->xStep = xStep;
122523  p->xFinalize = xFinal;
122524  p->pUserData = pUserData;
122525  p->nArg = (u16)nArg;
122526  return SQLITE_OK;
122527}
122528
122529/*
122530** Create new user functions.
122531*/
122532SQLITE_API int sqlite3_create_function(
122533  sqlite3 *db,
122534  const char *zFunc,
122535  int nArg,
122536  int enc,
122537  void *p,
122538  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
122539  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
122540  void (*xFinal)(sqlite3_context*)
122541){
122542  return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
122543                                    xFinal, 0);
122544}
122545
122546SQLITE_API int sqlite3_create_function_v2(
122547  sqlite3 *db,
122548  const char *zFunc,
122549  int nArg,
122550  int enc,
122551  void *p,
122552  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
122553  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
122554  void (*xFinal)(sqlite3_context*),
122555  void (*xDestroy)(void *)
122556){
122557  int rc = SQLITE_ERROR;
122558  FuncDestructor *pArg = 0;
122559  sqlite3_mutex_enter(db->mutex);
122560  if( xDestroy ){
122561    pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
122562    if( !pArg ){
122563      xDestroy(p);
122564      goto out;
122565    }
122566    pArg->xDestroy = xDestroy;
122567    pArg->pUserData = p;
122568  }
122569  rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
122570  if( pArg && pArg->nRef==0 ){
122571    assert( rc!=SQLITE_OK );
122572    xDestroy(p);
122573    sqlite3DbFree(db, pArg);
122574  }
122575
122576 out:
122577  rc = sqlite3ApiExit(db, rc);
122578  sqlite3_mutex_leave(db->mutex);
122579  return rc;
122580}
122581
122582#ifndef SQLITE_OMIT_UTF16
122583SQLITE_API int sqlite3_create_function16(
122584  sqlite3 *db,
122585  const void *zFunctionName,
122586  int nArg,
122587  int eTextRep,
122588  void *p,
122589  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
122590  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
122591  void (*xFinal)(sqlite3_context*)
122592){
122593  int rc;
122594  char *zFunc8;
122595  sqlite3_mutex_enter(db->mutex);
122596  assert( !db->mallocFailed );
122597  zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
122598  rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
122599  sqlite3DbFree(db, zFunc8);
122600  rc = sqlite3ApiExit(db, rc);
122601  sqlite3_mutex_leave(db->mutex);
122602  return rc;
122603}
122604#endif
122605
122606
122607/*
122608** Declare that a function has been overloaded by a virtual table.
122609**
122610** If the function already exists as a regular global function, then
122611** this routine is a no-op.  If the function does not exist, then create
122612** a new one that always throws a run-time error.
122613**
122614** When virtual tables intend to provide an overloaded function, they
122615** should call this routine to make sure the global function exists.
122616** A global function must exist in order for name resolution to work
122617** properly.
122618*/
122619SQLITE_API int sqlite3_overload_function(
122620  sqlite3 *db,
122621  const char *zName,
122622  int nArg
122623){
122624  int nName = sqlite3Strlen30(zName);
122625  int rc = SQLITE_OK;
122626  sqlite3_mutex_enter(db->mutex);
122627  if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
122628    rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
122629                           0, sqlite3InvalidFunction, 0, 0, 0);
122630  }
122631  rc = sqlite3ApiExit(db, rc);
122632  sqlite3_mutex_leave(db->mutex);
122633  return rc;
122634}
122635
122636#ifndef SQLITE_OMIT_TRACE
122637/*
122638** Register a trace function.  The pArg from the previously registered trace
122639** is returned.
122640**
122641** A NULL trace function means that no tracing is executes.  A non-NULL
122642** trace is a pointer to a function that is invoked at the start of each
122643** SQL statement.
122644*/
122645SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
122646  void *pOld;
122647  sqlite3_mutex_enter(db->mutex);
122648  pOld = db->pTraceArg;
122649  db->xTrace = xTrace;
122650  db->pTraceArg = pArg;
122651  sqlite3_mutex_leave(db->mutex);
122652  return pOld;
122653}
122654/*
122655** Register a profile function.  The pArg from the previously registered
122656** profile function is returned.
122657**
122658** A NULL profile function means that no profiling is executes.  A non-NULL
122659** profile is a pointer to a function that is invoked at the conclusion of
122660** each SQL statement that is run.
122661*/
122662SQLITE_API void *sqlite3_profile(
122663  sqlite3 *db,
122664  void (*xProfile)(void*,const char*,sqlite_uint64),
122665  void *pArg
122666){
122667  void *pOld;
122668  sqlite3_mutex_enter(db->mutex);
122669  pOld = db->pProfileArg;
122670  db->xProfile = xProfile;
122671  db->pProfileArg = pArg;
122672  sqlite3_mutex_leave(db->mutex);
122673  return pOld;
122674}
122675#endif /* SQLITE_OMIT_TRACE */
122676
122677/*
122678** Register a function to be invoked when a transaction commits.
122679** If the invoked function returns non-zero, then the commit becomes a
122680** rollback.
122681*/
122682SQLITE_API void *sqlite3_commit_hook(
122683  sqlite3 *db,              /* Attach the hook to this database */
122684  int (*xCallback)(void*),  /* Function to invoke on each commit */
122685  void *pArg                /* Argument to the function */
122686){
122687  void *pOld;
122688  sqlite3_mutex_enter(db->mutex);
122689  pOld = db->pCommitArg;
122690  db->xCommitCallback = xCallback;
122691  db->pCommitArg = pArg;
122692  sqlite3_mutex_leave(db->mutex);
122693  return pOld;
122694}
122695
122696/*
122697** Register a callback to be invoked each time a row is updated,
122698** inserted or deleted using this database connection.
122699*/
122700SQLITE_API void *sqlite3_update_hook(
122701  sqlite3 *db,              /* Attach the hook to this database */
122702  void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
122703  void *pArg                /* Argument to the function */
122704){
122705  void *pRet;
122706  sqlite3_mutex_enter(db->mutex);
122707  pRet = db->pUpdateArg;
122708  db->xUpdateCallback = xCallback;
122709  db->pUpdateArg = pArg;
122710  sqlite3_mutex_leave(db->mutex);
122711  return pRet;
122712}
122713
122714/*
122715** Register a callback to be invoked each time a transaction is rolled
122716** back by this database connection.
122717*/
122718SQLITE_API void *sqlite3_rollback_hook(
122719  sqlite3 *db,              /* Attach the hook to this database */
122720  void (*xCallback)(void*), /* Callback function */
122721  void *pArg                /* Argument to the function */
122722){
122723  void *pRet;
122724  sqlite3_mutex_enter(db->mutex);
122725  pRet = db->pRollbackArg;
122726  db->xRollbackCallback = xCallback;
122727  db->pRollbackArg = pArg;
122728  sqlite3_mutex_leave(db->mutex);
122729  return pRet;
122730}
122731
122732#ifndef SQLITE_OMIT_WAL
122733/*
122734** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
122735** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
122736** is greater than sqlite3.pWalArg cast to an integer (the value configured by
122737** wal_autocheckpoint()).
122738*/
122739SQLITE_PRIVATE int sqlite3WalDefaultHook(
122740  void *pClientData,     /* Argument */
122741  sqlite3 *db,           /* Connection */
122742  const char *zDb,       /* Database */
122743  int nFrame             /* Size of WAL */
122744){
122745  if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
122746    sqlite3BeginBenignMalloc();
122747    sqlite3_wal_checkpoint(db, zDb);
122748    sqlite3EndBenignMalloc();
122749  }
122750  return SQLITE_OK;
122751}
122752#endif /* SQLITE_OMIT_WAL */
122753
122754/*
122755** Configure an sqlite3_wal_hook() callback to automatically checkpoint
122756** a database after committing a transaction if there are nFrame or
122757** more frames in the log file. Passing zero or a negative value as the
122758** nFrame parameter disables automatic checkpoints entirely.
122759**
122760** The callback registered by this function replaces any existing callback
122761** registered using sqlite3_wal_hook(). Likewise, registering a callback
122762** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
122763** configured by this function.
122764*/
122765SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
122766#ifdef SQLITE_OMIT_WAL
122767  UNUSED_PARAMETER(db);
122768  UNUSED_PARAMETER(nFrame);
122769#else
122770  if( nFrame>0 ){
122771    sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
122772  }else{
122773    sqlite3_wal_hook(db, 0, 0);
122774  }
122775#endif
122776  return SQLITE_OK;
122777}
122778
122779/*
122780** Register a callback to be invoked each time a transaction is written
122781** into the write-ahead-log by this database connection.
122782*/
122783SQLITE_API void *sqlite3_wal_hook(
122784  sqlite3 *db,                    /* Attach the hook to this db handle */
122785  int(*xCallback)(void *, sqlite3*, const char*, int),
122786  void *pArg                      /* First argument passed to xCallback() */
122787){
122788#ifndef SQLITE_OMIT_WAL
122789  void *pRet;
122790  sqlite3_mutex_enter(db->mutex);
122791  pRet = db->pWalArg;
122792  db->xWalCallback = xCallback;
122793  db->pWalArg = pArg;
122794  sqlite3_mutex_leave(db->mutex);
122795  return pRet;
122796#else
122797  return 0;
122798#endif
122799}
122800
122801/*
122802** Checkpoint database zDb.
122803*/
122804SQLITE_API int sqlite3_wal_checkpoint_v2(
122805  sqlite3 *db,                    /* Database handle */
122806  const char *zDb,                /* Name of attached database (or NULL) */
122807  int eMode,                      /* SQLITE_CHECKPOINT_* value */
122808  int *pnLog,                     /* OUT: Size of WAL log in frames */
122809  int *pnCkpt                     /* OUT: Total number of frames checkpointed */
122810){
122811#ifdef SQLITE_OMIT_WAL
122812  return SQLITE_OK;
122813#else
122814  int rc;                         /* Return code */
122815  int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
122816
122817  /* Initialize the output variables to -1 in case an error occurs. */
122818  if( pnLog ) *pnLog = -1;
122819  if( pnCkpt ) *pnCkpt = -1;
122820
122821  assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
122822  assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
122823  assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
122824  if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
122825    return SQLITE_MISUSE;
122826  }
122827
122828  sqlite3_mutex_enter(db->mutex);
122829  if( zDb && zDb[0] ){
122830    iDb = sqlite3FindDbName(db, zDb);
122831  }
122832  if( iDb<0 ){
122833    rc = SQLITE_ERROR;
122834    sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
122835  }else{
122836    rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
122837    sqlite3Error(db, rc, 0);
122838  }
122839  rc = sqlite3ApiExit(db, rc);
122840  sqlite3_mutex_leave(db->mutex);
122841  return rc;
122842#endif
122843}
122844
122845
122846/*
122847** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
122848** to contains a zero-length string, all attached databases are
122849** checkpointed.
122850*/
122851SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
122852  return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
122853}
122854
122855#ifndef SQLITE_OMIT_WAL
122856/*
122857** Run a checkpoint on database iDb. This is a no-op if database iDb is
122858** not currently open in WAL mode.
122859**
122860** If a transaction is open on the database being checkpointed, this
122861** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
122862** an error occurs while running the checkpoint, an SQLite error code is
122863** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
122864**
122865** The mutex on database handle db should be held by the caller. The mutex
122866** associated with the specific b-tree being checkpointed is taken by
122867** this function while the checkpoint is running.
122868**
122869** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
122870** checkpointed. If an error is encountered it is returned immediately -
122871** no attempt is made to checkpoint any remaining databases.
122872**
122873** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
122874*/
122875SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
122876  int rc = SQLITE_OK;             /* Return code */
122877  int i;                          /* Used to iterate through attached dbs */
122878  int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
122879
122880  assert( sqlite3_mutex_held(db->mutex) );
122881  assert( !pnLog || *pnLog==-1 );
122882  assert( !pnCkpt || *pnCkpt==-1 );
122883
122884  for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
122885    if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
122886      rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
122887      pnLog = 0;
122888      pnCkpt = 0;
122889      if( rc==SQLITE_BUSY ){
122890        bBusy = 1;
122891        rc = SQLITE_OK;
122892      }
122893    }
122894  }
122895
122896  return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
122897}
122898#endif /* SQLITE_OMIT_WAL */
122899
122900/*
122901** This function returns true if main-memory should be used instead of
122902** a temporary file for transient pager files and statement journals.
122903** The value returned depends on the value of db->temp_store (runtime
122904** parameter) and the compile time value of SQLITE_TEMP_STORE. The
122905** following table describes the relationship between these two values
122906** and this functions return value.
122907**
122908**   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
122909**   -----------------     --------------     ------------------------------
122910**   0                     any                file      (return 0)
122911**   1                     1                  file      (return 0)
122912**   1                     2                  memory    (return 1)
122913**   1                     0                  file      (return 0)
122914**   2                     1                  file      (return 0)
122915**   2                     2                  memory    (return 1)
122916**   2                     0                  memory    (return 1)
122917**   3                     any                memory    (return 1)
122918*/
122919SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
122920#if SQLITE_TEMP_STORE==1
122921  return ( db->temp_store==2 );
122922#endif
122923#if SQLITE_TEMP_STORE==2
122924  return ( db->temp_store!=1 );
122925#endif
122926#if SQLITE_TEMP_STORE==3
122927  return 1;
122928#endif
122929#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
122930  return 0;
122931#endif
122932}
122933
122934/*
122935** Return UTF-8 encoded English language explanation of the most recent
122936** error.
122937*/
122938SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
122939  const char *z;
122940  if( !db ){
122941    return sqlite3ErrStr(SQLITE_NOMEM);
122942  }
122943  if( !sqlite3SafetyCheckSickOrOk(db) ){
122944    return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
122945  }
122946  sqlite3_mutex_enter(db->mutex);
122947  if( db->mallocFailed ){
122948    z = sqlite3ErrStr(SQLITE_NOMEM);
122949  }else{
122950    testcase( db->pErr==0 );
122951    z = (char*)sqlite3_value_text(db->pErr);
122952    assert( !db->mallocFailed );
122953    if( z==0 ){
122954      z = sqlite3ErrStr(db->errCode);
122955    }
122956  }
122957  sqlite3_mutex_leave(db->mutex);
122958  return z;
122959}
122960
122961#ifndef SQLITE_OMIT_UTF16
122962/*
122963** Return UTF-16 encoded English language explanation of the most recent
122964** error.
122965*/
122966SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
122967  static const u16 outOfMem[] = {
122968    'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
122969  };
122970  static const u16 misuse[] = {
122971    'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
122972    'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
122973    'c', 'a', 'l', 'l', 'e', 'd', ' ',
122974    'o', 'u', 't', ' ',
122975    'o', 'f', ' ',
122976    's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
122977  };
122978
122979  const void *z;
122980  if( !db ){
122981    return (void *)outOfMem;
122982  }
122983  if( !sqlite3SafetyCheckSickOrOk(db) ){
122984    return (void *)misuse;
122985  }
122986  sqlite3_mutex_enter(db->mutex);
122987  if( db->mallocFailed ){
122988    z = (void *)outOfMem;
122989  }else{
122990    z = sqlite3_value_text16(db->pErr);
122991    if( z==0 ){
122992      sqlite3Error(db, db->errCode, sqlite3ErrStr(db->errCode));
122993      z = sqlite3_value_text16(db->pErr);
122994    }
122995    /* A malloc() may have failed within the call to sqlite3_value_text16()
122996    ** above. If this is the case, then the db->mallocFailed flag needs to
122997    ** be cleared before returning. Do this directly, instead of via
122998    ** sqlite3ApiExit(), to avoid setting the database handle error message.
122999    */
123000    db->mallocFailed = 0;
123001  }
123002  sqlite3_mutex_leave(db->mutex);
123003  return z;
123004}
123005#endif /* SQLITE_OMIT_UTF16 */
123006
123007/*
123008** Return the most recent error code generated by an SQLite routine. If NULL is
123009** passed to this function, we assume a malloc() failed during sqlite3_open().
123010*/
123011SQLITE_API int sqlite3_errcode(sqlite3 *db){
123012  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
123013    return SQLITE_MISUSE_BKPT;
123014  }
123015  if( !db || db->mallocFailed ){
123016    return SQLITE_NOMEM;
123017  }
123018  return db->errCode & db->errMask;
123019}
123020SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
123021  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
123022    return SQLITE_MISUSE_BKPT;
123023  }
123024  if( !db || db->mallocFailed ){
123025    return SQLITE_NOMEM;
123026  }
123027  return db->errCode;
123028}
123029
123030/*
123031** Return a string that describes the kind of error specified in the
123032** argument.  For now, this simply calls the internal sqlite3ErrStr()
123033** function.
123034*/
123035SQLITE_API const char *sqlite3_errstr(int rc){
123036  return sqlite3ErrStr(rc);
123037}
123038
123039/*
123040** Invalidate all cached KeyInfo objects for database connection "db"
123041*/
123042static void invalidateCachedKeyInfo(sqlite3 *db){
123043  Db *pDb;                    /* A single database */
123044  int iDb;                    /* The database index number */
123045  HashElem *k;                /* For looping over tables in pDb */
123046  Table *pTab;                /* A table in the database */
123047  Index *pIdx;                /* Each index */
123048
123049  for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
123050    if( pDb->pBt==0 ) continue;
123051    sqlite3BtreeEnter(pDb->pBt);
123052    for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
123053      pTab = (Table*)sqliteHashData(k);
123054      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
123055        if( pIdx->pKeyInfo && pIdx->pKeyInfo->db==db ){
123056          sqlite3KeyInfoUnref(pIdx->pKeyInfo);
123057          pIdx->pKeyInfo = 0;
123058        }
123059      }
123060    }
123061    sqlite3BtreeLeave(pDb->pBt);
123062  }
123063}
123064
123065/*
123066** Create a new collating function for database "db".  The name is zName
123067** and the encoding is enc.
123068*/
123069static int createCollation(
123070  sqlite3* db,
123071  const char *zName,
123072  u8 enc,
123073  void* pCtx,
123074  int(*xCompare)(void*,int,const void*,int,const void*),
123075  void(*xDel)(void*)
123076){
123077  CollSeq *pColl;
123078  int enc2;
123079  int nName = sqlite3Strlen30(zName);
123080
123081  assert( sqlite3_mutex_held(db->mutex) );
123082
123083  /* If SQLITE_UTF16 is specified as the encoding type, transform this
123084  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
123085  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
123086  */
123087  enc2 = enc;
123088  testcase( enc2==SQLITE_UTF16 );
123089  testcase( enc2==SQLITE_UTF16_ALIGNED );
123090  if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
123091    enc2 = SQLITE_UTF16NATIVE;
123092  }
123093  if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
123094    return SQLITE_MISUSE_BKPT;
123095  }
123096
123097  /* Check if this call is removing or replacing an existing collation
123098  ** sequence. If so, and there are active VMs, return busy. If there
123099  ** are no active VMs, invalidate any pre-compiled statements.
123100  */
123101  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
123102  if( pColl && pColl->xCmp ){
123103    if( db->nVdbeActive ){
123104      sqlite3Error(db, SQLITE_BUSY,
123105        "unable to delete/modify collation sequence due to active statements");
123106      return SQLITE_BUSY;
123107    }
123108    sqlite3ExpirePreparedStatements(db);
123109    invalidateCachedKeyInfo(db);
123110
123111    /* If collation sequence pColl was created directly by a call to
123112    ** sqlite3_create_collation, and not generated by synthCollSeq(),
123113    ** then any copies made by synthCollSeq() need to be invalidated.
123114    ** Also, collation destructor - CollSeq.xDel() - function may need
123115    ** to be called.
123116    */
123117    if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
123118      CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
123119      int j;
123120      for(j=0; j<3; j++){
123121        CollSeq *p = &aColl[j];
123122        if( p->enc==pColl->enc ){
123123          if( p->xDel ){
123124            p->xDel(p->pUser);
123125          }
123126          p->xCmp = 0;
123127        }
123128      }
123129    }
123130  }
123131
123132  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
123133  if( pColl==0 ) return SQLITE_NOMEM;
123134  pColl->xCmp = xCompare;
123135  pColl->pUser = pCtx;
123136  pColl->xDel = xDel;
123137  pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
123138  sqlite3Error(db, SQLITE_OK, 0);
123139  return SQLITE_OK;
123140}
123141
123142
123143/*
123144** This array defines hard upper bounds on limit values.  The
123145** initializer must be kept in sync with the SQLITE_LIMIT_*
123146** #defines in sqlite3.h.
123147*/
123148static const int aHardLimit[] = {
123149  SQLITE_MAX_LENGTH,
123150  SQLITE_MAX_SQL_LENGTH,
123151  SQLITE_MAX_COLUMN,
123152  SQLITE_MAX_EXPR_DEPTH,
123153  SQLITE_MAX_COMPOUND_SELECT,
123154  SQLITE_MAX_VDBE_OP,
123155  SQLITE_MAX_FUNCTION_ARG,
123156  SQLITE_MAX_ATTACHED,
123157  SQLITE_MAX_LIKE_PATTERN_LENGTH,
123158  SQLITE_MAX_VARIABLE_NUMBER,
123159  SQLITE_MAX_TRIGGER_DEPTH,
123160};
123161
123162/*
123163** Make sure the hard limits are set to reasonable values
123164*/
123165#if SQLITE_MAX_LENGTH<100
123166# error SQLITE_MAX_LENGTH must be at least 100
123167#endif
123168#if SQLITE_MAX_SQL_LENGTH<100
123169# error SQLITE_MAX_SQL_LENGTH must be at least 100
123170#endif
123171#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
123172# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
123173#endif
123174#if SQLITE_MAX_COMPOUND_SELECT<2
123175# error SQLITE_MAX_COMPOUND_SELECT must be at least 2
123176#endif
123177#if SQLITE_MAX_VDBE_OP<40
123178# error SQLITE_MAX_VDBE_OP must be at least 40
123179#endif
123180#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
123181# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
123182#endif
123183#if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
123184# error SQLITE_MAX_ATTACHED must be between 0 and 62
123185#endif
123186#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
123187# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
123188#endif
123189#if SQLITE_MAX_COLUMN>32767
123190# error SQLITE_MAX_COLUMN must not exceed 32767
123191#endif
123192#if SQLITE_MAX_TRIGGER_DEPTH<1
123193# error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
123194#endif
123195
123196
123197/*
123198** Change the value of a limit.  Report the old value.
123199** If an invalid limit index is supplied, report -1.
123200** Make no changes but still report the old value if the
123201** new limit is negative.
123202**
123203** A new lower limit does not shrink existing constructs.
123204** It merely prevents new constructs that exceed the limit
123205** from forming.
123206*/
123207SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
123208  int oldLimit;
123209
123210
123211  /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
123212  ** there is a hard upper bound set at compile-time by a C preprocessor
123213  ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
123214  ** "_MAX_".)
123215  */
123216  assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
123217  assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
123218  assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
123219  assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
123220  assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
123221  assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
123222  assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
123223  assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
123224  assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
123225                                               SQLITE_MAX_LIKE_PATTERN_LENGTH );
123226  assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
123227  assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
123228  assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
123229
123230
123231  if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
123232    return -1;
123233  }
123234  oldLimit = db->aLimit[limitId];
123235  if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
123236    if( newLimit>aHardLimit[limitId] ){
123237      newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
123238    }
123239    db->aLimit[limitId] = newLimit;
123240  }
123241  return oldLimit;                     /* IMP: R-53341-35419 */
123242}
123243
123244/*
123245** This function is used to parse both URIs and non-URI filenames passed by the
123246** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
123247** URIs specified as part of ATTACH statements.
123248**
123249** The first argument to this function is the name of the VFS to use (or
123250** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
123251** query parameter. The second argument contains the URI (or non-URI filename)
123252** itself. When this function is called the *pFlags variable should contain
123253** the default flags to open the database handle with. The value stored in
123254** *pFlags may be updated before returning if the URI filename contains
123255** "cache=xxx" or "mode=xxx" query parameters.
123256**
123257** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
123258** the VFS that should be used to open the database file. *pzFile is set to
123259** point to a buffer containing the name of the file to open. It is the
123260** responsibility of the caller to eventually call sqlite3_free() to release
123261** this buffer.
123262**
123263** If an error occurs, then an SQLite error code is returned and *pzErrMsg
123264** may be set to point to a buffer containing an English language error
123265** message. It is the responsibility of the caller to eventually release
123266** this buffer by calling sqlite3_free().
123267*/
123268SQLITE_PRIVATE int sqlite3ParseUri(
123269  const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
123270  const char *zUri,               /* Nul-terminated URI to parse */
123271  unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
123272  sqlite3_vfs **ppVfs,            /* OUT: VFS to use */
123273  char **pzFile,                  /* OUT: Filename component of URI */
123274  char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
123275){
123276  int rc = SQLITE_OK;
123277  unsigned int flags = *pFlags;
123278  const char *zVfs = zDefaultVfs;
123279  char *zFile;
123280  char c;
123281  int nUri = sqlite3Strlen30(zUri);
123282
123283  assert( *pzErrMsg==0 );
123284
123285  if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri)
123286   && nUri>=5 && memcmp(zUri, "file:", 5)==0
123287  ){
123288    char *zOpt;
123289    int eState;                   /* Parser state when parsing URI */
123290    int iIn;                      /* Input character index */
123291    int iOut = 0;                 /* Output character index */
123292    int nByte = nUri+2;           /* Bytes of space to allocate */
123293
123294    /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
123295    ** method that there may be extra parameters following the file-name.  */
123296    flags |= SQLITE_OPEN_URI;
123297
123298    for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
123299    zFile = sqlite3_malloc(nByte);
123300    if( !zFile ) return SQLITE_NOMEM;
123301
123302    iIn = 5;
123303#ifndef SQLITE_ALLOW_URI_AUTHORITY
123304    /* Discard the scheme and authority segments of the URI. */
123305    if( zUri[5]=='/' && zUri[6]=='/' ){
123306      iIn = 7;
123307      while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
123308      if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
123309        *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
123310            iIn-7, &zUri[7]);
123311        rc = SQLITE_ERROR;
123312        goto parse_uri_out;
123313      }
123314    }
123315#endif
123316
123317    /* Copy the filename and any query parameters into the zFile buffer.
123318    ** Decode %HH escape codes along the way.
123319    **
123320    ** Within this loop, variable eState may be set to 0, 1 or 2, depending
123321    ** on the parsing context. As follows:
123322    **
123323    **   0: Parsing file-name.
123324    **   1: Parsing name section of a name=value query parameter.
123325    **   2: Parsing value section of a name=value query parameter.
123326    */
123327    eState = 0;
123328    while( (c = zUri[iIn])!=0 && c!='#' ){
123329      iIn++;
123330      if( c=='%'
123331       && sqlite3Isxdigit(zUri[iIn])
123332       && sqlite3Isxdigit(zUri[iIn+1])
123333      ){
123334        int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
123335        octet += sqlite3HexToInt(zUri[iIn++]);
123336
123337        assert( octet>=0 && octet<256 );
123338        if( octet==0 ){
123339          /* This branch is taken when "%00" appears within the URI. In this
123340          ** case we ignore all text in the remainder of the path, name or
123341          ** value currently being parsed. So ignore the current character
123342          ** and skip to the next "?", "=" or "&", as appropriate. */
123343          while( (c = zUri[iIn])!=0 && c!='#'
123344              && (eState!=0 || c!='?')
123345              && (eState!=1 || (c!='=' && c!='&'))
123346              && (eState!=2 || c!='&')
123347          ){
123348            iIn++;
123349          }
123350          continue;
123351        }
123352        c = octet;
123353      }else if( eState==1 && (c=='&' || c=='=') ){
123354        if( zFile[iOut-1]==0 ){
123355          /* An empty option name. Ignore this option altogether. */
123356          while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
123357          continue;
123358        }
123359        if( c=='&' ){
123360          zFile[iOut++] = '\0';
123361        }else{
123362          eState = 2;
123363        }
123364        c = 0;
123365      }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
123366        c = 0;
123367        eState = 1;
123368      }
123369      zFile[iOut++] = c;
123370    }
123371    if( eState==1 ) zFile[iOut++] = '\0';
123372    zFile[iOut++] = '\0';
123373    zFile[iOut++] = '\0';
123374
123375    /* Check if there were any options specified that should be interpreted
123376    ** here. Options that are interpreted here include "vfs" and those that
123377    ** correspond to flags that may be passed to the sqlite3_open_v2()
123378    ** method. */
123379    zOpt = &zFile[sqlite3Strlen30(zFile)+1];
123380    while( zOpt[0] ){
123381      int nOpt = sqlite3Strlen30(zOpt);
123382      char *zVal = &zOpt[nOpt+1];
123383      int nVal = sqlite3Strlen30(zVal);
123384
123385      if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
123386        zVfs = zVal;
123387      }else{
123388        struct OpenMode {
123389          const char *z;
123390          int mode;
123391        } *aMode = 0;
123392        char *zModeType = 0;
123393        int mask = 0;
123394        int limit = 0;
123395
123396        if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
123397          static struct OpenMode aCacheMode[] = {
123398            { "shared",  SQLITE_OPEN_SHAREDCACHE },
123399            { "private", SQLITE_OPEN_PRIVATECACHE },
123400            { 0, 0 }
123401          };
123402
123403          mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
123404          aMode = aCacheMode;
123405          limit = mask;
123406          zModeType = "cache";
123407        }
123408        if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
123409          static struct OpenMode aOpenMode[] = {
123410            { "ro",  SQLITE_OPEN_READONLY },
123411            { "rw",  SQLITE_OPEN_READWRITE },
123412            { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
123413            { "memory", SQLITE_OPEN_MEMORY },
123414            { 0, 0 }
123415          };
123416
123417          mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
123418                   | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
123419          aMode = aOpenMode;
123420          limit = mask & flags;
123421          zModeType = "access";
123422        }
123423
123424        if( aMode ){
123425          int i;
123426          int mode = 0;
123427          for(i=0; aMode[i].z; i++){
123428            const char *z = aMode[i].z;
123429            if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
123430              mode = aMode[i].mode;
123431              break;
123432            }
123433          }
123434          if( mode==0 ){
123435            *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
123436            rc = SQLITE_ERROR;
123437            goto parse_uri_out;
123438          }
123439          if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
123440            *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
123441                                        zModeType, zVal);
123442            rc = SQLITE_PERM;
123443            goto parse_uri_out;
123444          }
123445          flags = (flags & ~mask) | mode;
123446        }
123447      }
123448
123449      zOpt = &zVal[nVal+1];
123450    }
123451
123452  }else{
123453    zFile = sqlite3_malloc(nUri+2);
123454    if( !zFile ) return SQLITE_NOMEM;
123455    memcpy(zFile, zUri, nUri);
123456    zFile[nUri] = '\0';
123457    zFile[nUri+1] = '\0';
123458    flags &= ~SQLITE_OPEN_URI;
123459  }
123460
123461  *ppVfs = sqlite3_vfs_find(zVfs);
123462  if( *ppVfs==0 ){
123463    *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
123464    rc = SQLITE_ERROR;
123465  }
123466 parse_uri_out:
123467  if( rc!=SQLITE_OK ){
123468    sqlite3_free(zFile);
123469    zFile = 0;
123470  }
123471  *pFlags = flags;
123472  *pzFile = zFile;
123473  return rc;
123474}
123475
123476
123477/*
123478** This routine does the work of opening a database on behalf of
123479** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
123480** is UTF-8 encoded.
123481*/
123482static int openDatabase(
123483  const char *zFilename, /* Database filename UTF-8 encoded */
123484  sqlite3 **ppDb,        /* OUT: Returned database handle */
123485  unsigned int flags,    /* Operational flags */
123486  const char *zVfs       /* Name of the VFS to use */
123487){
123488  sqlite3 *db;                    /* Store allocated handle here */
123489  int rc;                         /* Return code */
123490  int isThreadsafe;               /* True for threadsafe connections */
123491  char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
123492  char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
123493
123494  *ppDb = 0;
123495#ifndef SQLITE_OMIT_AUTOINIT
123496  rc = sqlite3_initialize();
123497  if( rc ) return rc;
123498#endif
123499
123500  /* Only allow sensible combinations of bits in the flags argument.
123501  ** Throw an error if any non-sense combination is used.  If we
123502  ** do not block illegal combinations here, it could trigger
123503  ** assert() statements in deeper layers.  Sensible combinations
123504  ** are:
123505  **
123506  **  1:  SQLITE_OPEN_READONLY
123507  **  2:  SQLITE_OPEN_READWRITE
123508  **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
123509  */
123510  assert( SQLITE_OPEN_READONLY  == 0x01 );
123511  assert( SQLITE_OPEN_READWRITE == 0x02 );
123512  assert( SQLITE_OPEN_CREATE    == 0x04 );
123513  testcase( (1<<(flags&7))==0x02 ); /* READONLY */
123514  testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
123515  testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
123516  if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT;
123517
123518  if( sqlite3GlobalConfig.bCoreMutex==0 ){
123519    isThreadsafe = 0;
123520  }else if( flags & SQLITE_OPEN_NOMUTEX ){
123521    isThreadsafe = 0;
123522  }else if( flags & SQLITE_OPEN_FULLMUTEX ){
123523    isThreadsafe = 1;
123524  }else{
123525    isThreadsafe = sqlite3GlobalConfig.bFullMutex;
123526  }
123527  if( flags & SQLITE_OPEN_PRIVATECACHE ){
123528    flags &= ~SQLITE_OPEN_SHAREDCACHE;
123529  }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
123530    flags |= SQLITE_OPEN_SHAREDCACHE;
123531  }
123532
123533  /* Remove harmful bits from the flags parameter
123534  **
123535  ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
123536  ** dealt with in the previous code block.  Besides these, the only
123537  ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
123538  ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
123539  ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
123540  ** off all other flags.
123541  */
123542  flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
123543               SQLITE_OPEN_EXCLUSIVE |
123544               SQLITE_OPEN_MAIN_DB |
123545               SQLITE_OPEN_TEMP_DB |
123546               SQLITE_OPEN_TRANSIENT_DB |
123547               SQLITE_OPEN_MAIN_JOURNAL |
123548               SQLITE_OPEN_TEMP_JOURNAL |
123549               SQLITE_OPEN_SUBJOURNAL |
123550               SQLITE_OPEN_MASTER_JOURNAL |
123551               SQLITE_OPEN_NOMUTEX |
123552               SQLITE_OPEN_FULLMUTEX |
123553               SQLITE_OPEN_WAL
123554             );
123555
123556  /* Allocate the sqlite data structure */
123557  db = sqlite3MallocZero( sizeof(sqlite3) );
123558  if( db==0 ) goto opendb_out;
123559  if( isThreadsafe ){
123560    db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
123561    if( db->mutex==0 ){
123562      sqlite3_free(db);
123563      db = 0;
123564      goto opendb_out;
123565    }
123566  }
123567  sqlite3_mutex_enter(db->mutex);
123568  db->errMask = 0xff;
123569  db->nDb = 2;
123570  db->magic = SQLITE_MAGIC_BUSY;
123571  db->aDb = db->aDbStatic;
123572
123573  assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
123574  memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
123575  db->autoCommit = 1;
123576  db->nextAutovac = -1;
123577  db->szMmap = sqlite3GlobalConfig.szMmap;
123578  db->nextPagesize = 0;
123579  db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
123580#if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
123581                 | SQLITE_AutoIndex
123582#endif
123583#if SQLITE_DEFAULT_FILE_FORMAT<4
123584                 | SQLITE_LegacyFileFmt
123585#endif
123586#ifdef SQLITE_ENABLE_LOAD_EXTENSION
123587                 | SQLITE_LoadExtension
123588#endif
123589#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
123590                 | SQLITE_RecTriggers
123591#endif
123592#if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
123593                 | SQLITE_ForeignKeys
123594#endif
123595      ;
123596  sqlite3HashInit(&db->aCollSeq);
123597#ifndef SQLITE_OMIT_VIRTUALTABLE
123598  sqlite3HashInit(&db->aModule);
123599#endif
123600
123601  /* Add the default collation sequence BINARY. BINARY works for both UTF-8
123602  ** and UTF-16, so add a version for each to avoid any unnecessary
123603  ** conversions. The only error that can occur here is a malloc() failure.
123604  */
123605  createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
123606  createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
123607  createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
123608  createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
123609  if( db->mallocFailed ){
123610    goto opendb_out;
123611  }
123612  db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
123613  assert( db->pDfltColl!=0 );
123614
123615  /* Also add a UTF-8 case-insensitive collation sequence. */
123616  createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
123617
123618  /* Parse the filename/URI argument. */
123619  db->openFlags = flags;
123620  rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
123621  if( rc!=SQLITE_OK ){
123622    if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
123623    sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
123624    sqlite3_free(zErrMsg);
123625    goto opendb_out;
123626  }
123627
123628  /* Open the backend database driver */
123629  rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
123630                        flags | SQLITE_OPEN_MAIN_DB);
123631  if( rc!=SQLITE_OK ){
123632    if( rc==SQLITE_IOERR_NOMEM ){
123633      rc = SQLITE_NOMEM;
123634    }
123635    sqlite3Error(db, rc, 0);
123636    goto opendb_out;
123637  }
123638  db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
123639  db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
123640
123641
123642  /* The default safety_level for the main database is 'full'; for the temp
123643  ** database it is 'NONE'. This matches the pager layer defaults.
123644  */
123645  db->aDb[0].zName = "main";
123646  db->aDb[0].safety_level = 3;
123647  db->aDb[1].zName = "temp";
123648  db->aDb[1].safety_level = 1;
123649
123650  db->magic = SQLITE_MAGIC_OPEN;
123651  if( db->mallocFailed ){
123652    goto opendb_out;
123653  }
123654
123655  /* Register all built-in functions, but do not attempt to read the
123656  ** database schema yet. This is delayed until the first time the database
123657  ** is accessed.
123658  */
123659  sqlite3Error(db, SQLITE_OK, 0);
123660  sqlite3RegisterBuiltinFunctions(db);
123661
123662  /* Load automatic extensions - extensions that have been registered
123663  ** using the sqlite3_automatic_extension() API.
123664  */
123665  rc = sqlite3_errcode(db);
123666  if( rc==SQLITE_OK ){
123667    sqlite3AutoLoadExtensions(db);
123668    rc = sqlite3_errcode(db);
123669    if( rc!=SQLITE_OK ){
123670      goto opendb_out;
123671    }
123672  }
123673
123674#ifdef SQLITE_ENABLE_FTS1
123675  if( !db->mallocFailed ){
123676    extern int sqlite3Fts1Init(sqlite3*);
123677    rc = sqlite3Fts1Init(db);
123678  }
123679#endif
123680
123681#ifdef SQLITE_ENABLE_FTS2
123682  if( !db->mallocFailed && rc==SQLITE_OK ){
123683    extern int sqlite3Fts2Init(sqlite3*);
123684    rc = sqlite3Fts2Init(db);
123685  }
123686#endif
123687
123688#ifdef SQLITE_ENABLE_FTS3
123689  if( !db->mallocFailed && rc==SQLITE_OK ){
123690    rc = sqlite3Fts3Init(db);
123691  }
123692#endif
123693
123694#ifdef SQLITE_ENABLE_ICU
123695  if( !db->mallocFailed && rc==SQLITE_OK ){
123696    rc = sqlite3IcuInit(db);
123697  }
123698#endif
123699
123700#ifdef SQLITE_ENABLE_RTREE
123701  if( !db->mallocFailed && rc==SQLITE_OK){
123702    rc = sqlite3RtreeInit(db);
123703  }
123704#endif
123705
123706  /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
123707  ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
123708  ** mode.  Doing nothing at all also makes NORMAL the default.
123709  */
123710#ifdef SQLITE_DEFAULT_LOCKING_MODE
123711  db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
123712  sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
123713                          SQLITE_DEFAULT_LOCKING_MODE);
123714#endif
123715
123716  if( rc ) sqlite3Error(db, rc, 0);
123717
123718  /* Enable the lookaside-malloc subsystem */
123719  setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
123720                        sqlite3GlobalConfig.nLookaside);
123721
123722  sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
123723
123724opendb_out:
123725  sqlite3_free(zOpen);
123726  if( db ){
123727    assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
123728    sqlite3_mutex_leave(db->mutex);
123729  }
123730  rc = sqlite3_errcode(db);
123731  assert( db!=0 || rc==SQLITE_NOMEM );
123732  if( rc==SQLITE_NOMEM ){
123733    sqlite3_close(db);
123734    db = 0;
123735  }else if( rc!=SQLITE_OK ){
123736    db->magic = SQLITE_MAGIC_SICK;
123737  }
123738  *ppDb = db;
123739#ifdef SQLITE_ENABLE_SQLLOG
123740  if( sqlite3GlobalConfig.xSqllog ){
123741    /* Opening a db handle. Fourth parameter is passed 0. */
123742    void *pArg = sqlite3GlobalConfig.pSqllogArg;
123743    sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
123744  }
123745#endif
123746  return sqlite3ApiExit(0, rc);
123747}
123748
123749/*
123750** Open a new database handle.
123751*/
123752SQLITE_API int sqlite3_open(
123753  const char *zFilename,
123754  sqlite3 **ppDb
123755){
123756  return openDatabase(zFilename, ppDb,
123757                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
123758}
123759SQLITE_API int sqlite3_open_v2(
123760  const char *filename,   /* Database filename (UTF-8) */
123761  sqlite3 **ppDb,         /* OUT: SQLite db handle */
123762  int flags,              /* Flags */
123763  const char *zVfs        /* Name of VFS module to use */
123764){
123765  return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
123766}
123767
123768#ifndef SQLITE_OMIT_UTF16
123769/*
123770** Open a new database handle.
123771*/
123772SQLITE_API int sqlite3_open16(
123773  const void *zFilename,
123774  sqlite3 **ppDb
123775){
123776  char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
123777  sqlite3_value *pVal;
123778  int rc;
123779
123780  assert( zFilename );
123781  assert( ppDb );
123782  *ppDb = 0;
123783#ifndef SQLITE_OMIT_AUTOINIT
123784  rc = sqlite3_initialize();
123785  if( rc ) return rc;
123786#endif
123787  pVal = sqlite3ValueNew(0);
123788  sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
123789  zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
123790  if( zFilename8 ){
123791    rc = openDatabase(zFilename8, ppDb,
123792                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
123793    assert( *ppDb || rc==SQLITE_NOMEM );
123794    if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
123795      ENC(*ppDb) = SQLITE_UTF16NATIVE;
123796    }
123797  }else{
123798    rc = SQLITE_NOMEM;
123799  }
123800  sqlite3ValueFree(pVal);
123801
123802  return sqlite3ApiExit(0, rc);
123803}
123804#endif /* SQLITE_OMIT_UTF16 */
123805
123806/*
123807** Register a new collation sequence with the database handle db.
123808*/
123809SQLITE_API int sqlite3_create_collation(
123810  sqlite3* db,
123811  const char *zName,
123812  int enc,
123813  void* pCtx,
123814  int(*xCompare)(void*,int,const void*,int,const void*)
123815){
123816  int rc;
123817  sqlite3_mutex_enter(db->mutex);
123818  assert( !db->mallocFailed );
123819  rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
123820  rc = sqlite3ApiExit(db, rc);
123821  sqlite3_mutex_leave(db->mutex);
123822  return rc;
123823}
123824
123825/*
123826** Register a new collation sequence with the database handle db.
123827*/
123828SQLITE_API int sqlite3_create_collation_v2(
123829  sqlite3* db,
123830  const char *zName,
123831  int enc,
123832  void* pCtx,
123833  int(*xCompare)(void*,int,const void*,int,const void*),
123834  void(*xDel)(void*)
123835){
123836  int rc;
123837  sqlite3_mutex_enter(db->mutex);
123838  assert( !db->mallocFailed );
123839  rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
123840  rc = sqlite3ApiExit(db, rc);
123841  sqlite3_mutex_leave(db->mutex);
123842  return rc;
123843}
123844
123845#ifndef SQLITE_OMIT_UTF16
123846/*
123847** Register a new collation sequence with the database handle db.
123848*/
123849SQLITE_API int sqlite3_create_collation16(
123850  sqlite3* db,
123851  const void *zName,
123852  int enc,
123853  void* pCtx,
123854  int(*xCompare)(void*,int,const void*,int,const void*)
123855){
123856  int rc = SQLITE_OK;
123857  char *zName8;
123858  sqlite3_mutex_enter(db->mutex);
123859  assert( !db->mallocFailed );
123860  zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
123861  if( zName8 ){
123862    rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
123863    sqlite3DbFree(db, zName8);
123864  }
123865  rc = sqlite3ApiExit(db, rc);
123866  sqlite3_mutex_leave(db->mutex);
123867  return rc;
123868}
123869#endif /* SQLITE_OMIT_UTF16 */
123870
123871/*
123872** Register a collation sequence factory callback with the database handle
123873** db. Replace any previously installed collation sequence factory.
123874*/
123875SQLITE_API int sqlite3_collation_needed(
123876  sqlite3 *db,
123877  void *pCollNeededArg,
123878  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
123879){
123880  sqlite3_mutex_enter(db->mutex);
123881  db->xCollNeeded = xCollNeeded;
123882  db->xCollNeeded16 = 0;
123883  db->pCollNeededArg = pCollNeededArg;
123884  sqlite3_mutex_leave(db->mutex);
123885  return SQLITE_OK;
123886}
123887
123888#ifndef SQLITE_OMIT_UTF16
123889/*
123890** Register a collation sequence factory callback with the database handle
123891** db. Replace any previously installed collation sequence factory.
123892*/
123893SQLITE_API int sqlite3_collation_needed16(
123894  sqlite3 *db,
123895  void *pCollNeededArg,
123896  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
123897){
123898  sqlite3_mutex_enter(db->mutex);
123899  db->xCollNeeded = 0;
123900  db->xCollNeeded16 = xCollNeeded16;
123901  db->pCollNeededArg = pCollNeededArg;
123902  sqlite3_mutex_leave(db->mutex);
123903  return SQLITE_OK;
123904}
123905#endif /* SQLITE_OMIT_UTF16 */
123906
123907#ifndef SQLITE_OMIT_DEPRECATED
123908/*
123909** This function is now an anachronism. It used to be used to recover from a
123910** malloc() failure, but SQLite now does this automatically.
123911*/
123912SQLITE_API int sqlite3_global_recover(void){
123913  return SQLITE_OK;
123914}
123915#endif
123916
123917/*
123918** Test to see whether or not the database connection is in autocommit
123919** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
123920** by default.  Autocommit is disabled by a BEGIN statement and reenabled
123921** by the next COMMIT or ROLLBACK.
123922*/
123923SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
123924  return db->autoCommit;
123925}
123926
123927/*
123928** The following routines are subtitutes for constants SQLITE_CORRUPT,
123929** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
123930** constants.  They server two purposes:
123931**
123932**   1.  Serve as a convenient place to set a breakpoint in a debugger
123933**       to detect when version error conditions occurs.
123934**
123935**   2.  Invoke sqlite3_log() to provide the source code location where
123936**       a low-level error is first detected.
123937*/
123938SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
123939  testcase( sqlite3GlobalConfig.xLog!=0 );
123940  sqlite3_log(SQLITE_CORRUPT,
123941              "database corruption at line %d of [%.10s]",
123942              lineno, 20+sqlite3_sourceid());
123943  return SQLITE_CORRUPT;
123944}
123945SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
123946  testcase( sqlite3GlobalConfig.xLog!=0 );
123947  sqlite3_log(SQLITE_MISUSE,
123948              "misuse at line %d of [%.10s]",
123949              lineno, 20+sqlite3_sourceid());
123950  return SQLITE_MISUSE;
123951}
123952SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
123953  testcase( sqlite3GlobalConfig.xLog!=0 );
123954  sqlite3_log(SQLITE_CANTOPEN,
123955              "cannot open file at line %d of [%.10s]",
123956              lineno, 20+sqlite3_sourceid());
123957  return SQLITE_CANTOPEN;
123958}
123959
123960
123961#ifndef SQLITE_OMIT_DEPRECATED
123962/*
123963** This is a convenience routine that makes sure that all thread-specific
123964** data for this thread has been deallocated.
123965**
123966** SQLite no longer uses thread-specific data so this routine is now a
123967** no-op.  It is retained for historical compatibility.
123968*/
123969SQLITE_API void sqlite3_thread_cleanup(void){
123970}
123971#endif
123972
123973/*
123974** Return meta information about a specific column of a database table.
123975** See comment in sqlite3.h (sqlite.h.in) for details.
123976*/
123977#ifdef SQLITE_ENABLE_COLUMN_METADATA
123978SQLITE_API int sqlite3_table_column_metadata(
123979  sqlite3 *db,                /* Connection handle */
123980  const char *zDbName,        /* Database name or NULL */
123981  const char *zTableName,     /* Table name */
123982  const char *zColumnName,    /* Column name */
123983  char const **pzDataType,    /* OUTPUT: Declared data type */
123984  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
123985  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
123986  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
123987  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
123988){
123989  int rc;
123990  char *zErrMsg = 0;
123991  Table *pTab = 0;
123992  Column *pCol = 0;
123993  int iCol;
123994
123995  char const *zDataType = 0;
123996  char const *zCollSeq = 0;
123997  int notnull = 0;
123998  int primarykey = 0;
123999  int autoinc = 0;
124000
124001  /* Ensure the database schema has been loaded */
124002  sqlite3_mutex_enter(db->mutex);
124003  sqlite3BtreeEnterAll(db);
124004  rc = sqlite3Init(db, &zErrMsg);
124005  if( SQLITE_OK!=rc ){
124006    goto error_out;
124007  }
124008
124009  /* Locate the table in question */
124010  pTab = sqlite3FindTable(db, zTableName, zDbName);
124011  if( !pTab || pTab->pSelect ){
124012    pTab = 0;
124013    goto error_out;
124014  }
124015
124016  /* Find the column for which info is requested */
124017  if( sqlite3IsRowid(zColumnName) ){
124018    iCol = pTab->iPKey;
124019    if( iCol>=0 ){
124020      pCol = &pTab->aCol[iCol];
124021    }
124022  }else{
124023    for(iCol=0; iCol<pTab->nCol; iCol++){
124024      pCol = &pTab->aCol[iCol];
124025      if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
124026        break;
124027      }
124028    }
124029    if( iCol==pTab->nCol ){
124030      pTab = 0;
124031      goto error_out;
124032    }
124033  }
124034
124035  /* The following block stores the meta information that will be returned
124036  ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
124037  ** and autoinc. At this point there are two possibilities:
124038  **
124039  **     1. The specified column name was rowid", "oid" or "_rowid_"
124040  **        and there is no explicitly declared IPK column.
124041  **
124042  **     2. The table is not a view and the column name identified an
124043  **        explicitly declared column. Copy meta information from *pCol.
124044  */
124045  if( pCol ){
124046    zDataType = pCol->zType;
124047    zCollSeq = pCol->zColl;
124048    notnull = pCol->notNull!=0;
124049    primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
124050    autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
124051  }else{
124052    zDataType = "INTEGER";
124053    primarykey = 1;
124054  }
124055  if( !zCollSeq ){
124056    zCollSeq = "BINARY";
124057  }
124058
124059error_out:
124060  sqlite3BtreeLeaveAll(db);
124061
124062  /* Whether the function call succeeded or failed, set the output parameters
124063  ** to whatever their local counterparts contain. If an error did occur,
124064  ** this has the effect of zeroing all output parameters.
124065  */
124066  if( pzDataType ) *pzDataType = zDataType;
124067  if( pzCollSeq ) *pzCollSeq = zCollSeq;
124068  if( pNotNull ) *pNotNull = notnull;
124069  if( pPrimaryKey ) *pPrimaryKey = primarykey;
124070  if( pAutoinc ) *pAutoinc = autoinc;
124071
124072  if( SQLITE_OK==rc && !pTab ){
124073    sqlite3DbFree(db, zErrMsg);
124074    zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
124075        zColumnName);
124076    rc = SQLITE_ERROR;
124077  }
124078  sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
124079  sqlite3DbFree(db, zErrMsg);
124080  rc = sqlite3ApiExit(db, rc);
124081  sqlite3_mutex_leave(db->mutex);
124082  return rc;
124083}
124084#endif
124085
124086/*
124087** Sleep for a little while.  Return the amount of time slept.
124088*/
124089SQLITE_API int sqlite3_sleep(int ms){
124090  sqlite3_vfs *pVfs;
124091  int rc;
124092  pVfs = sqlite3_vfs_find(0);
124093  if( pVfs==0 ) return 0;
124094
124095  /* This function works in milliseconds, but the underlying OsSleep()
124096  ** API uses microseconds. Hence the 1000's.
124097  */
124098  rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
124099  return rc;
124100}
124101
124102/*
124103** Enable or disable the extended result codes.
124104*/
124105SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
124106  sqlite3_mutex_enter(db->mutex);
124107  db->errMask = onoff ? 0xffffffff : 0xff;
124108  sqlite3_mutex_leave(db->mutex);
124109  return SQLITE_OK;
124110}
124111
124112/*
124113** Invoke the xFileControl method on a particular database.
124114*/
124115SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
124116  int rc = SQLITE_ERROR;
124117  Btree *pBtree;
124118
124119  sqlite3_mutex_enter(db->mutex);
124120  pBtree = sqlite3DbNameToBtree(db, zDbName);
124121  if( pBtree ){
124122    Pager *pPager;
124123    sqlite3_file *fd;
124124    sqlite3BtreeEnter(pBtree);
124125    pPager = sqlite3BtreePager(pBtree);
124126    assert( pPager!=0 );
124127    fd = sqlite3PagerFile(pPager);
124128    assert( fd!=0 );
124129    if( op==SQLITE_FCNTL_FILE_POINTER ){
124130      *(sqlite3_file**)pArg = fd;
124131      rc = SQLITE_OK;
124132    }else if( fd->pMethods ){
124133      rc = sqlite3OsFileControl(fd, op, pArg);
124134    }else{
124135      rc = SQLITE_NOTFOUND;
124136    }
124137    sqlite3BtreeLeave(pBtree);
124138  }
124139  sqlite3_mutex_leave(db->mutex);
124140  return rc;
124141}
124142
124143/*
124144** Interface to the testing logic.
124145*/
124146SQLITE_API int sqlite3_test_control(int op, ...){
124147  int rc = 0;
124148#ifndef SQLITE_OMIT_BUILTIN_TEST
124149  va_list ap;
124150  va_start(ap, op);
124151  switch( op ){
124152
124153    /*
124154    ** Save the current state of the PRNG.
124155    */
124156    case SQLITE_TESTCTRL_PRNG_SAVE: {
124157      sqlite3PrngSaveState();
124158      break;
124159    }
124160
124161    /*
124162    ** Restore the state of the PRNG to the last state saved using
124163    ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
124164    ** this verb acts like PRNG_RESET.
124165    */
124166    case SQLITE_TESTCTRL_PRNG_RESTORE: {
124167      sqlite3PrngRestoreState();
124168      break;
124169    }
124170
124171    /*
124172    ** Reset the PRNG back to its uninitialized state.  The next call
124173    ** to sqlite3_randomness() will reseed the PRNG using a single call
124174    ** to the xRandomness method of the default VFS.
124175    */
124176    case SQLITE_TESTCTRL_PRNG_RESET: {
124177      sqlite3_randomness(0,0);
124178      break;
124179    }
124180
124181    /*
124182    **  sqlite3_test_control(BITVEC_TEST, size, program)
124183    **
124184    ** Run a test against a Bitvec object of size.  The program argument
124185    ** is an array of integers that defines the test.  Return -1 on a
124186    ** memory allocation error, 0 on success, or non-zero for an error.
124187    ** See the sqlite3BitvecBuiltinTest() for additional information.
124188    */
124189    case SQLITE_TESTCTRL_BITVEC_TEST: {
124190      int sz = va_arg(ap, int);
124191      int *aProg = va_arg(ap, int*);
124192      rc = sqlite3BitvecBuiltinTest(sz, aProg);
124193      break;
124194    }
124195
124196    /*
124197    **  sqlite3_test_control(FAULT_INSTALL, xCallback)
124198    **
124199    ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
124200    ** if xCallback is not NULL.
124201    **
124202    ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
124203    ** is called immediately after installing the new callback and the return
124204    ** value from sqlite3FaultSim(0) becomes the return from
124205    ** sqlite3_test_control().
124206    */
124207    case SQLITE_TESTCTRL_FAULT_INSTALL: {
124208      /* MSVC is picky about pulling func ptrs from va lists.
124209      ** http://support.microsoft.com/kb/47961
124210      ** sqlite3Config.xTestCallback = va_arg(ap, int(*)(int));
124211      */
124212      typedef int(*TESTCALLBACKFUNC_t)(int);
124213      sqlite3Config.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
124214      rc = sqlite3FaultSim(0);
124215      break;
124216    }
124217
124218    /*
124219    **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
124220    **
124221    ** Register hooks to call to indicate which malloc() failures
124222    ** are benign.
124223    */
124224    case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
124225      typedef void (*void_function)(void);
124226      void_function xBenignBegin;
124227      void_function xBenignEnd;
124228      xBenignBegin = va_arg(ap, void_function);
124229      xBenignEnd = va_arg(ap, void_function);
124230      sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
124231      break;
124232    }
124233
124234    /*
124235    **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
124236    **
124237    ** Set the PENDING byte to the value in the argument, if X>0.
124238    ** Make no changes if X==0.  Return the value of the pending byte
124239    ** as it existing before this routine was called.
124240    **
124241    ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
124242    ** an incompatible database file format.  Changing the PENDING byte
124243    ** while any database connection is open results in undefined and
124244    ** dileterious behavior.
124245    */
124246    case SQLITE_TESTCTRL_PENDING_BYTE: {
124247      rc = PENDING_BYTE;
124248#ifndef SQLITE_OMIT_WSD
124249      {
124250        unsigned int newVal = va_arg(ap, unsigned int);
124251        if( newVal ) sqlite3PendingByte = newVal;
124252      }
124253#endif
124254      break;
124255    }
124256
124257    /*
124258    **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
124259    **
124260    ** This action provides a run-time test to see whether or not
124261    ** assert() was enabled at compile-time.  If X is true and assert()
124262    ** is enabled, then the return value is true.  If X is true and
124263    ** assert() is disabled, then the return value is zero.  If X is
124264    ** false and assert() is enabled, then the assertion fires and the
124265    ** process aborts.  If X is false and assert() is disabled, then the
124266    ** return value is zero.
124267    */
124268    case SQLITE_TESTCTRL_ASSERT: {
124269      volatile int x = 0;
124270      assert( (x = va_arg(ap,int))!=0 );
124271      rc = x;
124272      break;
124273    }
124274
124275
124276    /*
124277    **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
124278    **
124279    ** This action provides a run-time test to see how the ALWAYS and
124280    ** NEVER macros were defined at compile-time.
124281    **
124282    ** The return value is ALWAYS(X).
124283    **
124284    ** The recommended test is X==2.  If the return value is 2, that means
124285    ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
124286    ** default setting.  If the return value is 1, then ALWAYS() is either
124287    ** hard-coded to true or else it asserts if its argument is false.
124288    ** The first behavior (hard-coded to true) is the case if
124289    ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
124290    ** behavior (assert if the argument to ALWAYS() is false) is the case if
124291    ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
124292    **
124293    ** The run-time test procedure might look something like this:
124294    **
124295    **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
124296    **      // ALWAYS() and NEVER() are no-op pass-through macros
124297    **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
124298    **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
124299    **    }else{
124300    **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
124301    **    }
124302    */
124303    case SQLITE_TESTCTRL_ALWAYS: {
124304      int x = va_arg(ap,int);
124305      rc = ALWAYS(x);
124306      break;
124307    }
124308
124309    /*
124310    **   sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
124311    **
124312    ** The integer returned reveals the byte-order of the computer on which
124313    ** SQLite is running:
124314    **
124315    **       1     big-endian,    determined at run-time
124316    **      10     little-endian, determined at run-time
124317    **  432101     big-endian,    determined at compile-time
124318    **  123410     little-endian, determined at compile-time
124319    */
124320    case SQLITE_TESTCTRL_BYTEORDER: {
124321      rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
124322      break;
124323    }
124324
124325    /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
124326    **
124327    ** Set the nReserve size to N for the main database on the database
124328    ** connection db.
124329    */
124330    case SQLITE_TESTCTRL_RESERVE: {
124331      sqlite3 *db = va_arg(ap, sqlite3*);
124332      int x = va_arg(ap,int);
124333      sqlite3_mutex_enter(db->mutex);
124334      sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
124335      sqlite3_mutex_leave(db->mutex);
124336      break;
124337    }
124338
124339    /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
124340    **
124341    ** Enable or disable various optimizations for testing purposes.  The
124342    ** argument N is a bitmask of optimizations to be disabled.  For normal
124343    ** operation N should be 0.  The idea is that a test program (like the
124344    ** SQL Logic Test or SLT test module) can run the same SQL multiple times
124345    ** with various optimizations disabled to verify that the same answer
124346    ** is obtained in every case.
124347    */
124348    case SQLITE_TESTCTRL_OPTIMIZATIONS: {
124349      sqlite3 *db = va_arg(ap, sqlite3*);
124350      db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
124351      break;
124352    }
124353
124354#ifdef SQLITE_N_KEYWORD
124355    /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
124356    **
124357    ** If zWord is a keyword recognized by the parser, then return the
124358    ** number of keywords.  Or if zWord is not a keyword, return 0.
124359    **
124360    ** This test feature is only available in the amalgamation since
124361    ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
124362    ** is built using separate source files.
124363    */
124364    case SQLITE_TESTCTRL_ISKEYWORD: {
124365      const char *zWord = va_arg(ap, const char*);
124366      int n = sqlite3Strlen30(zWord);
124367      rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
124368      break;
124369    }
124370#endif
124371
124372    /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
124373    **
124374    ** Pass pFree into sqlite3ScratchFree().
124375    ** If sz>0 then allocate a scratch buffer into pNew.
124376    */
124377    case SQLITE_TESTCTRL_SCRATCHMALLOC: {
124378      void *pFree, **ppNew;
124379      int sz;
124380      sz = va_arg(ap, int);
124381      ppNew = va_arg(ap, void**);
124382      pFree = va_arg(ap, void*);
124383      if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
124384      sqlite3ScratchFree(pFree);
124385      break;
124386    }
124387
124388    /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
124389    **
124390    ** If parameter onoff is non-zero, configure the wrappers so that all
124391    ** subsequent calls to localtime() and variants fail. If onoff is zero,
124392    ** undo this setting.
124393    */
124394    case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
124395      sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
124396      break;
124397    }
124398
124399#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
124400    /*   sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT,
124401    **                        sqlite3_stmt*,const char**);
124402    **
124403    ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds
124404    ** a string that describes the optimized parse tree.  This test-control
124405    ** returns a pointer to that string.
124406    */
124407    case SQLITE_TESTCTRL_EXPLAIN_STMT: {
124408      sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*);
124409      const char **pzRet = va_arg(ap, const char**);
124410      *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt);
124411      break;
124412    }
124413#endif
124414
124415    /*   sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
124416    **
124417    ** Set or clear a flag that indicates that the database file is always well-
124418    ** formed and never corrupt.  This flag is clear by default, indicating that
124419    ** database files might have arbitrary corruption.  Setting the flag during
124420    ** testing causes certain assert() statements in the code to be activated
124421    ** that demonstrat invariants on well-formed database files.
124422    */
124423    case SQLITE_TESTCTRL_NEVER_CORRUPT: {
124424      sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
124425      break;
124426    }
124427
124428
124429    /*   sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
124430    **
124431    ** Set the VDBE coverage callback function to xCallback with context
124432    ** pointer ptr.
124433    */
124434    case SQLITE_TESTCTRL_VDBE_COVERAGE: {
124435#ifdef SQLITE_VDBE_COVERAGE
124436      typedef void (*branch_callback)(void*,int,u8,u8);
124437      sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
124438      sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
124439#endif
124440      break;
124441    }
124442
124443  }
124444  va_end(ap);
124445#endif /* SQLITE_OMIT_BUILTIN_TEST */
124446  return rc;
124447}
124448
124449/*
124450** This is a utility routine, useful to VFS implementations, that checks
124451** to see if a database file was a URI that contained a specific query
124452** parameter, and if so obtains the value of the query parameter.
124453**
124454** The zFilename argument is the filename pointer passed into the xOpen()
124455** method of a VFS implementation.  The zParam argument is the name of the
124456** query parameter we seek.  This routine returns the value of the zParam
124457** parameter if it exists.  If the parameter does not exist, this routine
124458** returns a NULL pointer.
124459*/
124460SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
124461  if( zFilename==0 ) return 0;
124462  zFilename += sqlite3Strlen30(zFilename) + 1;
124463  while( zFilename[0] ){
124464    int x = strcmp(zFilename, zParam);
124465    zFilename += sqlite3Strlen30(zFilename) + 1;
124466    if( x==0 ) return zFilename;
124467    zFilename += sqlite3Strlen30(zFilename) + 1;
124468  }
124469  return 0;
124470}
124471
124472/*
124473** Return a boolean value for a query parameter.
124474*/
124475SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
124476  const char *z = sqlite3_uri_parameter(zFilename, zParam);
124477  bDflt = bDflt!=0;
124478  return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
124479}
124480
124481/*
124482** Return a 64-bit integer value for a query parameter.
124483*/
124484SQLITE_API sqlite3_int64 sqlite3_uri_int64(
124485  const char *zFilename,    /* Filename as passed to xOpen */
124486  const char *zParam,       /* URI parameter sought */
124487  sqlite3_int64 bDflt       /* return if parameter is missing */
124488){
124489  const char *z = sqlite3_uri_parameter(zFilename, zParam);
124490  sqlite3_int64 v;
124491  if( z && sqlite3Atoi64(z, &v, sqlite3Strlen30(z), SQLITE_UTF8)==SQLITE_OK ){
124492    bDflt = v;
124493  }
124494  return bDflt;
124495}
124496
124497/*
124498** Return the Btree pointer identified by zDbName.  Return NULL if not found.
124499*/
124500SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
124501  int i;
124502  for(i=0; i<db->nDb; i++){
124503    if( db->aDb[i].pBt
124504     && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
124505    ){
124506      return db->aDb[i].pBt;
124507    }
124508  }
124509  return 0;
124510}
124511
124512/*
124513** Return the filename of the database associated with a database
124514** connection.
124515*/
124516SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
124517  Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
124518  return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
124519}
124520
124521/*
124522** Return 1 if database is read-only or 0 if read/write.  Return -1 if
124523** no such database exists.
124524*/
124525SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
124526  Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
124527  return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
124528}
124529
124530/************** End of main.c ************************************************/
124531/************** Begin file notify.c ******************************************/
124532/*
124533** 2009 March 3
124534**
124535** The author disclaims copyright to this source code.  In place of
124536** a legal notice, here is a blessing:
124537**
124538**    May you do good and not evil.
124539**    May you find forgiveness for yourself and forgive others.
124540**    May you share freely, never taking more than you give.
124541**
124542*************************************************************************
124543**
124544** This file contains the implementation of the sqlite3_unlock_notify()
124545** API method and its associated functionality.
124546*/
124547
124548/* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
124549#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
124550
124551/*
124552** Public interfaces:
124553**
124554**   sqlite3ConnectionBlocked()
124555**   sqlite3ConnectionUnlocked()
124556**   sqlite3ConnectionClosed()
124557**   sqlite3_unlock_notify()
124558*/
124559
124560#define assertMutexHeld() \
124561  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
124562
124563/*
124564** Head of a linked list of all sqlite3 objects created by this process
124565** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
124566** is not NULL. This variable may only accessed while the STATIC_MASTER
124567** mutex is held.
124568*/
124569static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
124570
124571#ifndef NDEBUG
124572/*
124573** This function is a complex assert() that verifies the following
124574** properties of the blocked connections list:
124575**
124576**   1) Each entry in the list has a non-NULL value for either
124577**      pUnlockConnection or pBlockingConnection, or both.
124578**
124579**   2) All entries in the list that share a common value for
124580**      xUnlockNotify are grouped together.
124581**
124582**   3) If the argument db is not NULL, then none of the entries in the
124583**      blocked connections list have pUnlockConnection or pBlockingConnection
124584**      set to db. This is used when closing connection db.
124585*/
124586static void checkListProperties(sqlite3 *db){
124587  sqlite3 *p;
124588  for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
124589    int seen = 0;
124590    sqlite3 *p2;
124591
124592    /* Verify property (1) */
124593    assert( p->pUnlockConnection || p->pBlockingConnection );
124594
124595    /* Verify property (2) */
124596    for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
124597      if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
124598      assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
124599      assert( db==0 || p->pUnlockConnection!=db );
124600      assert( db==0 || p->pBlockingConnection!=db );
124601    }
124602  }
124603}
124604#else
124605# define checkListProperties(x)
124606#endif
124607
124608/*
124609** Remove connection db from the blocked connections list. If connection
124610** db is not currently a part of the list, this function is a no-op.
124611*/
124612static void removeFromBlockedList(sqlite3 *db){
124613  sqlite3 **pp;
124614  assertMutexHeld();
124615  for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
124616    if( *pp==db ){
124617      *pp = (*pp)->pNextBlocked;
124618      break;
124619    }
124620  }
124621}
124622
124623/*
124624** Add connection db to the blocked connections list. It is assumed
124625** that it is not already a part of the list.
124626*/
124627static void addToBlockedList(sqlite3 *db){
124628  sqlite3 **pp;
124629  assertMutexHeld();
124630  for(
124631    pp=&sqlite3BlockedList;
124632    *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
124633    pp=&(*pp)->pNextBlocked
124634  );
124635  db->pNextBlocked = *pp;
124636  *pp = db;
124637}
124638
124639/*
124640** Obtain the STATIC_MASTER mutex.
124641*/
124642static void enterMutex(void){
124643  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
124644  checkListProperties(0);
124645}
124646
124647/*
124648** Release the STATIC_MASTER mutex.
124649*/
124650static void leaveMutex(void){
124651  assertMutexHeld();
124652  checkListProperties(0);
124653  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
124654}
124655
124656/*
124657** Register an unlock-notify callback.
124658**
124659** This is called after connection "db" has attempted some operation
124660** but has received an SQLITE_LOCKED error because another connection
124661** (call it pOther) in the same process was busy using the same shared
124662** cache.  pOther is found by looking at db->pBlockingConnection.
124663**
124664** If there is no blocking connection, the callback is invoked immediately,
124665** before this routine returns.
124666**
124667** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
124668** a deadlock.
124669**
124670** Otherwise, make arrangements to invoke xNotify when pOther drops
124671** its locks.
124672**
124673** Each call to this routine overrides any prior callbacks registered
124674** on the same "db".  If xNotify==0 then any prior callbacks are immediately
124675** cancelled.
124676*/
124677SQLITE_API int sqlite3_unlock_notify(
124678  sqlite3 *db,
124679  void (*xNotify)(void **, int),
124680  void *pArg
124681){
124682  int rc = SQLITE_OK;
124683
124684  sqlite3_mutex_enter(db->mutex);
124685  enterMutex();
124686
124687  if( xNotify==0 ){
124688    removeFromBlockedList(db);
124689    db->pBlockingConnection = 0;
124690    db->pUnlockConnection = 0;
124691    db->xUnlockNotify = 0;
124692    db->pUnlockArg = 0;
124693  }else if( 0==db->pBlockingConnection ){
124694    /* The blocking transaction has been concluded. Or there never was a
124695    ** blocking transaction. In either case, invoke the notify callback
124696    ** immediately.
124697    */
124698    xNotify(&pArg, 1);
124699  }else{
124700    sqlite3 *p;
124701
124702    for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
124703    if( p ){
124704      rc = SQLITE_LOCKED;              /* Deadlock detected. */
124705    }else{
124706      db->pUnlockConnection = db->pBlockingConnection;
124707      db->xUnlockNotify = xNotify;
124708      db->pUnlockArg = pArg;
124709      removeFromBlockedList(db);
124710      addToBlockedList(db);
124711    }
124712  }
124713
124714  leaveMutex();
124715  assert( !db->mallocFailed );
124716  sqlite3Error(db, rc, (rc?"database is deadlocked":0));
124717  sqlite3_mutex_leave(db->mutex);
124718  return rc;
124719}
124720
124721/*
124722** This function is called while stepping or preparing a statement
124723** associated with connection db. The operation will return SQLITE_LOCKED
124724** to the user because it requires a lock that will not be available
124725** until connection pBlocker concludes its current transaction.
124726*/
124727SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
124728  enterMutex();
124729  if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
124730    addToBlockedList(db);
124731  }
124732  db->pBlockingConnection = pBlocker;
124733  leaveMutex();
124734}
124735
124736/*
124737** This function is called when
124738** the transaction opened by database db has just finished. Locks held
124739** by database connection db have been released.
124740**
124741** This function loops through each entry in the blocked connections
124742** list and does the following:
124743**
124744**   1) If the sqlite3.pBlockingConnection member of a list entry is
124745**      set to db, then set pBlockingConnection=0.
124746**
124747**   2) If the sqlite3.pUnlockConnection member of a list entry is
124748**      set to db, then invoke the configured unlock-notify callback and
124749**      set pUnlockConnection=0.
124750**
124751**   3) If the two steps above mean that pBlockingConnection==0 and
124752**      pUnlockConnection==0, remove the entry from the blocked connections
124753**      list.
124754*/
124755SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
124756  void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
124757  int nArg = 0;                            /* Number of entries in aArg[] */
124758  sqlite3 **pp;                            /* Iterator variable */
124759  void **aArg;               /* Arguments to the unlock callback */
124760  void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
124761  void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
124762
124763  aArg = aStatic;
124764  enterMutex();         /* Enter STATIC_MASTER mutex */
124765
124766  /* This loop runs once for each entry in the blocked-connections list. */
124767  for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
124768    sqlite3 *p = *pp;
124769
124770    /* Step 1. */
124771    if( p->pBlockingConnection==db ){
124772      p->pBlockingConnection = 0;
124773    }
124774
124775    /* Step 2. */
124776    if( p->pUnlockConnection==db ){
124777      assert( p->xUnlockNotify );
124778      if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
124779        xUnlockNotify(aArg, nArg);
124780        nArg = 0;
124781      }
124782
124783      sqlite3BeginBenignMalloc();
124784      assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
124785      assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
124786      if( (!aDyn && nArg==(int)ArraySize(aStatic))
124787       || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
124788      ){
124789        /* The aArg[] array needs to grow. */
124790        void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
124791        if( pNew ){
124792          memcpy(pNew, aArg, nArg*sizeof(void *));
124793          sqlite3_free(aDyn);
124794          aDyn = aArg = pNew;
124795        }else{
124796          /* This occurs when the array of context pointers that need to
124797          ** be passed to the unlock-notify callback is larger than the
124798          ** aStatic[] array allocated on the stack and the attempt to
124799          ** allocate a larger array from the heap has failed.
124800          **
124801          ** This is a difficult situation to handle. Returning an error
124802          ** code to the caller is insufficient, as even if an error code
124803          ** is returned the transaction on connection db will still be
124804          ** closed and the unlock-notify callbacks on blocked connections
124805          ** will go unissued. This might cause the application to wait
124806          ** indefinitely for an unlock-notify callback that will never
124807          ** arrive.
124808          **
124809          ** Instead, invoke the unlock-notify callback with the context
124810          ** array already accumulated. We can then clear the array and
124811          ** begin accumulating any further context pointers without
124812          ** requiring any dynamic allocation. This is sub-optimal because
124813          ** it means that instead of one callback with a large array of
124814          ** context pointers the application will receive two or more
124815          ** callbacks with smaller arrays of context pointers, which will
124816          ** reduce the applications ability to prioritize multiple
124817          ** connections. But it is the best that can be done under the
124818          ** circumstances.
124819          */
124820          xUnlockNotify(aArg, nArg);
124821          nArg = 0;
124822        }
124823      }
124824      sqlite3EndBenignMalloc();
124825
124826      aArg[nArg++] = p->pUnlockArg;
124827      xUnlockNotify = p->xUnlockNotify;
124828      p->pUnlockConnection = 0;
124829      p->xUnlockNotify = 0;
124830      p->pUnlockArg = 0;
124831    }
124832
124833    /* Step 3. */
124834    if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
124835      /* Remove connection p from the blocked connections list. */
124836      *pp = p->pNextBlocked;
124837      p->pNextBlocked = 0;
124838    }else{
124839      pp = &p->pNextBlocked;
124840    }
124841  }
124842
124843  if( nArg!=0 ){
124844    xUnlockNotify(aArg, nArg);
124845  }
124846  sqlite3_free(aDyn);
124847  leaveMutex();         /* Leave STATIC_MASTER mutex */
124848}
124849
124850/*
124851** This is called when the database connection passed as an argument is
124852** being closed. The connection is removed from the blocked list.
124853*/
124854SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
124855  sqlite3ConnectionUnlocked(db);
124856  enterMutex();
124857  removeFromBlockedList(db);
124858  checkListProperties(db);
124859  leaveMutex();
124860}
124861#endif
124862
124863/************** End of notify.c **********************************************/
124864/************** Begin file fts3.c ********************************************/
124865/*
124866** 2006 Oct 10
124867**
124868** The author disclaims copyright to this source code.  In place of
124869** a legal notice, here is a blessing:
124870**
124871**    May you do good and not evil.
124872**    May you find forgiveness for yourself and forgive others.
124873**    May you share freely, never taking more than you give.
124874**
124875******************************************************************************
124876**
124877** This is an SQLite module implementing full-text search.
124878*/
124879
124880/*
124881** The code in this file is only compiled if:
124882**
124883**     * The FTS3 module is being built as an extension
124884**       (in which case SQLITE_CORE is not defined), or
124885**
124886**     * The FTS3 module is being built into the core of
124887**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
124888*/
124889
124890/* The full-text index is stored in a series of b+tree (-like)
124891** structures called segments which map terms to doclists.  The
124892** structures are like b+trees in layout, but are constructed from the
124893** bottom up in optimal fashion and are not updatable.  Since trees
124894** are built from the bottom up, things will be described from the
124895** bottom up.
124896**
124897**
124898**** Varints ****
124899** The basic unit of encoding is a variable-length integer called a
124900** varint.  We encode variable-length integers in little-endian order
124901** using seven bits * per byte as follows:
124902**
124903** KEY:
124904**         A = 0xxxxxxx    7 bits of data and one flag bit
124905**         B = 1xxxxxxx    7 bits of data and one flag bit
124906**
124907**  7 bits - A
124908** 14 bits - BA
124909** 21 bits - BBA
124910** and so on.
124911**
124912** This is similar in concept to how sqlite encodes "varints" but
124913** the encoding is not the same.  SQLite varints are big-endian
124914** are are limited to 9 bytes in length whereas FTS3 varints are
124915** little-endian and can be up to 10 bytes in length (in theory).
124916**
124917** Example encodings:
124918**
124919**     1:    0x01
124920**   127:    0x7f
124921**   128:    0x81 0x00
124922**
124923**
124924**** Document lists ****
124925** A doclist (document list) holds a docid-sorted list of hits for a
124926** given term.  Doclists hold docids and associated token positions.
124927** A docid is the unique integer identifier for a single document.
124928** A position is the index of a word within the document.  The first
124929** word of the document has a position of 0.
124930**
124931** FTS3 used to optionally store character offsets using a compile-time
124932** option.  But that functionality is no longer supported.
124933**
124934** A doclist is stored like this:
124935**
124936** array {
124937**   varint docid;          (delta from previous doclist)
124938**   array {                (position list for column 0)
124939**     varint position;     (2 more than the delta from previous position)
124940**   }
124941**   array {
124942**     varint POS_COLUMN;   (marks start of position list for new column)
124943**     varint column;       (index of new column)
124944**     array {
124945**       varint position;   (2 more than the delta from previous position)
124946**     }
124947**   }
124948**   varint POS_END;        (marks end of positions for this document.
124949** }
124950**
124951** Here, array { X } means zero or more occurrences of X, adjacent in
124952** memory.  A "position" is an index of a token in the token stream
124953** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
124954** in the same logical place as the position element, and act as sentinals
124955** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
124956** The positions numbers are not stored literally but rather as two more
124957** than the difference from the prior position, or the just the position plus
124958** 2 for the first position.  Example:
124959**
124960**   label:       A B C D E  F  G H   I  J K
124961**   value:     123 5 9 1 1 14 35 0 234 72 0
124962**
124963** The 123 value is the first docid.  For column zero in this document
124964** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
124965** at D signals the start of a new column; the 1 at E indicates that the
124966** new column is column number 1.  There are two positions at 12 and 45
124967** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
124968** 234 at I is the delta to next docid (357).  It has one position 70
124969** (72-2) and then terminates with the 0 at K.
124970**
124971** A "position-list" is the list of positions for multiple columns for
124972** a single docid.  A "column-list" is the set of positions for a single
124973** column.  Hence, a position-list consists of one or more column-lists,
124974** a document record consists of a docid followed by a position-list and
124975** a doclist consists of one or more document records.
124976**
124977** A bare doclist omits the position information, becoming an
124978** array of varint-encoded docids.
124979**
124980**** Segment leaf nodes ****
124981** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
124982** nodes are written using LeafWriter, and read using LeafReader (to
124983** iterate through a single leaf node's data) and LeavesReader (to
124984** iterate through a segment's entire leaf layer).  Leaf nodes have
124985** the format:
124986**
124987** varint iHeight;             (height from leaf level, always 0)
124988** varint nTerm;               (length of first term)
124989** char pTerm[nTerm];          (content of first term)
124990** varint nDoclist;            (length of term's associated doclist)
124991** char pDoclist[nDoclist];    (content of doclist)
124992** array {
124993**                             (further terms are delta-encoded)
124994**   varint nPrefix;           (length of prefix shared with previous term)
124995**   varint nSuffix;           (length of unshared suffix)
124996**   char pTermSuffix[nSuffix];(unshared suffix of next term)
124997**   varint nDoclist;          (length of term's associated doclist)
124998**   char pDoclist[nDoclist];  (content of doclist)
124999** }
125000**
125001** Here, array { X } means zero or more occurrences of X, adjacent in
125002** memory.
125003**
125004** Leaf nodes are broken into blocks which are stored contiguously in
125005** the %_segments table in sorted order.  This means that when the end
125006** of a node is reached, the next term is in the node with the next
125007** greater node id.
125008**
125009** New data is spilled to a new leaf node when the current node
125010** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
125011** larger than STANDALONE_MIN (default 1024) is placed in a standalone
125012** node (a leaf node with a single term and doclist).  The goal of
125013** these settings is to pack together groups of small doclists while
125014** making it efficient to directly access large doclists.  The
125015** assumption is that large doclists represent terms which are more
125016** likely to be query targets.
125017**
125018** TODO(shess) It may be useful for blocking decisions to be more
125019** dynamic.  For instance, it may make more sense to have a 2.5k leaf
125020** node rather than splitting into 2k and .5k nodes.  My intuition is
125021** that this might extend through 2x or 4x the pagesize.
125022**
125023**
125024**** Segment interior nodes ****
125025** Segment interior nodes store blockids for subtree nodes and terms
125026** to describe what data is stored by the each subtree.  Interior
125027** nodes are written using InteriorWriter, and read using
125028** InteriorReader.  InteriorWriters are created as needed when
125029** SegmentWriter creates new leaf nodes, or when an interior node
125030** itself grows too big and must be split.  The format of interior
125031** nodes:
125032**
125033** varint iHeight;           (height from leaf level, always >0)
125034** varint iBlockid;          (block id of node's leftmost subtree)
125035** optional {
125036**   varint nTerm;           (length of first term)
125037**   char pTerm[nTerm];      (content of first term)
125038**   array {
125039**                                (further terms are delta-encoded)
125040**     varint nPrefix;            (length of shared prefix with previous term)
125041**     varint nSuffix;            (length of unshared suffix)
125042**     char pTermSuffix[nSuffix]; (unshared suffix of next term)
125043**   }
125044** }
125045**
125046** Here, optional { X } means an optional element, while array { X }
125047** means zero or more occurrences of X, adjacent in memory.
125048**
125049** An interior node encodes n terms separating n+1 subtrees.  The
125050** subtree blocks are contiguous, so only the first subtree's blockid
125051** is encoded.  The subtree at iBlockid will contain all terms less
125052** than the first term encoded (or all terms if no term is encoded).
125053** Otherwise, for terms greater than or equal to pTerm[i] but less
125054** than pTerm[i+1], the subtree for that term will be rooted at
125055** iBlockid+i.  Interior nodes only store enough term data to
125056** distinguish adjacent children (if the rightmost term of the left
125057** child is "something", and the leftmost term of the right child is
125058** "wicked", only "w" is stored).
125059**
125060** New data is spilled to a new interior node at the same height when
125061** the current node exceeds INTERIOR_MAX bytes (default 2048).
125062** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
125063** interior nodes and making the tree too skinny.  The interior nodes
125064** at a given height are naturally tracked by interior nodes at
125065** height+1, and so on.
125066**
125067**
125068**** Segment directory ****
125069** The segment directory in table %_segdir stores meta-information for
125070** merging and deleting segments, and also the root node of the
125071** segment's tree.
125072**
125073** The root node is the top node of the segment's tree after encoding
125074** the entire segment, restricted to ROOT_MAX bytes (default 1024).
125075** This could be either a leaf node or an interior node.  If the top
125076** node requires more than ROOT_MAX bytes, it is flushed to %_segments
125077** and a new root interior node is generated (which should always fit
125078** within ROOT_MAX because it only needs space for 2 varints, the
125079** height and the blockid of the previous root).
125080**
125081** The meta-information in the segment directory is:
125082**   level               - segment level (see below)
125083**   idx                 - index within level
125084**                       - (level,idx uniquely identify a segment)
125085**   start_block         - first leaf node
125086**   leaves_end_block    - last leaf node
125087**   end_block           - last block (including interior nodes)
125088**   root                - contents of root node
125089**
125090** If the root node is a leaf node, then start_block,
125091** leaves_end_block, and end_block are all 0.
125092**
125093**
125094**** Segment merging ****
125095** To amortize update costs, segments are grouped into levels and
125096** merged in batches.  Each increase in level represents exponentially
125097** more documents.
125098**
125099** New documents (actually, document updates) are tokenized and
125100** written individually (using LeafWriter) to a level 0 segment, with
125101** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
125102** level 0 segments are merged into a single level 1 segment.  Level 1
125103** is populated like level 0, and eventually MERGE_COUNT level 1
125104** segments are merged to a single level 2 segment (representing
125105** MERGE_COUNT^2 updates), and so on.
125106**
125107** A segment merge traverses all segments at a given level in
125108** parallel, performing a straightforward sorted merge.  Since segment
125109** leaf nodes are written in to the %_segments table in order, this
125110** merge traverses the underlying sqlite disk structures efficiently.
125111** After the merge, all segment blocks from the merged level are
125112** deleted.
125113**
125114** MERGE_COUNT controls how often we merge segments.  16 seems to be
125115** somewhat of a sweet spot for insertion performance.  32 and 64 show
125116** very similar performance numbers to 16 on insertion, though they're
125117** a tiny bit slower (perhaps due to more overhead in merge-time
125118** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
125119** 16, 2 about 66% slower than 16.
125120**
125121** At query time, high MERGE_COUNT increases the number of segments
125122** which need to be scanned and merged.  For instance, with 100k docs
125123** inserted:
125124**
125125**    MERGE_COUNT   segments
125126**       16           25
125127**        8           12
125128**        4           10
125129**        2            6
125130**
125131** This appears to have only a moderate impact on queries for very
125132** frequent terms (which are somewhat dominated by segment merge
125133** costs), and infrequent and non-existent terms still seem to be fast
125134** even with many segments.
125135**
125136** TODO(shess) That said, it would be nice to have a better query-side
125137** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
125138** optimizations to things like doclist merging will swing the sweet
125139** spot around.
125140**
125141**
125142**
125143**** Handling of deletions and updates ****
125144** Since we're using a segmented structure, with no docid-oriented
125145** index into the term index, we clearly cannot simply update the term
125146** index when a document is deleted or updated.  For deletions, we
125147** write an empty doclist (varint(docid) varint(POS_END)), for updates
125148** we simply write the new doclist.  Segment merges overwrite older
125149** data for a particular docid with newer data, so deletes or updates
125150** will eventually overtake the earlier data and knock it out.  The
125151** query logic likewise merges doclists so that newer data knocks out
125152** older data.
125153*/
125154
125155/************** Include fts3Int.h in the middle of fts3.c ********************/
125156/************** Begin file fts3Int.h *****************************************/
125157/*
125158** 2009 Nov 12
125159**
125160** The author disclaims copyright to this source code.  In place of
125161** a legal notice, here is a blessing:
125162**
125163**    May you do good and not evil.
125164**    May you find forgiveness for yourself and forgive others.
125165**    May you share freely, never taking more than you give.
125166**
125167******************************************************************************
125168**
125169*/
125170#ifndef _FTSINT_H
125171#define _FTSINT_H
125172
125173#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
125174# define NDEBUG 1
125175#endif
125176
125177/*
125178** FTS4 is really an extension for FTS3.  It is enabled using the
125179** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
125180** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
125181*/
125182#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
125183# define SQLITE_ENABLE_FTS3
125184#endif
125185
125186#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
125187
125188/* If not building as part of the core, include sqlite3ext.h. */
125189#ifndef SQLITE_CORE
125190SQLITE_EXTENSION_INIT3
125191#endif
125192
125193/************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
125194/************** Begin file fts3_tokenizer.h **********************************/
125195/*
125196** 2006 July 10
125197**
125198** The author disclaims copyright to this source code.
125199**
125200*************************************************************************
125201** Defines the interface to tokenizers used by fulltext-search.  There
125202** are three basic components:
125203**
125204** sqlite3_tokenizer_module is a singleton defining the tokenizer
125205** interface functions.  This is essentially the class structure for
125206** tokenizers.
125207**
125208** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
125209** including customization information defined at creation time.
125210**
125211** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
125212** tokens from a particular input.
125213*/
125214#ifndef _FTS3_TOKENIZER_H_
125215#define _FTS3_TOKENIZER_H_
125216
125217/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
125218** If tokenizers are to be allowed to call sqlite3_*() functions, then
125219** we will need a way to register the API consistently.
125220*/
125221
125222/*
125223** Structures used by the tokenizer interface. When a new tokenizer
125224** implementation is registered, the caller provides a pointer to
125225** an sqlite3_tokenizer_module containing pointers to the callback
125226** functions that make up an implementation.
125227**
125228** When an fts3 table is created, it passes any arguments passed to
125229** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
125230** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
125231** implementation. The xCreate() function in turn returns an
125232** sqlite3_tokenizer structure representing the specific tokenizer to
125233** be used for the fts3 table (customized by the tokenizer clause arguments).
125234**
125235** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
125236** method is called. It returns an sqlite3_tokenizer_cursor object
125237** that may be used to tokenize a specific input buffer based on
125238** the tokenization rules supplied by a specific sqlite3_tokenizer
125239** object.
125240*/
125241typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
125242typedef struct sqlite3_tokenizer sqlite3_tokenizer;
125243typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
125244
125245struct sqlite3_tokenizer_module {
125246
125247  /*
125248  ** Structure version. Should always be set to 0 or 1.
125249  */
125250  int iVersion;
125251
125252  /*
125253  ** Create a new tokenizer. The values in the argv[] array are the
125254  ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
125255  ** TABLE statement that created the fts3 table. For example, if
125256  ** the following SQL is executed:
125257  **
125258  **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
125259  **
125260  ** then argc is set to 2, and the argv[] array contains pointers
125261  ** to the strings "arg1" and "arg2".
125262  **
125263  ** This method should return either SQLITE_OK (0), or an SQLite error
125264  ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
125265  ** to point at the newly created tokenizer structure. The generic
125266  ** sqlite3_tokenizer.pModule variable should not be initialized by
125267  ** this callback. The caller will do so.
125268  */
125269  int (*xCreate)(
125270    int argc,                           /* Size of argv array */
125271    const char *const*argv,             /* Tokenizer argument strings */
125272    sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
125273  );
125274
125275  /*
125276  ** Destroy an existing tokenizer. The fts3 module calls this method
125277  ** exactly once for each successful call to xCreate().
125278  */
125279  int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
125280
125281  /*
125282  ** Create a tokenizer cursor to tokenize an input buffer. The caller
125283  ** is responsible for ensuring that the input buffer remains valid
125284  ** until the cursor is closed (using the xClose() method).
125285  */
125286  int (*xOpen)(
125287    sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
125288    const char *pInput, int nBytes,      /* Input buffer */
125289    sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
125290  );
125291
125292  /*
125293  ** Destroy an existing tokenizer cursor. The fts3 module calls this
125294  ** method exactly once for each successful call to xOpen().
125295  */
125296  int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
125297
125298  /*
125299  ** Retrieve the next token from the tokenizer cursor pCursor. This
125300  ** method should either return SQLITE_OK and set the values of the
125301  ** "OUT" variables identified below, or SQLITE_DONE to indicate that
125302  ** the end of the buffer has been reached, or an SQLite error code.
125303  **
125304  ** *ppToken should be set to point at a buffer containing the
125305  ** normalized version of the token (i.e. after any case-folding and/or
125306  ** stemming has been performed). *pnBytes should be set to the length
125307  ** of this buffer in bytes. The input text that generated the token is
125308  ** identified by the byte offsets returned in *piStartOffset and
125309  ** *piEndOffset. *piStartOffset should be set to the index of the first
125310  ** byte of the token in the input buffer. *piEndOffset should be set
125311  ** to the index of the first byte just past the end of the token in
125312  ** the input buffer.
125313  **
125314  ** The buffer *ppToken is set to point at is managed by the tokenizer
125315  ** implementation. It is only required to be valid until the next call
125316  ** to xNext() or xClose().
125317  */
125318  /* TODO(shess) current implementation requires pInput to be
125319  ** nul-terminated.  This should either be fixed, or pInput/nBytes
125320  ** should be converted to zInput.
125321  */
125322  int (*xNext)(
125323    sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
125324    const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
125325    int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
125326    int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
125327    int *piPosition      /* OUT: Number of tokens returned before this one */
125328  );
125329
125330  /***********************************************************************
125331  ** Methods below this point are only available if iVersion>=1.
125332  */
125333
125334  /*
125335  ** Configure the language id of a tokenizer cursor.
125336  */
125337  int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
125338};
125339
125340struct sqlite3_tokenizer {
125341  const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
125342  /* Tokenizer implementations will typically add additional fields */
125343};
125344
125345struct sqlite3_tokenizer_cursor {
125346  sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
125347  /* Tokenizer implementations will typically add additional fields */
125348};
125349
125350int fts3_global_term_cnt(int iTerm, int iCol);
125351int fts3_term_cnt(int iTerm, int iCol);
125352
125353
125354#endif /* _FTS3_TOKENIZER_H_ */
125355
125356/************** End of fts3_tokenizer.h **************************************/
125357/************** Continuing where we left off in fts3Int.h ********************/
125358/************** Include fts3_hash.h in the middle of fts3Int.h ***************/
125359/************** Begin file fts3_hash.h ***************************************/
125360/*
125361** 2001 September 22
125362**
125363** The author disclaims copyright to this source code.  In place of
125364** a legal notice, here is a blessing:
125365**
125366**    May you do good and not evil.
125367**    May you find forgiveness for yourself and forgive others.
125368**    May you share freely, never taking more than you give.
125369**
125370*************************************************************************
125371** This is the header file for the generic hash-table implementation
125372** used in SQLite.  We've modified it slightly to serve as a standalone
125373** hash table implementation for the full-text indexing module.
125374**
125375*/
125376#ifndef _FTS3_HASH_H_
125377#define _FTS3_HASH_H_
125378
125379/* Forward declarations of structures. */
125380typedef struct Fts3Hash Fts3Hash;
125381typedef struct Fts3HashElem Fts3HashElem;
125382
125383/* A complete hash table is an instance of the following structure.
125384** The internals of this structure are intended to be opaque -- client
125385** code should not attempt to access or modify the fields of this structure
125386** directly.  Change this structure only by using the routines below.
125387** However, many of the "procedures" and "functions" for modifying and
125388** accessing this structure are really macros, so we can't really make
125389** this structure opaque.
125390*/
125391struct Fts3Hash {
125392  char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
125393  char copyKey;           /* True if copy of key made on insert */
125394  int count;              /* Number of entries in this table */
125395  Fts3HashElem *first;    /* The first element of the array */
125396  int htsize;             /* Number of buckets in the hash table */
125397  struct _fts3ht {        /* the hash table */
125398    int count;               /* Number of entries with this hash */
125399    Fts3HashElem *chain;     /* Pointer to first entry with this hash */
125400  } *ht;
125401};
125402
125403/* Each element in the hash table is an instance of the following
125404** structure.  All elements are stored on a single doubly-linked list.
125405**
125406** Again, this structure is intended to be opaque, but it can't really
125407** be opaque because it is used by macros.
125408*/
125409struct Fts3HashElem {
125410  Fts3HashElem *next, *prev; /* Next and previous elements in the table */
125411  void *data;                /* Data associated with this element */
125412  void *pKey; int nKey;      /* Key associated with this element */
125413};
125414
125415/*
125416** There are 2 different modes of operation for a hash table:
125417**
125418**   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
125419**                           (including the null-terminator, if any).  Case
125420**                           is respected in comparisons.
125421**
125422**   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long.
125423**                           memcmp() is used to compare keys.
125424**
125425** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
125426*/
125427#define FTS3_HASH_STRING    1
125428#define FTS3_HASH_BINARY    2
125429
125430/*
125431** Access routines.  To delete, insert a NULL pointer.
125432*/
125433SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
125434SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
125435SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
125436SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
125437SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
125438
125439/*
125440** Shorthand for the functions above
125441*/
125442#define fts3HashInit     sqlite3Fts3HashInit
125443#define fts3HashInsert   sqlite3Fts3HashInsert
125444#define fts3HashFind     sqlite3Fts3HashFind
125445#define fts3HashClear    sqlite3Fts3HashClear
125446#define fts3HashFindElem sqlite3Fts3HashFindElem
125447
125448/*
125449** Macros for looping over all elements of a hash table.  The idiom is
125450** like this:
125451**
125452**   Fts3Hash h;
125453**   Fts3HashElem *p;
125454**   ...
125455**   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
125456**     SomeStructure *pData = fts3HashData(p);
125457**     // do something with pData
125458**   }
125459*/
125460#define fts3HashFirst(H)  ((H)->first)
125461#define fts3HashNext(E)   ((E)->next)
125462#define fts3HashData(E)   ((E)->data)
125463#define fts3HashKey(E)    ((E)->pKey)
125464#define fts3HashKeysize(E) ((E)->nKey)
125465
125466/*
125467** Number of entries in a hash table
125468*/
125469#define fts3HashCount(H)  ((H)->count)
125470
125471#endif /* _FTS3_HASH_H_ */
125472
125473/************** End of fts3_hash.h *******************************************/
125474/************** Continuing where we left off in fts3Int.h ********************/
125475
125476/*
125477** This constant determines the maximum depth of an FTS expression tree
125478** that the library will create and use. FTS uses recursion to perform
125479** various operations on the query tree, so the disadvantage of a large
125480** limit is that it may allow very large queries to use large amounts
125481** of stack space (perhaps causing a stack overflow).
125482*/
125483#ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
125484# define SQLITE_FTS3_MAX_EXPR_DEPTH 12
125485#endif
125486
125487
125488/*
125489** This constant controls how often segments are merged. Once there are
125490** FTS3_MERGE_COUNT segments of level N, they are merged into a single
125491** segment of level N+1.
125492*/
125493#define FTS3_MERGE_COUNT 16
125494
125495/*
125496** This is the maximum amount of data (in bytes) to store in the
125497** Fts3Table.pendingTerms hash table. Normally, the hash table is
125498** populated as documents are inserted/updated/deleted in a transaction
125499** and used to create a new segment when the transaction is committed.
125500** However if this limit is reached midway through a transaction, a new
125501** segment is created and the hash table cleared immediately.
125502*/
125503#define FTS3_MAX_PENDING_DATA (1*1024*1024)
125504
125505/*
125506** Macro to return the number of elements in an array. SQLite has a
125507** similar macro called ArraySize(). Use a different name to avoid
125508** a collision when building an amalgamation with built-in FTS3.
125509*/
125510#define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
125511
125512
125513#ifndef MIN
125514# define MIN(x,y) ((x)<(y)?(x):(y))
125515#endif
125516#ifndef MAX
125517# define MAX(x,y) ((x)>(y)?(x):(y))
125518#endif
125519
125520/*
125521** Maximum length of a varint encoded integer. The varint format is different
125522** from that used by SQLite, so the maximum length is 10, not 9.
125523*/
125524#define FTS3_VARINT_MAX 10
125525
125526/*
125527** FTS4 virtual tables may maintain multiple indexes - one index of all terms
125528** in the document set and zero or more prefix indexes. All indexes are stored
125529** as one or more b+-trees in the %_segments and %_segdir tables.
125530**
125531** It is possible to determine which index a b+-tree belongs to based on the
125532** value stored in the "%_segdir.level" column. Given this value L, the index
125533** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
125534** level values between 0 and 1023 (inclusive) belong to index 0, all levels
125535** between 1024 and 2047 to index 1, and so on.
125536**
125537** It is considered impossible for an index to use more than 1024 levels. In
125538** theory though this may happen, but only after at least
125539** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
125540*/
125541#define FTS3_SEGDIR_MAXLEVEL      1024
125542#define FTS3_SEGDIR_MAXLEVEL_STR "1024"
125543
125544/*
125545** The testcase() macro is only used by the amalgamation.  If undefined,
125546** make it a no-op.
125547*/
125548#ifndef testcase
125549# define testcase(X)
125550#endif
125551
125552/*
125553** Terminator values for position-lists and column-lists.
125554*/
125555#define POS_COLUMN  (1)     /* Column-list terminator */
125556#define POS_END     (0)     /* Position-list terminator */
125557
125558/*
125559** This section provides definitions to allow the
125560** FTS3 extension to be compiled outside of the
125561** amalgamation.
125562*/
125563#ifndef SQLITE_AMALGAMATION
125564/*
125565** Macros indicating that conditional expressions are always true or
125566** false.
125567*/
125568#ifdef SQLITE_COVERAGE_TEST
125569# define ALWAYS(x) (1)
125570# define NEVER(X)  (0)
125571#else
125572# define ALWAYS(x) (x)
125573# define NEVER(x)  (x)
125574#endif
125575
125576/*
125577** Internal types used by SQLite.
125578*/
125579typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
125580typedef short int i16;            /* 2-byte (or larger) signed integer */
125581typedef unsigned int u32;         /* 4-byte unsigned integer */
125582typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
125583typedef sqlite3_int64 i64;        /* 8-byte signed integer */
125584
125585/*
125586** Macro used to suppress compiler warnings for unused parameters.
125587*/
125588#define UNUSED_PARAMETER(x) (void)(x)
125589
125590/*
125591** Activate assert() only if SQLITE_TEST is enabled.
125592*/
125593#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
125594# define NDEBUG 1
125595#endif
125596
125597/*
125598** The TESTONLY macro is used to enclose variable declarations or
125599** other bits of code that are needed to support the arguments
125600** within testcase() and assert() macros.
125601*/
125602#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
125603# define TESTONLY(X)  X
125604#else
125605# define TESTONLY(X)
125606#endif
125607
125608#endif /* SQLITE_AMALGAMATION */
125609
125610#ifdef SQLITE_DEBUG
125611SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
125612# define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
125613#else
125614# define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
125615#endif
125616
125617typedef struct Fts3Table Fts3Table;
125618typedef struct Fts3Cursor Fts3Cursor;
125619typedef struct Fts3Expr Fts3Expr;
125620typedef struct Fts3Phrase Fts3Phrase;
125621typedef struct Fts3PhraseToken Fts3PhraseToken;
125622
125623typedef struct Fts3Doclist Fts3Doclist;
125624typedef struct Fts3SegFilter Fts3SegFilter;
125625typedef struct Fts3DeferredToken Fts3DeferredToken;
125626typedef struct Fts3SegReader Fts3SegReader;
125627typedef struct Fts3MultiSegReader Fts3MultiSegReader;
125628
125629/*
125630** A connection to a fulltext index is an instance of the following
125631** structure. The xCreate and xConnect methods create an instance
125632** of this structure and xDestroy and xDisconnect free that instance.
125633** All other methods receive a pointer to the structure as one of their
125634** arguments.
125635*/
125636struct Fts3Table {
125637  sqlite3_vtab base;              /* Base class used by SQLite core */
125638  sqlite3 *db;                    /* The database connection */
125639  const char *zDb;                /* logical database name */
125640  const char *zName;              /* virtual table name */
125641  int nColumn;                    /* number of named columns in virtual table */
125642  char **azColumn;                /* column names.  malloced */
125643  u8 *abNotindexed;               /* True for 'notindexed' columns */
125644  sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
125645  char *zContentTbl;              /* content=xxx option, or NULL */
125646  char *zLanguageid;              /* languageid=xxx option, or NULL */
125647  int nAutoincrmerge;             /* Value configured by 'automerge' */
125648  u32 nLeafAdd;                   /* Number of leaf blocks added this trans */
125649
125650  /* Precompiled statements used by the implementation. Each of these
125651  ** statements is run and reset within a single virtual table API call.
125652  */
125653  sqlite3_stmt *aStmt[40];
125654
125655  char *zReadExprlist;
125656  char *zWriteExprlist;
125657
125658  int nNodeSize;                  /* Soft limit for node size */
125659  u8 bFts4;                       /* True for FTS4, false for FTS3 */
125660  u8 bHasStat;                    /* True if %_stat table exists (2==unknown) */
125661  u8 bHasDocsize;                 /* True if %_docsize table exists */
125662  u8 bDescIdx;                    /* True if doclists are in reverse order */
125663  u8 bIgnoreSavepoint;            /* True to ignore xSavepoint invocations */
125664  int nPgsz;                      /* Page size for host database */
125665  char *zSegmentsTbl;             /* Name of %_segments table */
125666  sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
125667
125668  /*
125669  ** The following array of hash tables is used to buffer pending index
125670  ** updates during transactions. All pending updates buffered at any one
125671  ** time must share a common language-id (see the FTS4 langid= feature).
125672  ** The current language id is stored in variable iPrevLangid.
125673  **
125674  ** A single FTS4 table may have multiple full-text indexes. For each index
125675  ** there is an entry in the aIndex[] array. Index 0 is an index of all the
125676  ** terms that appear in the document set. Each subsequent index in aIndex[]
125677  ** is an index of prefixes of a specific length.
125678  **
125679  ** Variable nPendingData contains an estimate the memory consumed by the
125680  ** pending data structures, including hash table overhead, but not including
125681  ** malloc overhead.  When nPendingData exceeds nMaxPendingData, all hash
125682  ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
125683  ** recently inserted record.
125684  */
125685  int nIndex;                     /* Size of aIndex[] */
125686  struct Fts3Index {
125687    int nPrefix;                  /* Prefix length (0 for main terms index) */
125688    Fts3Hash hPending;            /* Pending terms table for this index */
125689  } *aIndex;
125690  int nMaxPendingData;            /* Max pending data before flush to disk */
125691  int nPendingData;               /* Current bytes of pending data */
125692  sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
125693  int iPrevLangid;                /* Langid of recently inserted document */
125694
125695#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
125696  /* State variables used for validating that the transaction control
125697  ** methods of the virtual table are called at appropriate times.  These
125698  ** values do not contribute to FTS functionality; they are used for
125699  ** verifying the operation of the SQLite core.
125700  */
125701  int inTransaction;     /* True after xBegin but before xCommit/xRollback */
125702  int mxSavepoint;       /* Largest valid xSavepoint integer */
125703#endif
125704
125705#ifdef SQLITE_TEST
125706  /* True to disable the incremental doclist optimization. This is controled
125707  ** by special insert command 'test-no-incr-doclist'.  */
125708  int bNoIncrDoclist;
125709#endif
125710};
125711
125712/*
125713** When the core wants to read from the virtual table, it creates a
125714** virtual table cursor (an instance of the following structure) using
125715** the xOpen method. Cursors are destroyed using the xClose method.
125716*/
125717struct Fts3Cursor {
125718  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
125719  i16 eSearch;                    /* Search strategy (see below) */
125720  u8 isEof;                       /* True if at End Of Results */
125721  u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
125722  sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
125723  Fts3Expr *pExpr;                /* Parsed MATCH query string */
125724  int iLangid;                    /* Language being queried for */
125725  int nPhrase;                    /* Number of matchable phrases in query */
125726  Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
125727  sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
125728  char *pNextId;                  /* Pointer into the body of aDoclist */
125729  char *aDoclist;                 /* List of docids for full-text queries */
125730  int nDoclist;                   /* Size of buffer at aDoclist */
125731  u8 bDesc;                       /* True to sort in descending order */
125732  int eEvalmode;                  /* An FTS3_EVAL_XX constant */
125733  int nRowAvg;                    /* Average size of database rows, in pages */
125734  sqlite3_int64 nDoc;             /* Documents in table */
125735  i64 iMinDocid;                  /* Minimum docid to return */
125736  i64 iMaxDocid;                  /* Maximum docid to return */
125737  int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
125738  u32 *aMatchinfo;                /* Information about most recent match */
125739  int nMatchinfo;                 /* Number of elements in aMatchinfo[] */
125740  char *zMatchinfo;               /* Matchinfo specification */
125741};
125742
125743#define FTS3_EVAL_FILTER    0
125744#define FTS3_EVAL_NEXT      1
125745#define FTS3_EVAL_MATCHINFO 2
125746
125747/*
125748** The Fts3Cursor.eSearch member is always set to one of the following.
125749** Actualy, Fts3Cursor.eSearch can be greater than or equal to
125750** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
125751** of the column to be searched.  For example, in
125752**
125753**     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
125754**     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
125755**
125756** Because the LHS of the MATCH operator is 2nd column "b",
125757** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
125758** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1"
125759** indicating that all columns should be searched,
125760** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
125761*/
125762#define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
125763#define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
125764#define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
125765
125766/*
125767** The lower 16-bits of the sqlite3_index_info.idxNum value set by
125768** the xBestIndex() method contains the Fts3Cursor.eSearch value described
125769** above. The upper 16-bits contain a combination of the following
125770** bits, used to describe extra constraints on full-text searches.
125771*/
125772#define FTS3_HAVE_LANGID    0x00010000      /* languageid=? */
125773#define FTS3_HAVE_DOCID_GE  0x00020000      /* docid>=? */
125774#define FTS3_HAVE_DOCID_LE  0x00040000      /* docid<=? */
125775
125776struct Fts3Doclist {
125777  char *aAll;                    /* Array containing doclist (or NULL) */
125778  int nAll;                      /* Size of a[] in bytes */
125779  char *pNextDocid;              /* Pointer to next docid */
125780
125781  sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
125782  int bFreeList;                 /* True if pList should be sqlite3_free()d */
125783  char *pList;                   /* Pointer to position list following iDocid */
125784  int nList;                     /* Length of position list */
125785};
125786
125787/*
125788** A "phrase" is a sequence of one or more tokens that must match in
125789** sequence.  A single token is the base case and the most common case.
125790** For a sequence of tokens contained in double-quotes (i.e. "one two three")
125791** nToken will be the number of tokens in the string.
125792*/
125793struct Fts3PhraseToken {
125794  char *z;                        /* Text of the token */
125795  int n;                          /* Number of bytes in buffer z */
125796  int isPrefix;                   /* True if token ends with a "*" character */
125797  int bFirst;                     /* True if token must appear at position 0 */
125798
125799  /* Variables above this point are populated when the expression is
125800  ** parsed (by code in fts3_expr.c). Below this point the variables are
125801  ** used when evaluating the expression. */
125802  Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
125803  Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
125804};
125805
125806struct Fts3Phrase {
125807  /* Cache of doclist for this phrase. */
125808  Fts3Doclist doclist;
125809  int bIncr;                 /* True if doclist is loaded incrementally */
125810  int iDoclistToken;
125811
125812  /* Variables below this point are populated by fts3_expr.c when parsing
125813  ** a MATCH expression. Everything above is part of the evaluation phase.
125814  */
125815  int nToken;                /* Number of tokens in the phrase */
125816  int iColumn;               /* Index of column this phrase must match */
125817  Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
125818};
125819
125820/*
125821** A tree of these objects forms the RHS of a MATCH operator.
125822**
125823** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
125824** points to a malloced buffer, size nDoclist bytes, containing the results
125825** of this phrase query in FTS3 doclist format. As usual, the initial
125826** "Length" field found in doclists stored on disk is omitted from this
125827** buffer.
125828**
125829** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
125830** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
125831** where nCol is the number of columns in the queried FTS table. The array
125832** is populated as follows:
125833**
125834**   aMI[iCol*3 + 0] = Undefined
125835**   aMI[iCol*3 + 1] = Number of occurrences
125836**   aMI[iCol*3 + 2] = Number of rows containing at least one instance
125837**
125838** The aMI array is allocated using sqlite3_malloc(). It should be freed
125839** when the expression node is.
125840*/
125841struct Fts3Expr {
125842  int eType;                 /* One of the FTSQUERY_XXX values defined below */
125843  int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
125844  Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
125845  Fts3Expr *pLeft;           /* Left operand */
125846  Fts3Expr *pRight;          /* Right operand */
125847  Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
125848
125849  /* The following are used by the fts3_eval.c module. */
125850  sqlite3_int64 iDocid;      /* Current docid */
125851  u8 bEof;                   /* True this expression is at EOF already */
125852  u8 bStart;                 /* True if iDocid is valid */
125853  u8 bDeferred;              /* True if this expression is entirely deferred */
125854
125855  u32 *aMI;
125856};
125857
125858/*
125859** Candidate values for Fts3Query.eType. Note that the order of the first
125860** four values is in order of precedence when parsing expressions. For
125861** example, the following:
125862**
125863**   "a OR b AND c NOT d NEAR e"
125864**
125865** is equivalent to:
125866**
125867**   "a OR (b AND (c NOT (d NEAR e)))"
125868*/
125869#define FTSQUERY_NEAR   1
125870#define FTSQUERY_NOT    2
125871#define FTSQUERY_AND    3
125872#define FTSQUERY_OR     4
125873#define FTSQUERY_PHRASE 5
125874
125875
125876/* fts3_write.c */
125877SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
125878SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
125879SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
125880SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
125881SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
125882  sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
125883SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
125884  Fts3Table*,int,const char*,int,int,Fts3SegReader**);
125885SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
125886SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
125887SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
125888
125889SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
125890SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
125891
125892#ifndef SQLITE_DISABLE_FTS4_DEFERRED
125893SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
125894SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
125895SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
125896SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
125897SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
125898#else
125899# define sqlite3Fts3FreeDeferredTokens(x)
125900# define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
125901# define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
125902# define sqlite3Fts3FreeDeferredDoclists(x)
125903# define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
125904#endif
125905
125906SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
125907SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
125908
125909/* Special values interpreted by sqlite3SegReaderCursor() */
125910#define FTS3_SEGCURSOR_PENDING        -1
125911#define FTS3_SEGCURSOR_ALL            -2
125912
125913SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
125914SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
125915SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
125916
125917SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
125918    int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
125919
125920/* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
125921#define FTS3_SEGMENT_REQUIRE_POS   0x00000001
125922#define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
125923#define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
125924#define FTS3_SEGMENT_PREFIX        0x00000008
125925#define FTS3_SEGMENT_SCAN          0x00000010
125926#define FTS3_SEGMENT_FIRST         0x00000020
125927
125928/* Type passed as 4th argument to SegmentReaderIterate() */
125929struct Fts3SegFilter {
125930  const char *zTerm;
125931  int nTerm;
125932  int iCol;
125933  int flags;
125934};
125935
125936struct Fts3MultiSegReader {
125937  /* Used internally by sqlite3Fts3SegReaderXXX() calls */
125938  Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
125939  int nSegment;                   /* Size of apSegment array */
125940  int nAdvance;                   /* How many seg-readers to advance */
125941  Fts3SegFilter *pFilter;         /* Pointer to filter object */
125942  char *aBuffer;                  /* Buffer to merge doclists in */
125943  int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
125944
125945  int iColFilter;                 /* If >=0, filter for this column */
125946  int bRestart;
125947
125948  /* Used by fts3.c only. */
125949  int nCost;                      /* Cost of running iterator */
125950  int bLookup;                    /* True if a lookup of a single entry. */
125951
125952  /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
125953  char *zTerm;                    /* Pointer to term buffer */
125954  int nTerm;                      /* Size of zTerm in bytes */
125955  char *aDoclist;                 /* Pointer to doclist buffer */
125956  int nDoclist;                   /* Size of aDoclist[] in bytes */
125957};
125958
125959SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
125960
125961#define fts3GetVarint32(p, piVal) (                                           \
125962  (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
125963)
125964
125965/* fts3.c */
125966SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
125967SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
125968SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
125969SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
125970SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
125971SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
125972SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
125973SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
125974SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
125975
125976/* fts3_tokenizer.c */
125977SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
125978SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
125979SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
125980    sqlite3_tokenizer **, char **
125981);
125982SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
125983
125984/* fts3_snippet.c */
125985SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
125986SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
125987  const char *, const char *, int, int
125988);
125989SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
125990
125991/* fts3_expr.c */
125992SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
125993  char **, int, int, int, const char *, int, Fts3Expr **, char **
125994);
125995SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
125996#ifdef SQLITE_TEST
125997SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
125998SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
125999#endif
126000
126001SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
126002  sqlite3_tokenizer_cursor **
126003);
126004
126005/* fts3_aux.c */
126006SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
126007
126008SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
126009
126010SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
126011    Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
126012SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
126013    Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
126014SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
126015SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
126016SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
126017
126018/* fts3_tokenize_vtab.c */
126019SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
126020
126021/* fts3_unicode2.c (functions generated by parsing unicode text files) */
126022#ifdef SQLITE_ENABLE_FTS4_UNICODE61
126023SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
126024SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
126025SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
126026#endif
126027
126028#endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
126029#endif /* _FTSINT_H */
126030
126031/************** End of fts3Int.h *********************************************/
126032/************** Continuing where we left off in fts3.c ***********************/
126033#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
126034
126035#if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
126036# define SQLITE_CORE 1
126037#endif
126038
126039/* #include <assert.h> */
126040/* #include <stdlib.h> */
126041/* #include <stddef.h> */
126042/* #include <stdio.h> */
126043/* #include <string.h> */
126044/* #include <stdarg.h> */
126045
126046#ifndef SQLITE_CORE
126047  SQLITE_EXTENSION_INIT1
126048#endif
126049
126050static int fts3EvalNext(Fts3Cursor *pCsr);
126051static int fts3EvalStart(Fts3Cursor *pCsr);
126052static int fts3TermSegReaderCursor(
126053    Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
126054
126055/*
126056** Write a 64-bit variable-length integer to memory starting at p[0].
126057** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
126058** The number of bytes written is returned.
126059*/
126060SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
126061  unsigned char *q = (unsigned char *) p;
126062  sqlite_uint64 vu = v;
126063  do{
126064    *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
126065    vu >>= 7;
126066  }while( vu!=0 );
126067  q[-1] &= 0x7f;  /* turn off high bit in final byte */
126068  assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
126069  return (int) (q - (unsigned char *)p);
126070}
126071
126072#define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
126073  v = (v & mask1) | ( (*ptr++) << shift );                    \
126074  if( (v & mask2)==0 ){ var = v; return ret; }
126075#define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
126076  v = (*ptr++);                                               \
126077  if( (v & mask2)==0 ){ var = v; return ret; }
126078
126079/*
126080** Read a 64-bit variable-length integer from memory starting at p[0].
126081** Return the number of bytes read, or 0 on error.
126082** The value is stored in *v.
126083*/
126084SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
126085  const char *pStart = p;
126086  u32 a;
126087  u64 b;
126088  int shift;
126089
126090  GETVARINT_INIT(a, p, 0,  0x00,     0x80, *v, 1);
126091  GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *v, 2);
126092  GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *v, 3);
126093  GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
126094  b = (a & 0x0FFFFFFF );
126095
126096  for(shift=28; shift<=63; shift+=7){
126097    u64 c = *p++;
126098    b += (c&0x7F) << shift;
126099    if( (c & 0x80)==0 ) break;
126100  }
126101  *v = b;
126102  return (int)(p - pStart);
126103}
126104
126105/*
126106** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
126107** 32-bit integer before it is returned.
126108*/
126109SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
126110  u32 a;
126111
126112#ifndef fts3GetVarint32
126113  GETVARINT_INIT(a, p, 0,  0x00,     0x80, *pi, 1);
126114#else
126115  a = (*p++);
126116  assert( a & 0x80 );
126117#endif
126118
126119  GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *pi, 2);
126120  GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *pi, 3);
126121  GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
126122  a = (a & 0x0FFFFFFF );
126123  *pi = (int)(a | ((u32)(*p & 0x0F) << 28));
126124  return 5;
126125}
126126
126127/*
126128** Return the number of bytes required to encode v as a varint
126129*/
126130SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
126131  int i = 0;
126132  do{
126133    i++;
126134    v >>= 7;
126135  }while( v!=0 );
126136  return i;
126137}
126138
126139/*
126140** Convert an SQL-style quoted string into a normal string by removing
126141** the quote characters.  The conversion is done in-place.  If the
126142** input does not begin with a quote character, then this routine
126143** is a no-op.
126144**
126145** Examples:
126146**
126147**     "abc"   becomes   abc
126148**     'xyz'   becomes   xyz
126149**     [pqr]   becomes   pqr
126150**     `mno`   becomes   mno
126151**
126152*/
126153SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
126154  char quote;                     /* Quote character (if any ) */
126155
126156  quote = z[0];
126157  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
126158    int iIn = 1;                  /* Index of next byte to read from input */
126159    int iOut = 0;                 /* Index of next byte to write to output */
126160
126161    /* If the first byte was a '[', then the close-quote character is a ']' */
126162    if( quote=='[' ) quote = ']';
126163
126164    while( ALWAYS(z[iIn]) ){
126165      if( z[iIn]==quote ){
126166        if( z[iIn+1]!=quote ) break;
126167        z[iOut++] = quote;
126168        iIn += 2;
126169      }else{
126170        z[iOut++] = z[iIn++];
126171      }
126172    }
126173    z[iOut] = '\0';
126174  }
126175}
126176
126177/*
126178** Read a single varint from the doclist at *pp and advance *pp to point
126179** to the first byte past the end of the varint.  Add the value of the varint
126180** to *pVal.
126181*/
126182static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
126183  sqlite3_int64 iVal;
126184  *pp += sqlite3Fts3GetVarint(*pp, &iVal);
126185  *pVal += iVal;
126186}
126187
126188/*
126189** When this function is called, *pp points to the first byte following a
126190** varint that is part of a doclist (or position-list, or any other list
126191** of varints). This function moves *pp to point to the start of that varint,
126192** and sets *pVal by the varint value.
126193**
126194** Argument pStart points to the first byte of the doclist that the
126195** varint is part of.
126196*/
126197static void fts3GetReverseVarint(
126198  char **pp,
126199  char *pStart,
126200  sqlite3_int64 *pVal
126201){
126202  sqlite3_int64 iVal;
126203  char *p;
126204
126205  /* Pointer p now points at the first byte past the varint we are
126206  ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
126207  ** clear on character p[-1]. */
126208  for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
126209  p++;
126210  *pp = p;
126211
126212  sqlite3Fts3GetVarint(p, &iVal);
126213  *pVal = iVal;
126214}
126215
126216/*
126217** The xDisconnect() virtual table method.
126218*/
126219static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
126220  Fts3Table *p = (Fts3Table *)pVtab;
126221  int i;
126222
126223  assert( p->nPendingData==0 );
126224  assert( p->pSegments==0 );
126225
126226  /* Free any prepared statements held */
126227  for(i=0; i<SizeofArray(p->aStmt); i++){
126228    sqlite3_finalize(p->aStmt[i]);
126229  }
126230  sqlite3_free(p->zSegmentsTbl);
126231  sqlite3_free(p->zReadExprlist);
126232  sqlite3_free(p->zWriteExprlist);
126233  sqlite3_free(p->zContentTbl);
126234  sqlite3_free(p->zLanguageid);
126235
126236  /* Invoke the tokenizer destructor to free the tokenizer. */
126237  p->pTokenizer->pModule->xDestroy(p->pTokenizer);
126238
126239  sqlite3_free(p);
126240  return SQLITE_OK;
126241}
126242
126243/*
126244** Construct one or more SQL statements from the format string given
126245** and then evaluate those statements. The success code is written
126246** into *pRc.
126247**
126248** If *pRc is initially non-zero then this routine is a no-op.
126249*/
126250static void fts3DbExec(
126251  int *pRc,              /* Success code */
126252  sqlite3 *db,           /* Database in which to run SQL */
126253  const char *zFormat,   /* Format string for SQL */
126254  ...                    /* Arguments to the format string */
126255){
126256  va_list ap;
126257  char *zSql;
126258  if( *pRc ) return;
126259  va_start(ap, zFormat);
126260  zSql = sqlite3_vmprintf(zFormat, ap);
126261  va_end(ap);
126262  if( zSql==0 ){
126263    *pRc = SQLITE_NOMEM;
126264  }else{
126265    *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
126266    sqlite3_free(zSql);
126267  }
126268}
126269
126270/*
126271** The xDestroy() virtual table method.
126272*/
126273static int fts3DestroyMethod(sqlite3_vtab *pVtab){
126274  Fts3Table *p = (Fts3Table *)pVtab;
126275  int rc = SQLITE_OK;              /* Return code */
126276  const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
126277  sqlite3 *db = p->db;             /* Database handle */
126278
126279  /* Drop the shadow tables */
126280  if( p->zContentTbl==0 ){
126281    fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
126282  }
126283  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
126284  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
126285  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
126286  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
126287
126288  /* If everything has worked, invoke fts3DisconnectMethod() to free the
126289  ** memory associated with the Fts3Table structure and return SQLITE_OK.
126290  ** Otherwise, return an SQLite error code.
126291  */
126292  return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
126293}
126294
126295
126296/*
126297** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
126298** passed as the first argument. This is done as part of the xConnect()
126299** and xCreate() methods.
126300**
126301** If *pRc is non-zero when this function is called, it is a no-op.
126302** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
126303** before returning.
126304*/
126305static void fts3DeclareVtab(int *pRc, Fts3Table *p){
126306  if( *pRc==SQLITE_OK ){
126307    int i;                        /* Iterator variable */
126308    int rc;                       /* Return code */
126309    char *zSql;                   /* SQL statement passed to declare_vtab() */
126310    char *zCols;                  /* List of user defined columns */
126311    const char *zLanguageid;
126312
126313    zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
126314    sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
126315
126316    /* Create a list of user columns for the virtual table */
126317    zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
126318    for(i=1; zCols && i<p->nColumn; i++){
126319      zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
126320    }
126321
126322    /* Create the whole "CREATE TABLE" statement to pass to SQLite */
126323    zSql = sqlite3_mprintf(
126324        "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
126325        zCols, p->zName, zLanguageid
126326    );
126327    if( !zCols || !zSql ){
126328      rc = SQLITE_NOMEM;
126329    }else{
126330      rc = sqlite3_declare_vtab(p->db, zSql);
126331    }
126332
126333    sqlite3_free(zSql);
126334    sqlite3_free(zCols);
126335    *pRc = rc;
126336  }
126337}
126338
126339/*
126340** Create the %_stat table if it does not already exist.
126341*/
126342SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
126343  fts3DbExec(pRc, p->db,
126344      "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
126345          "(id INTEGER PRIMARY KEY, value BLOB);",
126346      p->zDb, p->zName
126347  );
126348  if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
126349}
126350
126351/*
126352** Create the backing store tables (%_content, %_segments and %_segdir)
126353** required by the FTS3 table passed as the only argument. This is done
126354** as part of the vtab xCreate() method.
126355**
126356** If the p->bHasDocsize boolean is true (indicating that this is an
126357** FTS4 table, not an FTS3 table) then also create the %_docsize and
126358** %_stat tables required by FTS4.
126359*/
126360static int fts3CreateTables(Fts3Table *p){
126361  int rc = SQLITE_OK;             /* Return code */
126362  int i;                          /* Iterator variable */
126363  sqlite3 *db = p->db;            /* The database connection */
126364
126365  if( p->zContentTbl==0 ){
126366    const char *zLanguageid = p->zLanguageid;
126367    char *zContentCols;           /* Columns of %_content table */
126368
126369    /* Create a list of user columns for the content table */
126370    zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
126371    for(i=0; zContentCols && i<p->nColumn; i++){
126372      char *z = p->azColumn[i];
126373      zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
126374    }
126375    if( zLanguageid && zContentCols ){
126376      zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
126377    }
126378    if( zContentCols==0 ) rc = SQLITE_NOMEM;
126379
126380    /* Create the content table */
126381    fts3DbExec(&rc, db,
126382       "CREATE TABLE %Q.'%q_content'(%s)",
126383       p->zDb, p->zName, zContentCols
126384    );
126385    sqlite3_free(zContentCols);
126386  }
126387
126388  /* Create other tables */
126389  fts3DbExec(&rc, db,
126390      "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
126391      p->zDb, p->zName
126392  );
126393  fts3DbExec(&rc, db,
126394      "CREATE TABLE %Q.'%q_segdir'("
126395        "level INTEGER,"
126396        "idx INTEGER,"
126397        "start_block INTEGER,"
126398        "leaves_end_block INTEGER,"
126399        "end_block INTEGER,"
126400        "root BLOB,"
126401        "PRIMARY KEY(level, idx)"
126402      ");",
126403      p->zDb, p->zName
126404  );
126405  if( p->bHasDocsize ){
126406    fts3DbExec(&rc, db,
126407        "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
126408        p->zDb, p->zName
126409    );
126410  }
126411  assert( p->bHasStat==p->bFts4 );
126412  if( p->bHasStat ){
126413    sqlite3Fts3CreateStatTable(&rc, p);
126414  }
126415  return rc;
126416}
126417
126418/*
126419** Store the current database page-size in bytes in p->nPgsz.
126420**
126421** If *pRc is non-zero when this function is called, it is a no-op.
126422** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
126423** before returning.
126424*/
126425static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
126426  if( *pRc==SQLITE_OK ){
126427    int rc;                       /* Return code */
126428    char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
126429    sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
126430
126431    zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
126432    if( !zSql ){
126433      rc = SQLITE_NOMEM;
126434    }else{
126435      rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
126436      if( rc==SQLITE_OK ){
126437        sqlite3_step(pStmt);
126438        p->nPgsz = sqlite3_column_int(pStmt, 0);
126439        rc = sqlite3_finalize(pStmt);
126440      }else if( rc==SQLITE_AUTH ){
126441        p->nPgsz = 1024;
126442        rc = SQLITE_OK;
126443      }
126444    }
126445    assert( p->nPgsz>0 || rc!=SQLITE_OK );
126446    sqlite3_free(zSql);
126447    *pRc = rc;
126448  }
126449}
126450
126451/*
126452** "Special" FTS4 arguments are column specifications of the following form:
126453**
126454**   <key> = <value>
126455**
126456** There may not be whitespace surrounding the "=" character. The <value>
126457** term may be quoted, but the <key> may not.
126458*/
126459static int fts3IsSpecialColumn(
126460  const char *z,
126461  int *pnKey,
126462  char **pzValue
126463){
126464  char *zValue;
126465  const char *zCsr = z;
126466
126467  while( *zCsr!='=' ){
126468    if( *zCsr=='\0' ) return 0;
126469    zCsr++;
126470  }
126471
126472  *pnKey = (int)(zCsr-z);
126473  zValue = sqlite3_mprintf("%s", &zCsr[1]);
126474  if( zValue ){
126475    sqlite3Fts3Dequote(zValue);
126476  }
126477  *pzValue = zValue;
126478  return 1;
126479}
126480
126481/*
126482** Append the output of a printf() style formatting to an existing string.
126483*/
126484static void fts3Appendf(
126485  int *pRc,                       /* IN/OUT: Error code */
126486  char **pz,                      /* IN/OUT: Pointer to string buffer */
126487  const char *zFormat,            /* Printf format string to append */
126488  ...                             /* Arguments for printf format string */
126489){
126490  if( *pRc==SQLITE_OK ){
126491    va_list ap;
126492    char *z;
126493    va_start(ap, zFormat);
126494    z = sqlite3_vmprintf(zFormat, ap);
126495    va_end(ap);
126496    if( z && *pz ){
126497      char *z2 = sqlite3_mprintf("%s%s", *pz, z);
126498      sqlite3_free(z);
126499      z = z2;
126500    }
126501    if( z==0 ) *pRc = SQLITE_NOMEM;
126502    sqlite3_free(*pz);
126503    *pz = z;
126504  }
126505}
126506
126507/*
126508** Return a copy of input string zInput enclosed in double-quotes (") and
126509** with all double quote characters escaped. For example:
126510**
126511**     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
126512**
126513** The pointer returned points to memory obtained from sqlite3_malloc(). It
126514** is the callers responsibility to call sqlite3_free() to release this
126515** memory.
126516*/
126517static char *fts3QuoteId(char const *zInput){
126518  int nRet;
126519  char *zRet;
126520  nRet = 2 + (int)strlen(zInput)*2 + 1;
126521  zRet = sqlite3_malloc(nRet);
126522  if( zRet ){
126523    int i;
126524    char *z = zRet;
126525    *(z++) = '"';
126526    for(i=0; zInput[i]; i++){
126527      if( zInput[i]=='"' ) *(z++) = '"';
126528      *(z++) = zInput[i];
126529    }
126530    *(z++) = '"';
126531    *(z++) = '\0';
126532  }
126533  return zRet;
126534}
126535
126536/*
126537** Return a list of comma separated SQL expressions and a FROM clause that
126538** could be used in a SELECT statement such as the following:
126539**
126540**     SELECT <list of expressions> FROM %_content AS x ...
126541**
126542** to return the docid, followed by each column of text data in order
126543** from left to write. If parameter zFunc is not NULL, then instead of
126544** being returned directly each column of text data is passed to an SQL
126545** function named zFunc first. For example, if zFunc is "unzip" and the
126546** table has the three user-defined columns "a", "b", and "c", the following
126547** string is returned:
126548**
126549**     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
126550**
126551** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
126552** is the responsibility of the caller to eventually free it.
126553**
126554** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
126555** a NULL pointer is returned). Otherwise, if an OOM error is encountered
126556** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
126557** no error occurs, *pRc is left unmodified.
126558*/
126559static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
126560  char *zRet = 0;
126561  char *zFree = 0;
126562  char *zFunction;
126563  int i;
126564
126565  if( p->zContentTbl==0 ){
126566    if( !zFunc ){
126567      zFunction = "";
126568    }else{
126569      zFree = zFunction = fts3QuoteId(zFunc);
126570    }
126571    fts3Appendf(pRc, &zRet, "docid");
126572    for(i=0; i<p->nColumn; i++){
126573      fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
126574    }
126575    if( p->zLanguageid ){
126576      fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
126577    }
126578    sqlite3_free(zFree);
126579  }else{
126580    fts3Appendf(pRc, &zRet, "rowid");
126581    for(i=0; i<p->nColumn; i++){
126582      fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
126583    }
126584    if( p->zLanguageid ){
126585      fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
126586    }
126587  }
126588  fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
126589      p->zDb,
126590      (p->zContentTbl ? p->zContentTbl : p->zName),
126591      (p->zContentTbl ? "" : "_content")
126592  );
126593  return zRet;
126594}
126595
126596/*
126597** Return a list of N comma separated question marks, where N is the number
126598** of columns in the %_content table (one for the docid plus one for each
126599** user-defined text column).
126600**
126601** If argument zFunc is not NULL, then all but the first question mark
126602** is preceded by zFunc and an open bracket, and followed by a closed
126603** bracket. For example, if zFunc is "zip" and the FTS3 table has three
126604** user-defined text columns, the following string is returned:
126605**
126606**     "?, zip(?), zip(?), zip(?)"
126607**
126608** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
126609** is the responsibility of the caller to eventually free it.
126610**
126611** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
126612** a NULL pointer is returned). Otherwise, if an OOM error is encountered
126613** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
126614** no error occurs, *pRc is left unmodified.
126615*/
126616static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
126617  char *zRet = 0;
126618  char *zFree = 0;
126619  char *zFunction;
126620  int i;
126621
126622  if( !zFunc ){
126623    zFunction = "";
126624  }else{
126625    zFree = zFunction = fts3QuoteId(zFunc);
126626  }
126627  fts3Appendf(pRc, &zRet, "?");
126628  for(i=0; i<p->nColumn; i++){
126629    fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
126630  }
126631  if( p->zLanguageid ){
126632    fts3Appendf(pRc, &zRet, ", ?");
126633  }
126634  sqlite3_free(zFree);
126635  return zRet;
126636}
126637
126638/*
126639** This function interprets the string at (*pp) as a non-negative integer
126640** value. It reads the integer and sets *pnOut to the value read, then
126641** sets *pp to point to the byte immediately following the last byte of
126642** the integer value.
126643**
126644** Only decimal digits ('0'..'9') may be part of an integer value.
126645**
126646** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
126647** the output value undefined. Otherwise SQLITE_OK is returned.
126648**
126649** This function is used when parsing the "prefix=" FTS4 parameter.
126650*/
126651static int fts3GobbleInt(const char **pp, int *pnOut){
126652  const char *p;                  /* Iterator pointer */
126653  int nInt = 0;                   /* Output value */
126654
126655  for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
126656    nInt = nInt * 10 + (p[0] - '0');
126657  }
126658  if( p==*pp ) return SQLITE_ERROR;
126659  *pnOut = nInt;
126660  *pp = p;
126661  return SQLITE_OK;
126662}
126663
126664/*
126665** This function is called to allocate an array of Fts3Index structures
126666** representing the indexes maintained by the current FTS table. FTS tables
126667** always maintain the main "terms" index, but may also maintain one or
126668** more "prefix" indexes, depending on the value of the "prefix=" parameter
126669** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
126670**
126671** Argument zParam is passed the value of the "prefix=" option if one was
126672** specified, or NULL otherwise.
126673**
126674** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
126675** the allocated array. *pnIndex is set to the number of elements in the
126676** array. If an error does occur, an SQLite error code is returned.
126677**
126678** Regardless of whether or not an error is returned, it is the responsibility
126679** of the caller to call sqlite3_free() on the output array to free it.
126680*/
126681static int fts3PrefixParameter(
126682  const char *zParam,             /* ABC in prefix=ABC parameter to parse */
126683  int *pnIndex,                   /* OUT: size of *apIndex[] array */
126684  struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
126685){
126686  struct Fts3Index *aIndex;       /* Allocated array */
126687  int nIndex = 1;                 /* Number of entries in array */
126688
126689  if( zParam && zParam[0] ){
126690    const char *p;
126691    nIndex++;
126692    for(p=zParam; *p; p++){
126693      if( *p==',' ) nIndex++;
126694    }
126695  }
126696
126697  aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
126698  *apIndex = aIndex;
126699  *pnIndex = nIndex;
126700  if( !aIndex ){
126701    return SQLITE_NOMEM;
126702  }
126703
126704  memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
126705  if( zParam ){
126706    const char *p = zParam;
126707    int i;
126708    for(i=1; i<nIndex; i++){
126709      int nPrefix;
126710      if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
126711      aIndex[i].nPrefix = nPrefix;
126712      p++;
126713    }
126714  }
126715
126716  return SQLITE_OK;
126717}
126718
126719/*
126720** This function is called when initializing an FTS4 table that uses the
126721** content=xxx option. It determines the number of and names of the columns
126722** of the new FTS4 table.
126723**
126724** The third argument passed to this function is the value passed to the
126725** config=xxx option (i.e. "xxx"). This function queries the database for
126726** a table of that name. If found, the output variables are populated
126727** as follows:
126728**
126729**   *pnCol:   Set to the number of columns table xxx has,
126730**
126731**   *pnStr:   Set to the total amount of space required to store a copy
126732**             of each columns name, including the nul-terminator.
126733**
126734**   *pazCol:  Set to point to an array of *pnCol strings. Each string is
126735**             the name of the corresponding column in table xxx. The array
126736**             and its contents are allocated using a single allocation. It
126737**             is the responsibility of the caller to free this allocation
126738**             by eventually passing the *pazCol value to sqlite3_free().
126739**
126740** If the table cannot be found, an error code is returned and the output
126741** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
126742** returned (and the output variables are undefined).
126743*/
126744static int fts3ContentColumns(
126745  sqlite3 *db,                    /* Database handle */
126746  const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
126747  const char *zTbl,               /* Name of content table */
126748  const char ***pazCol,           /* OUT: Malloc'd array of column names */
126749  int *pnCol,                     /* OUT: Size of array *pazCol */
126750  int *pnStr                      /* OUT: Bytes of string content */
126751){
126752  int rc = SQLITE_OK;             /* Return code */
126753  char *zSql;                     /* "SELECT *" statement on zTbl */
126754  sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
126755
126756  zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
126757  if( !zSql ){
126758    rc = SQLITE_NOMEM;
126759  }else{
126760    rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
126761  }
126762  sqlite3_free(zSql);
126763
126764  if( rc==SQLITE_OK ){
126765    const char **azCol;           /* Output array */
126766    int nStr = 0;                 /* Size of all column names (incl. 0x00) */
126767    int nCol;                     /* Number of table columns */
126768    int i;                        /* Used to iterate through columns */
126769
126770    /* Loop through the returned columns. Set nStr to the number of bytes of
126771    ** space required to store a copy of each column name, including the
126772    ** nul-terminator byte.  */
126773    nCol = sqlite3_column_count(pStmt);
126774    for(i=0; i<nCol; i++){
126775      const char *zCol = sqlite3_column_name(pStmt, i);
126776      nStr += (int)strlen(zCol) + 1;
126777    }
126778
126779    /* Allocate and populate the array to return. */
126780    azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
126781    if( azCol==0 ){
126782      rc = SQLITE_NOMEM;
126783    }else{
126784      char *p = (char *)&azCol[nCol];
126785      for(i=0; i<nCol; i++){
126786        const char *zCol = sqlite3_column_name(pStmt, i);
126787        int n = (int)strlen(zCol)+1;
126788        memcpy(p, zCol, n);
126789        azCol[i] = p;
126790        p += n;
126791      }
126792    }
126793    sqlite3_finalize(pStmt);
126794
126795    /* Set the output variables. */
126796    *pnCol = nCol;
126797    *pnStr = nStr;
126798    *pazCol = azCol;
126799  }
126800
126801  return rc;
126802}
126803
126804/*
126805** This function is the implementation of both the xConnect and xCreate
126806** methods of the FTS3 virtual table.
126807**
126808** The argv[] array contains the following:
126809**
126810**   argv[0]   -> module name  ("fts3" or "fts4")
126811**   argv[1]   -> database name
126812**   argv[2]   -> table name
126813**   argv[...] -> "column name" and other module argument fields.
126814*/
126815static int fts3InitVtab(
126816  int isCreate,                   /* True for xCreate, false for xConnect */
126817  sqlite3 *db,                    /* The SQLite database connection */
126818  void *pAux,                     /* Hash table containing tokenizers */
126819  int argc,                       /* Number of elements in argv array */
126820  const char * const *argv,       /* xCreate/xConnect argument array */
126821  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
126822  char **pzErr                    /* Write any error message here */
126823){
126824  Fts3Hash *pHash = (Fts3Hash *)pAux;
126825  Fts3Table *p = 0;               /* Pointer to allocated vtab */
126826  int rc = SQLITE_OK;             /* Return code */
126827  int i;                          /* Iterator variable */
126828  int nByte;                      /* Size of allocation used for *p */
126829  int iCol;                       /* Column index */
126830  int nString = 0;                /* Bytes required to hold all column names */
126831  int nCol = 0;                   /* Number of columns in the FTS table */
126832  char *zCsr;                     /* Space for holding column names */
126833  int nDb;                        /* Bytes required to hold database name */
126834  int nName;                      /* Bytes required to hold table name */
126835  int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
126836  const char **aCol;              /* Array of column names */
126837  sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
126838
126839  int nIndex;                     /* Size of aIndex[] array */
126840  struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
126841
126842  /* The results of parsing supported FTS4 key=value options: */
126843  int bNoDocsize = 0;             /* True to omit %_docsize table */
126844  int bDescIdx = 0;               /* True to store descending indexes */
126845  char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
126846  char *zCompress = 0;            /* compress=? parameter (or NULL) */
126847  char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
126848  char *zContent = 0;             /* content=? parameter (or NULL) */
126849  char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */
126850  char **azNotindexed = 0;        /* The set of notindexed= columns */
126851  int nNotindexed = 0;            /* Size of azNotindexed[] array */
126852
126853  assert( strlen(argv[0])==4 );
126854  assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
126855       || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
126856  );
126857
126858  nDb = (int)strlen(argv[1]) + 1;
126859  nName = (int)strlen(argv[2]) + 1;
126860
126861  nByte = sizeof(const char *) * (argc-2);
126862  aCol = (const char **)sqlite3_malloc(nByte);
126863  if( aCol ){
126864    memset((void*)aCol, 0, nByte);
126865    azNotindexed = (char **)sqlite3_malloc(nByte);
126866  }
126867  if( azNotindexed ){
126868    memset(azNotindexed, 0, nByte);
126869  }
126870  if( !aCol || !azNotindexed ){
126871    rc = SQLITE_NOMEM;
126872    goto fts3_init_out;
126873  }
126874
126875  /* Loop through all of the arguments passed by the user to the FTS3/4
126876  ** module (i.e. all the column names and special arguments). This loop
126877  ** does the following:
126878  **
126879  **   + Figures out the number of columns the FTSX table will have, and
126880  **     the number of bytes of space that must be allocated to store copies
126881  **     of the column names.
126882  **
126883  **   + If there is a tokenizer specification included in the arguments,
126884  **     initializes the tokenizer pTokenizer.
126885  */
126886  for(i=3; rc==SQLITE_OK && i<argc; i++){
126887    char const *z = argv[i];
126888    int nKey;
126889    char *zVal;
126890
126891    /* Check if this is a tokenizer specification */
126892    if( !pTokenizer
126893     && strlen(z)>8
126894     && 0==sqlite3_strnicmp(z, "tokenize", 8)
126895     && 0==sqlite3Fts3IsIdChar(z[8])
126896    ){
126897      rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
126898    }
126899
126900    /* Check if it is an FTS4 special argument. */
126901    else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
126902      struct Fts4Option {
126903        const char *zOpt;
126904        int nOpt;
126905      } aFts4Opt[] = {
126906        { "matchinfo",   9 },     /* 0 -> MATCHINFO */
126907        { "prefix",      6 },     /* 1 -> PREFIX */
126908        { "compress",    8 },     /* 2 -> COMPRESS */
126909        { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
126910        { "order",       5 },     /* 4 -> ORDER */
126911        { "content",     7 },     /* 5 -> CONTENT */
126912        { "languageid", 10 },     /* 6 -> LANGUAGEID */
126913        { "notindexed", 10 }      /* 7 -> NOTINDEXED */
126914      };
126915
126916      int iOpt;
126917      if( !zVal ){
126918        rc = SQLITE_NOMEM;
126919      }else{
126920        for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
126921          struct Fts4Option *pOp = &aFts4Opt[iOpt];
126922          if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
126923            break;
126924          }
126925        }
126926        if( iOpt==SizeofArray(aFts4Opt) ){
126927          *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
126928          rc = SQLITE_ERROR;
126929        }else{
126930          switch( iOpt ){
126931            case 0:               /* MATCHINFO */
126932              if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
126933                *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
126934                rc = SQLITE_ERROR;
126935              }
126936              bNoDocsize = 1;
126937              break;
126938
126939            case 1:               /* PREFIX */
126940              sqlite3_free(zPrefix);
126941              zPrefix = zVal;
126942              zVal = 0;
126943              break;
126944
126945            case 2:               /* COMPRESS */
126946              sqlite3_free(zCompress);
126947              zCompress = zVal;
126948              zVal = 0;
126949              break;
126950
126951            case 3:               /* UNCOMPRESS */
126952              sqlite3_free(zUncompress);
126953              zUncompress = zVal;
126954              zVal = 0;
126955              break;
126956
126957            case 4:               /* ORDER */
126958              if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
126959               && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
126960              ){
126961                *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
126962                rc = SQLITE_ERROR;
126963              }
126964              bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
126965              break;
126966
126967            case 5:              /* CONTENT */
126968              sqlite3_free(zContent);
126969              zContent = zVal;
126970              zVal = 0;
126971              break;
126972
126973            case 6:              /* LANGUAGEID */
126974              assert( iOpt==6 );
126975              sqlite3_free(zLanguageid);
126976              zLanguageid = zVal;
126977              zVal = 0;
126978              break;
126979
126980            case 7:              /* NOTINDEXED */
126981              azNotindexed[nNotindexed++] = zVal;
126982              zVal = 0;
126983              break;
126984          }
126985        }
126986        sqlite3_free(zVal);
126987      }
126988    }
126989
126990    /* Otherwise, the argument is a column name. */
126991    else {
126992      nString += (int)(strlen(z) + 1);
126993      aCol[nCol++] = z;
126994    }
126995  }
126996
126997  /* If a content=xxx option was specified, the following:
126998  **
126999  **   1. Ignore any compress= and uncompress= options.
127000  **
127001  **   2. If no column names were specified as part of the CREATE VIRTUAL
127002  **      TABLE statement, use all columns from the content table.
127003  */
127004  if( rc==SQLITE_OK && zContent ){
127005    sqlite3_free(zCompress);
127006    sqlite3_free(zUncompress);
127007    zCompress = 0;
127008    zUncompress = 0;
127009    if( nCol==0 ){
127010      sqlite3_free((void*)aCol);
127011      aCol = 0;
127012      rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
127013
127014      /* If a languageid= option was specified, remove the language id
127015      ** column from the aCol[] array. */
127016      if( rc==SQLITE_OK && zLanguageid ){
127017        int j;
127018        for(j=0; j<nCol; j++){
127019          if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
127020            int k;
127021            for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
127022            nCol--;
127023            break;
127024          }
127025        }
127026      }
127027    }
127028  }
127029  if( rc!=SQLITE_OK ) goto fts3_init_out;
127030
127031  if( nCol==0 ){
127032    assert( nString==0 );
127033    aCol[0] = "content";
127034    nString = 8;
127035    nCol = 1;
127036  }
127037
127038  if( pTokenizer==0 ){
127039    rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
127040    if( rc!=SQLITE_OK ) goto fts3_init_out;
127041  }
127042  assert( pTokenizer );
127043
127044  rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
127045  if( rc==SQLITE_ERROR ){
127046    assert( zPrefix );
127047    *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
127048  }
127049  if( rc!=SQLITE_OK ) goto fts3_init_out;
127050
127051  /* Allocate and populate the Fts3Table structure. */
127052  nByte = sizeof(Fts3Table) +                  /* Fts3Table */
127053          nCol * sizeof(char *) +              /* azColumn */
127054          nIndex * sizeof(struct Fts3Index) +  /* aIndex */
127055          nCol * sizeof(u8) +                  /* abNotindexed */
127056          nName +                              /* zName */
127057          nDb +                                /* zDb */
127058          nString;                             /* Space for azColumn strings */
127059  p = (Fts3Table*)sqlite3_malloc(nByte);
127060  if( p==0 ){
127061    rc = SQLITE_NOMEM;
127062    goto fts3_init_out;
127063  }
127064  memset(p, 0, nByte);
127065  p->db = db;
127066  p->nColumn = nCol;
127067  p->nPendingData = 0;
127068  p->azColumn = (char **)&p[1];
127069  p->pTokenizer = pTokenizer;
127070  p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
127071  p->bHasDocsize = (isFts4 && bNoDocsize==0);
127072  p->bHasStat = isFts4;
127073  p->bFts4 = isFts4;
127074  p->bDescIdx = bDescIdx;
127075  p->nAutoincrmerge = 0xff;   /* 0xff means setting unknown */
127076  p->zContentTbl = zContent;
127077  p->zLanguageid = zLanguageid;
127078  zContent = 0;
127079  zLanguageid = 0;
127080  TESTONLY( p->inTransaction = -1 );
127081  TESTONLY( p->mxSavepoint = -1 );
127082
127083  p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
127084  memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
127085  p->nIndex = nIndex;
127086  for(i=0; i<nIndex; i++){
127087    fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
127088  }
127089  p->abNotindexed = (u8 *)&p->aIndex[nIndex];
127090
127091  /* Fill in the zName and zDb fields of the vtab structure. */
127092  zCsr = (char *)&p->abNotindexed[nCol];
127093  p->zName = zCsr;
127094  memcpy(zCsr, argv[2], nName);
127095  zCsr += nName;
127096  p->zDb = zCsr;
127097  memcpy(zCsr, argv[1], nDb);
127098  zCsr += nDb;
127099
127100  /* Fill in the azColumn array */
127101  for(iCol=0; iCol<nCol; iCol++){
127102    char *z;
127103    int n = 0;
127104    z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
127105    memcpy(zCsr, z, n);
127106    zCsr[n] = '\0';
127107    sqlite3Fts3Dequote(zCsr);
127108    p->azColumn[iCol] = zCsr;
127109    zCsr += n+1;
127110    assert( zCsr <= &((char *)p)[nByte] );
127111  }
127112
127113  /* Fill in the abNotindexed array */
127114  for(iCol=0; iCol<nCol; iCol++){
127115    int n = (int)strlen(p->azColumn[iCol]);
127116    for(i=0; i<nNotindexed; i++){
127117      char *zNot = azNotindexed[i];
127118      if( zNot && n==(int)strlen(zNot)
127119       && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
127120      ){
127121        p->abNotindexed[iCol] = 1;
127122        sqlite3_free(zNot);
127123        azNotindexed[i] = 0;
127124      }
127125    }
127126  }
127127  for(i=0; i<nNotindexed; i++){
127128    if( azNotindexed[i] ){
127129      *pzErr = sqlite3_mprintf("no such column: %s", azNotindexed[i]);
127130      rc = SQLITE_ERROR;
127131    }
127132  }
127133
127134  if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
127135    char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
127136    rc = SQLITE_ERROR;
127137    *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
127138  }
127139  p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
127140  p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
127141  if( rc!=SQLITE_OK ) goto fts3_init_out;
127142
127143  /* If this is an xCreate call, create the underlying tables in the
127144  ** database. TODO: For xConnect(), it could verify that said tables exist.
127145  */
127146  if( isCreate ){
127147    rc = fts3CreateTables(p);
127148  }
127149
127150  /* Check to see if a legacy fts3 table has been "upgraded" by the
127151  ** addition of a %_stat table so that it can use incremental merge.
127152  */
127153  if( !isFts4 && !isCreate ){
127154    p->bHasStat = 2;
127155  }
127156
127157  /* Figure out the page-size for the database. This is required in order to
127158  ** estimate the cost of loading large doclists from the database.  */
127159  fts3DatabasePageSize(&rc, p);
127160  p->nNodeSize = p->nPgsz-35;
127161
127162  /* Declare the table schema to SQLite. */
127163  fts3DeclareVtab(&rc, p);
127164
127165fts3_init_out:
127166  sqlite3_free(zPrefix);
127167  sqlite3_free(aIndex);
127168  sqlite3_free(zCompress);
127169  sqlite3_free(zUncompress);
127170  sqlite3_free(zContent);
127171  sqlite3_free(zLanguageid);
127172  for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
127173  sqlite3_free((void *)aCol);
127174  sqlite3_free((void *)azNotindexed);
127175  if( rc!=SQLITE_OK ){
127176    if( p ){
127177      fts3DisconnectMethod((sqlite3_vtab *)p);
127178    }else if( pTokenizer ){
127179      pTokenizer->pModule->xDestroy(pTokenizer);
127180    }
127181  }else{
127182    assert( p->pSegments==0 );
127183    *ppVTab = &p->base;
127184  }
127185  return rc;
127186}
127187
127188/*
127189** The xConnect() and xCreate() methods for the virtual table. All the
127190** work is done in function fts3InitVtab().
127191*/
127192static int fts3ConnectMethod(
127193  sqlite3 *db,                    /* Database connection */
127194  void *pAux,                     /* Pointer to tokenizer hash table */
127195  int argc,                       /* Number of elements in argv array */
127196  const char * const *argv,       /* xCreate/xConnect argument array */
127197  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
127198  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
127199){
127200  return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
127201}
127202static int fts3CreateMethod(
127203  sqlite3 *db,                    /* Database connection */
127204  void *pAux,                     /* Pointer to tokenizer hash table */
127205  int argc,                       /* Number of elements in argv array */
127206  const char * const *argv,       /* xCreate/xConnect argument array */
127207  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
127208  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
127209){
127210  return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
127211}
127212
127213/*
127214** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
127215** extension is currently being used by a version of SQLite too old to
127216** support estimatedRows. In that case this function is a no-op.
127217*/
127218static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
127219#if SQLITE_VERSION_NUMBER>=3008002
127220  if( sqlite3_libversion_number()>=3008002 ){
127221    pIdxInfo->estimatedRows = nRow;
127222  }
127223#endif
127224}
127225
127226/*
127227** Implementation of the xBestIndex method for FTS3 tables. There
127228** are three possible strategies, in order of preference:
127229**
127230**   1. Direct lookup by rowid or docid.
127231**   2. Full-text search using a MATCH operator on a non-docid column.
127232**   3. Linear scan of %_content table.
127233*/
127234static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
127235  Fts3Table *p = (Fts3Table *)pVTab;
127236  int i;                          /* Iterator variable */
127237  int iCons = -1;                 /* Index of constraint to use */
127238
127239  int iLangidCons = -1;           /* Index of langid=x constraint, if present */
127240  int iDocidGe = -1;              /* Index of docid>=x constraint, if present */
127241  int iDocidLe = -1;              /* Index of docid<=x constraint, if present */
127242  int iIdx;
127243
127244  /* By default use a full table scan. This is an expensive option,
127245  ** so search through the constraints to see if a more efficient
127246  ** strategy is possible.
127247  */
127248  pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
127249  pInfo->estimatedCost = 5000000;
127250  for(i=0; i<pInfo->nConstraint; i++){
127251    int bDocid;                 /* True if this constraint is on docid */
127252    struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
127253    if( pCons->usable==0 ){
127254      if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
127255        /* There exists an unusable MATCH constraint. This means that if
127256        ** the planner does elect to use the results of this call as part
127257        ** of the overall query plan the user will see an "unable to use
127258        ** function MATCH in the requested context" error. To discourage
127259        ** this, return a very high cost here.  */
127260        pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
127261        pInfo->estimatedCost = 1e50;
127262        fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
127263        return SQLITE_OK;
127264      }
127265      continue;
127266    }
127267
127268    bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
127269
127270    /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
127271    if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
127272      pInfo->idxNum = FTS3_DOCID_SEARCH;
127273      pInfo->estimatedCost = 1.0;
127274      iCons = i;
127275    }
127276
127277    /* A MATCH constraint. Use a full-text search.
127278    **
127279    ** If there is more than one MATCH constraint available, use the first
127280    ** one encountered. If there is both a MATCH constraint and a direct
127281    ** rowid/docid lookup, prefer the MATCH strategy. This is done even
127282    ** though the rowid/docid lookup is faster than a MATCH query, selecting
127283    ** it would lead to an "unable to use function MATCH in the requested
127284    ** context" error.
127285    */
127286    if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
127287     && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
127288    ){
127289      pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
127290      pInfo->estimatedCost = 2.0;
127291      iCons = i;
127292    }
127293
127294    /* Equality constraint on the langid column */
127295    if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
127296     && pCons->iColumn==p->nColumn + 2
127297    ){
127298      iLangidCons = i;
127299    }
127300
127301    if( bDocid ){
127302      switch( pCons->op ){
127303        case SQLITE_INDEX_CONSTRAINT_GE:
127304        case SQLITE_INDEX_CONSTRAINT_GT:
127305          iDocidGe = i;
127306          break;
127307
127308        case SQLITE_INDEX_CONSTRAINT_LE:
127309        case SQLITE_INDEX_CONSTRAINT_LT:
127310          iDocidLe = i;
127311          break;
127312      }
127313    }
127314  }
127315
127316  iIdx = 1;
127317  if( iCons>=0 ){
127318    pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
127319    pInfo->aConstraintUsage[iCons].omit = 1;
127320  }
127321  if( iLangidCons>=0 ){
127322    pInfo->idxNum |= FTS3_HAVE_LANGID;
127323    pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
127324  }
127325  if( iDocidGe>=0 ){
127326    pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
127327    pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
127328  }
127329  if( iDocidLe>=0 ){
127330    pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
127331    pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
127332  }
127333
127334  /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
127335  ** docid) order. Both ascending and descending are possible.
127336  */
127337  if( pInfo->nOrderBy==1 ){
127338    struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
127339    if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
127340      if( pOrder->desc ){
127341        pInfo->idxStr = "DESC";
127342      }else{
127343        pInfo->idxStr = "ASC";
127344      }
127345      pInfo->orderByConsumed = 1;
127346    }
127347  }
127348
127349  assert( p->pSegments==0 );
127350  return SQLITE_OK;
127351}
127352
127353/*
127354** Implementation of xOpen method.
127355*/
127356static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
127357  sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
127358
127359  UNUSED_PARAMETER(pVTab);
127360
127361  /* Allocate a buffer large enough for an Fts3Cursor structure. If the
127362  ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
127363  ** if the allocation fails, return SQLITE_NOMEM.
127364  */
127365  *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
127366  if( !pCsr ){
127367    return SQLITE_NOMEM;
127368  }
127369  memset(pCsr, 0, sizeof(Fts3Cursor));
127370  return SQLITE_OK;
127371}
127372
127373/*
127374** Close the cursor.  For additional information see the documentation
127375** on the xClose method of the virtual table interface.
127376*/
127377static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
127378  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
127379  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
127380  sqlite3_finalize(pCsr->pStmt);
127381  sqlite3Fts3ExprFree(pCsr->pExpr);
127382  sqlite3Fts3FreeDeferredTokens(pCsr);
127383  sqlite3_free(pCsr->aDoclist);
127384  sqlite3_free(pCsr->aMatchinfo);
127385  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
127386  sqlite3_free(pCsr);
127387  return SQLITE_OK;
127388}
127389
127390/*
127391** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
127392** compose and prepare an SQL statement of the form:
127393**
127394**    "SELECT <columns> FROM %_content WHERE rowid = ?"
127395**
127396** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
127397** it. If an error occurs, return an SQLite error code.
127398**
127399** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
127400*/
127401static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
127402  int rc = SQLITE_OK;
127403  if( pCsr->pStmt==0 ){
127404    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
127405    char *zSql;
127406    zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
127407    if( !zSql ) return SQLITE_NOMEM;
127408    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
127409    sqlite3_free(zSql);
127410  }
127411  *ppStmt = pCsr->pStmt;
127412  return rc;
127413}
127414
127415/*
127416** Position the pCsr->pStmt statement so that it is on the row
127417** of the %_content table that contains the last match.  Return
127418** SQLITE_OK on success.
127419*/
127420static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
127421  int rc = SQLITE_OK;
127422  if( pCsr->isRequireSeek ){
127423    sqlite3_stmt *pStmt = 0;
127424
127425    rc = fts3CursorSeekStmt(pCsr, &pStmt);
127426    if( rc==SQLITE_OK ){
127427      sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
127428      pCsr->isRequireSeek = 0;
127429      if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
127430        return SQLITE_OK;
127431      }else{
127432        rc = sqlite3_reset(pCsr->pStmt);
127433        if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
127434          /* If no row was found and no error has occurred, then the %_content
127435          ** table is missing a row that is present in the full-text index.
127436          ** The data structures are corrupt.  */
127437          rc = FTS_CORRUPT_VTAB;
127438          pCsr->isEof = 1;
127439        }
127440      }
127441    }
127442  }
127443
127444  if( rc!=SQLITE_OK && pContext ){
127445    sqlite3_result_error_code(pContext, rc);
127446  }
127447  return rc;
127448}
127449
127450/*
127451** This function is used to process a single interior node when searching
127452** a b-tree for a term or term prefix. The node data is passed to this
127453** function via the zNode/nNode parameters. The term to search for is
127454** passed in zTerm/nTerm.
127455**
127456** If piFirst is not NULL, then this function sets *piFirst to the blockid
127457** of the child node that heads the sub-tree that may contain the term.
127458**
127459** If piLast is not NULL, then *piLast is set to the right-most child node
127460** that heads a sub-tree that may contain a term for which zTerm/nTerm is
127461** a prefix.
127462**
127463** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
127464*/
127465static int fts3ScanInteriorNode(
127466  const char *zTerm,              /* Term to select leaves for */
127467  int nTerm,                      /* Size of term zTerm in bytes */
127468  const char *zNode,              /* Buffer containing segment interior node */
127469  int nNode,                      /* Size of buffer at zNode */
127470  sqlite3_int64 *piFirst,         /* OUT: Selected child node */
127471  sqlite3_int64 *piLast           /* OUT: Selected child node */
127472){
127473  int rc = SQLITE_OK;             /* Return code */
127474  const char *zCsr = zNode;       /* Cursor to iterate through node */
127475  const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
127476  char *zBuffer = 0;              /* Buffer to load terms into */
127477  int nAlloc = 0;                 /* Size of allocated buffer */
127478  int isFirstTerm = 1;            /* True when processing first term on page */
127479  sqlite3_int64 iChild;           /* Block id of child node to descend to */
127480
127481  /* Skip over the 'height' varint that occurs at the start of every
127482  ** interior node. Then load the blockid of the left-child of the b-tree
127483  ** node into variable iChild.
127484  **
127485  ** Even if the data structure on disk is corrupted, this (reading two
127486  ** varints from the buffer) does not risk an overread. If zNode is a
127487  ** root node, then the buffer comes from a SELECT statement. SQLite does
127488  ** not make this guarantee explicitly, but in practice there are always
127489  ** either more than 20 bytes of allocated space following the nNode bytes of
127490  ** contents, or two zero bytes. Or, if the node is read from the %_segments
127491  ** table, then there are always 20 bytes of zeroed padding following the
127492  ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
127493  */
127494  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
127495  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
127496  if( zCsr>zEnd ){
127497    return FTS_CORRUPT_VTAB;
127498  }
127499
127500  while( zCsr<zEnd && (piFirst || piLast) ){
127501    int cmp;                      /* memcmp() result */
127502    int nSuffix;                  /* Size of term suffix */
127503    int nPrefix = 0;              /* Size of term prefix */
127504    int nBuffer;                  /* Total term size */
127505
127506    /* Load the next term on the node into zBuffer. Use realloc() to expand
127507    ** the size of zBuffer if required.  */
127508    if( !isFirstTerm ){
127509      zCsr += fts3GetVarint32(zCsr, &nPrefix);
127510    }
127511    isFirstTerm = 0;
127512    zCsr += fts3GetVarint32(zCsr, &nSuffix);
127513
127514    if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
127515      rc = FTS_CORRUPT_VTAB;
127516      goto finish_scan;
127517    }
127518    if( nPrefix+nSuffix>nAlloc ){
127519      char *zNew;
127520      nAlloc = (nPrefix+nSuffix) * 2;
127521      zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
127522      if( !zNew ){
127523        rc = SQLITE_NOMEM;
127524        goto finish_scan;
127525      }
127526      zBuffer = zNew;
127527    }
127528    assert( zBuffer );
127529    memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
127530    nBuffer = nPrefix + nSuffix;
127531    zCsr += nSuffix;
127532
127533    /* Compare the term we are searching for with the term just loaded from
127534    ** the interior node. If the specified term is greater than or equal
127535    ** to the term from the interior node, then all terms on the sub-tree
127536    ** headed by node iChild are smaller than zTerm. No need to search
127537    ** iChild.
127538    **
127539    ** If the interior node term is larger than the specified term, then
127540    ** the tree headed by iChild may contain the specified term.
127541    */
127542    cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
127543    if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
127544      *piFirst = iChild;
127545      piFirst = 0;
127546    }
127547
127548    if( piLast && cmp<0 ){
127549      *piLast = iChild;
127550      piLast = 0;
127551    }
127552
127553    iChild++;
127554  };
127555
127556  if( piFirst ) *piFirst = iChild;
127557  if( piLast ) *piLast = iChild;
127558
127559 finish_scan:
127560  sqlite3_free(zBuffer);
127561  return rc;
127562}
127563
127564
127565/*
127566** The buffer pointed to by argument zNode (size nNode bytes) contains an
127567** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
127568** contains a term. This function searches the sub-tree headed by the zNode
127569** node for the range of leaf nodes that may contain the specified term
127570** or terms for which the specified term is a prefix.
127571**
127572** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
127573** left-most leaf node in the tree that may contain the specified term.
127574** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
127575** right-most leaf node that may contain a term for which the specified
127576** term is a prefix.
127577**
127578** It is possible that the range of returned leaf nodes does not contain
127579** the specified term or any terms for which it is a prefix. However, if the
127580** segment does contain any such terms, they are stored within the identified
127581** range. Because this function only inspects interior segment nodes (and
127582** never loads leaf nodes into memory), it is not possible to be sure.
127583**
127584** If an error occurs, an error code other than SQLITE_OK is returned.
127585*/
127586static int fts3SelectLeaf(
127587  Fts3Table *p,                   /* Virtual table handle */
127588  const char *zTerm,              /* Term to select leaves for */
127589  int nTerm,                      /* Size of term zTerm in bytes */
127590  const char *zNode,              /* Buffer containing segment interior node */
127591  int nNode,                      /* Size of buffer at zNode */
127592  sqlite3_int64 *piLeaf,          /* Selected leaf node */
127593  sqlite3_int64 *piLeaf2          /* Selected leaf node */
127594){
127595  int rc;                         /* Return code */
127596  int iHeight;                    /* Height of this node in tree */
127597
127598  assert( piLeaf || piLeaf2 );
127599
127600  fts3GetVarint32(zNode, &iHeight);
127601  rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
127602  assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
127603
127604  if( rc==SQLITE_OK && iHeight>1 ){
127605    char *zBlob = 0;              /* Blob read from %_segments table */
127606    int nBlob;                    /* Size of zBlob in bytes */
127607
127608    if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
127609      rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
127610      if( rc==SQLITE_OK ){
127611        rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
127612      }
127613      sqlite3_free(zBlob);
127614      piLeaf = 0;
127615      zBlob = 0;
127616    }
127617
127618    if( rc==SQLITE_OK ){
127619      rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
127620    }
127621    if( rc==SQLITE_OK ){
127622      rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
127623    }
127624    sqlite3_free(zBlob);
127625  }
127626
127627  return rc;
127628}
127629
127630/*
127631** This function is used to create delta-encoded serialized lists of FTS3
127632** varints. Each call to this function appends a single varint to a list.
127633*/
127634static void fts3PutDeltaVarint(
127635  char **pp,                      /* IN/OUT: Output pointer */
127636  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
127637  sqlite3_int64 iVal              /* Write this value to the list */
127638){
127639  assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
127640  *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
127641  *piPrev = iVal;
127642}
127643
127644/*
127645** When this function is called, *ppPoslist is assumed to point to the
127646** start of a position-list. After it returns, *ppPoslist points to the
127647** first byte after the position-list.
127648**
127649** A position list is list of positions (delta encoded) and columns for
127650** a single document record of a doclist.  So, in other words, this
127651** routine advances *ppPoslist so that it points to the next docid in
127652** the doclist, or to the first byte past the end of the doclist.
127653**
127654** If pp is not NULL, then the contents of the position list are copied
127655** to *pp. *pp is set to point to the first byte past the last byte copied
127656** before this function returns.
127657*/
127658static void fts3PoslistCopy(char **pp, char **ppPoslist){
127659  char *pEnd = *ppPoslist;
127660  char c = 0;
127661
127662  /* The end of a position list is marked by a zero encoded as an FTS3
127663  ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
127664  ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
127665  ** of some other, multi-byte, value.
127666  **
127667  ** The following while-loop moves pEnd to point to the first byte that is not
127668  ** immediately preceded by a byte with the 0x80 bit set. Then increments
127669  ** pEnd once more so that it points to the byte immediately following the
127670  ** last byte in the position-list.
127671  */
127672  while( *pEnd | c ){
127673    c = *pEnd++ & 0x80;
127674    testcase( c!=0 && (*pEnd)==0 );
127675  }
127676  pEnd++;  /* Advance past the POS_END terminator byte */
127677
127678  if( pp ){
127679    int n = (int)(pEnd - *ppPoslist);
127680    char *p = *pp;
127681    memcpy(p, *ppPoslist, n);
127682    p += n;
127683    *pp = p;
127684  }
127685  *ppPoslist = pEnd;
127686}
127687
127688/*
127689** When this function is called, *ppPoslist is assumed to point to the
127690** start of a column-list. After it returns, *ppPoslist points to the
127691** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
127692**
127693** A column-list is list of delta-encoded positions for a single column
127694** within a single document within a doclist.
127695**
127696** The column-list is terminated either by a POS_COLUMN varint (1) or
127697** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
127698** the POS_COLUMN or POS_END that terminates the column-list.
127699**
127700** If pp is not NULL, then the contents of the column-list are copied
127701** to *pp. *pp is set to point to the first byte past the last byte copied
127702** before this function returns.  The POS_COLUMN or POS_END terminator
127703** is not copied into *pp.
127704*/
127705static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
127706  char *pEnd = *ppPoslist;
127707  char c = 0;
127708
127709  /* A column-list is terminated by either a 0x01 or 0x00 byte that is
127710  ** not part of a multi-byte varint.
127711  */
127712  while( 0xFE & (*pEnd | c) ){
127713    c = *pEnd++ & 0x80;
127714    testcase( c!=0 && ((*pEnd)&0xfe)==0 );
127715  }
127716  if( pp ){
127717    int n = (int)(pEnd - *ppPoslist);
127718    char *p = *pp;
127719    memcpy(p, *ppPoslist, n);
127720    p += n;
127721    *pp = p;
127722  }
127723  *ppPoslist = pEnd;
127724}
127725
127726/*
127727** Value used to signify the end of an position-list. This is safe because
127728** it is not possible to have a document with 2^31 terms.
127729*/
127730#define POSITION_LIST_END 0x7fffffff
127731
127732/*
127733** This function is used to help parse position-lists. When this function is
127734** called, *pp may point to the start of the next varint in the position-list
127735** being parsed, or it may point to 1 byte past the end of the position-list
127736** (in which case **pp will be a terminator bytes POS_END (0) or
127737** (1)).
127738**
127739** If *pp points past the end of the current position-list, set *pi to
127740** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
127741** increment the current value of *pi by the value read, and set *pp to
127742** point to the next value before returning.
127743**
127744** Before calling this routine *pi must be initialized to the value of
127745** the previous position, or zero if we are reading the first position
127746** in the position-list.  Because positions are delta-encoded, the value
127747** of the previous position is needed in order to compute the value of
127748** the next position.
127749*/
127750static void fts3ReadNextPos(
127751  char **pp,                    /* IN/OUT: Pointer into position-list buffer */
127752  sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
127753){
127754  if( (**pp)&0xFE ){
127755    fts3GetDeltaVarint(pp, pi);
127756    *pi -= 2;
127757  }else{
127758    *pi = POSITION_LIST_END;
127759  }
127760}
127761
127762/*
127763** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
127764** the value of iCol encoded as a varint to *pp.   This will start a new
127765** column list.
127766**
127767** Set *pp to point to the byte just after the last byte written before
127768** returning (do not modify it if iCol==0). Return the total number of bytes
127769** written (0 if iCol==0).
127770*/
127771static int fts3PutColNumber(char **pp, int iCol){
127772  int n = 0;                      /* Number of bytes written */
127773  if( iCol ){
127774    char *p = *pp;                /* Output pointer */
127775    n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
127776    *p = 0x01;
127777    *pp = &p[n];
127778  }
127779  return n;
127780}
127781
127782/*
127783** Compute the union of two position lists.  The output written
127784** into *pp contains all positions of both *pp1 and *pp2 in sorted
127785** order and with any duplicates removed.  All pointers are
127786** updated appropriately.   The caller is responsible for insuring
127787** that there is enough space in *pp to hold the complete output.
127788*/
127789static void fts3PoslistMerge(
127790  char **pp,                      /* Output buffer */
127791  char **pp1,                     /* Left input list */
127792  char **pp2                      /* Right input list */
127793){
127794  char *p = *pp;
127795  char *p1 = *pp1;
127796  char *p2 = *pp2;
127797
127798  while( *p1 || *p2 ){
127799    int iCol1;         /* The current column index in pp1 */
127800    int iCol2;         /* The current column index in pp2 */
127801
127802    if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
127803    else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
127804    else iCol1 = 0;
127805
127806    if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
127807    else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
127808    else iCol2 = 0;
127809
127810    if( iCol1==iCol2 ){
127811      sqlite3_int64 i1 = 0;       /* Last position from pp1 */
127812      sqlite3_int64 i2 = 0;       /* Last position from pp2 */
127813      sqlite3_int64 iPrev = 0;
127814      int n = fts3PutColNumber(&p, iCol1);
127815      p1 += n;
127816      p2 += n;
127817
127818      /* At this point, both p1 and p2 point to the start of column-lists
127819      ** for the same column (the column with index iCol1 and iCol2).
127820      ** A column-list is a list of non-negative delta-encoded varints, each
127821      ** incremented by 2 before being stored. Each list is terminated by a
127822      ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
127823      ** and writes the results to buffer p. p is left pointing to the byte
127824      ** after the list written. No terminator (POS_END or POS_COLUMN) is
127825      ** written to the output.
127826      */
127827      fts3GetDeltaVarint(&p1, &i1);
127828      fts3GetDeltaVarint(&p2, &i2);
127829      do {
127830        fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
127831        iPrev -= 2;
127832        if( i1==i2 ){
127833          fts3ReadNextPos(&p1, &i1);
127834          fts3ReadNextPos(&p2, &i2);
127835        }else if( i1<i2 ){
127836          fts3ReadNextPos(&p1, &i1);
127837        }else{
127838          fts3ReadNextPos(&p2, &i2);
127839        }
127840      }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
127841    }else if( iCol1<iCol2 ){
127842      p1 += fts3PutColNumber(&p, iCol1);
127843      fts3ColumnlistCopy(&p, &p1);
127844    }else{
127845      p2 += fts3PutColNumber(&p, iCol2);
127846      fts3ColumnlistCopy(&p, &p2);
127847    }
127848  }
127849
127850  *p++ = POS_END;
127851  *pp = p;
127852  *pp1 = p1 + 1;
127853  *pp2 = p2 + 1;
127854}
127855
127856/*
127857** This function is used to merge two position lists into one. When it is
127858** called, *pp1 and *pp2 must both point to position lists. A position-list is
127859** the part of a doclist that follows each document id. For example, if a row
127860** contains:
127861**
127862**     'a b c'|'x y z'|'a b b a'
127863**
127864** Then the position list for this row for token 'b' would consist of:
127865**
127866**     0x02 0x01 0x02 0x03 0x03 0x00
127867**
127868** When this function returns, both *pp1 and *pp2 are left pointing to the
127869** byte following the 0x00 terminator of their respective position lists.
127870**
127871** If isSaveLeft is 0, an entry is added to the output position list for
127872** each position in *pp2 for which there exists one or more positions in
127873** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
127874** when the *pp1 token appears before the *pp2 token, but not more than nToken
127875** slots before it.
127876**
127877** e.g. nToken==1 searches for adjacent positions.
127878*/
127879static int fts3PoslistPhraseMerge(
127880  char **pp,                      /* IN/OUT: Preallocated output buffer */
127881  int nToken,                     /* Maximum difference in token positions */
127882  int isSaveLeft,                 /* Save the left position */
127883  int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
127884  char **pp1,                     /* IN/OUT: Left input list */
127885  char **pp2                      /* IN/OUT: Right input list */
127886){
127887  char *p = *pp;
127888  char *p1 = *pp1;
127889  char *p2 = *pp2;
127890  int iCol1 = 0;
127891  int iCol2 = 0;
127892
127893  /* Never set both isSaveLeft and isExact for the same invocation. */
127894  assert( isSaveLeft==0 || isExact==0 );
127895
127896  assert( p!=0 && *p1!=0 && *p2!=0 );
127897  if( *p1==POS_COLUMN ){
127898    p1++;
127899    p1 += fts3GetVarint32(p1, &iCol1);
127900  }
127901  if( *p2==POS_COLUMN ){
127902    p2++;
127903    p2 += fts3GetVarint32(p2, &iCol2);
127904  }
127905
127906  while( 1 ){
127907    if( iCol1==iCol2 ){
127908      char *pSave = p;
127909      sqlite3_int64 iPrev = 0;
127910      sqlite3_int64 iPos1 = 0;
127911      sqlite3_int64 iPos2 = 0;
127912
127913      if( iCol1 ){
127914        *p++ = POS_COLUMN;
127915        p += sqlite3Fts3PutVarint(p, iCol1);
127916      }
127917
127918      assert( *p1!=POS_END && *p1!=POS_COLUMN );
127919      assert( *p2!=POS_END && *p2!=POS_COLUMN );
127920      fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
127921      fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
127922
127923      while( 1 ){
127924        if( iPos2==iPos1+nToken
127925         || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
127926        ){
127927          sqlite3_int64 iSave;
127928          iSave = isSaveLeft ? iPos1 : iPos2;
127929          fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
127930          pSave = 0;
127931          assert( p );
127932        }
127933        if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
127934          if( (*p2&0xFE)==0 ) break;
127935          fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
127936        }else{
127937          if( (*p1&0xFE)==0 ) break;
127938          fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
127939        }
127940      }
127941
127942      if( pSave ){
127943        assert( pp && p );
127944        p = pSave;
127945      }
127946
127947      fts3ColumnlistCopy(0, &p1);
127948      fts3ColumnlistCopy(0, &p2);
127949      assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
127950      if( 0==*p1 || 0==*p2 ) break;
127951
127952      p1++;
127953      p1 += fts3GetVarint32(p1, &iCol1);
127954      p2++;
127955      p2 += fts3GetVarint32(p2, &iCol2);
127956    }
127957
127958    /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
127959    ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
127960    ** end of the position list, or the 0x01 that precedes the next
127961    ** column-number in the position list.
127962    */
127963    else if( iCol1<iCol2 ){
127964      fts3ColumnlistCopy(0, &p1);
127965      if( 0==*p1 ) break;
127966      p1++;
127967      p1 += fts3GetVarint32(p1, &iCol1);
127968    }else{
127969      fts3ColumnlistCopy(0, &p2);
127970      if( 0==*p2 ) break;
127971      p2++;
127972      p2 += fts3GetVarint32(p2, &iCol2);
127973    }
127974  }
127975
127976  fts3PoslistCopy(0, &p2);
127977  fts3PoslistCopy(0, &p1);
127978  *pp1 = p1;
127979  *pp2 = p2;
127980  if( *pp==p ){
127981    return 0;
127982  }
127983  *p++ = 0x00;
127984  *pp = p;
127985  return 1;
127986}
127987
127988/*
127989** Merge two position-lists as required by the NEAR operator. The argument
127990** position lists correspond to the left and right phrases of an expression
127991** like:
127992**
127993**     "phrase 1" NEAR "phrase number 2"
127994**
127995** Position list *pp1 corresponds to the left-hand side of the NEAR
127996** expression and *pp2 to the right. As usual, the indexes in the position
127997** lists are the offsets of the last token in each phrase (tokens "1" and "2"
127998** in the example above).
127999**
128000** The output position list - written to *pp - is a copy of *pp2 with those
128001** entries that are not sufficiently NEAR entries in *pp1 removed.
128002*/
128003static int fts3PoslistNearMerge(
128004  char **pp,                      /* Output buffer */
128005  char *aTmp,                     /* Temporary buffer space */
128006  int nRight,                     /* Maximum difference in token positions */
128007  int nLeft,                      /* Maximum difference in token positions */
128008  char **pp1,                     /* IN/OUT: Left input list */
128009  char **pp2                      /* IN/OUT: Right input list */
128010){
128011  char *p1 = *pp1;
128012  char *p2 = *pp2;
128013
128014  char *pTmp1 = aTmp;
128015  char *pTmp2;
128016  char *aTmp2;
128017  int res = 1;
128018
128019  fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
128020  aTmp2 = pTmp2 = pTmp1;
128021  *pp1 = p1;
128022  *pp2 = p2;
128023  fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
128024  if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
128025    fts3PoslistMerge(pp, &aTmp, &aTmp2);
128026  }else if( pTmp1!=aTmp ){
128027    fts3PoslistCopy(pp, &aTmp);
128028  }else if( pTmp2!=aTmp2 ){
128029    fts3PoslistCopy(pp, &aTmp2);
128030  }else{
128031    res = 0;
128032  }
128033
128034  return res;
128035}
128036
128037/*
128038** An instance of this function is used to merge together the (potentially
128039** large number of) doclists for each term that matches a prefix query.
128040** See function fts3TermSelectMerge() for details.
128041*/
128042typedef struct TermSelect TermSelect;
128043struct TermSelect {
128044  char *aaOutput[16];             /* Malloc'd output buffers */
128045  int anOutput[16];               /* Size each output buffer in bytes */
128046};
128047
128048/*
128049** This function is used to read a single varint from a buffer. Parameter
128050** pEnd points 1 byte past the end of the buffer. When this function is
128051** called, if *pp points to pEnd or greater, then the end of the buffer
128052** has been reached. In this case *pp is set to 0 and the function returns.
128053**
128054** If *pp does not point to or past pEnd, then a single varint is read
128055** from *pp. *pp is then set to point 1 byte past the end of the read varint.
128056**
128057** If bDescIdx is false, the value read is added to *pVal before returning.
128058** If it is true, the value read is subtracted from *pVal before this
128059** function returns.
128060*/
128061static void fts3GetDeltaVarint3(
128062  char **pp,                      /* IN/OUT: Point to read varint from */
128063  char *pEnd,                     /* End of buffer */
128064  int bDescIdx,                   /* True if docids are descending */
128065  sqlite3_int64 *pVal             /* IN/OUT: Integer value */
128066){
128067  if( *pp>=pEnd ){
128068    *pp = 0;
128069  }else{
128070    sqlite3_int64 iVal;
128071    *pp += sqlite3Fts3GetVarint(*pp, &iVal);
128072    if( bDescIdx ){
128073      *pVal -= iVal;
128074    }else{
128075      *pVal += iVal;
128076    }
128077  }
128078}
128079
128080/*
128081** This function is used to write a single varint to a buffer. The varint
128082** is written to *pp. Before returning, *pp is set to point 1 byte past the
128083** end of the value written.
128084**
128085** If *pbFirst is zero when this function is called, the value written to
128086** the buffer is that of parameter iVal.
128087**
128088** If *pbFirst is non-zero when this function is called, then the value
128089** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
128090** (if bDescIdx is non-zero).
128091**
128092** Before returning, this function always sets *pbFirst to 1 and *piPrev
128093** to the value of parameter iVal.
128094*/
128095static void fts3PutDeltaVarint3(
128096  char **pp,                      /* IN/OUT: Output pointer */
128097  int bDescIdx,                   /* True for descending docids */
128098  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
128099  int *pbFirst,                   /* IN/OUT: True after first int written */
128100  sqlite3_int64 iVal              /* Write this value to the list */
128101){
128102  sqlite3_int64 iWrite;
128103  if( bDescIdx==0 || *pbFirst==0 ){
128104    iWrite = iVal - *piPrev;
128105  }else{
128106    iWrite = *piPrev - iVal;
128107  }
128108  assert( *pbFirst || *piPrev==0 );
128109  assert( *pbFirst==0 || iWrite>0 );
128110  *pp += sqlite3Fts3PutVarint(*pp, iWrite);
128111  *piPrev = iVal;
128112  *pbFirst = 1;
128113}
128114
128115
128116/*
128117** This macro is used by various functions that merge doclists. The two
128118** arguments are 64-bit docid values. If the value of the stack variable
128119** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
128120** Otherwise, (i2-i1).
128121**
128122** Using this makes it easier to write code that can merge doclists that are
128123** sorted in either ascending or descending order.
128124*/
128125#define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
128126
128127/*
128128** This function does an "OR" merge of two doclists (output contains all
128129** positions contained in either argument doclist). If the docids in the
128130** input doclists are sorted in ascending order, parameter bDescDoclist
128131** should be false. If they are sorted in ascending order, it should be
128132** passed a non-zero value.
128133**
128134** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
128135** containing the output doclist and SQLITE_OK is returned. In this case
128136** *pnOut is set to the number of bytes in the output doclist.
128137**
128138** If an error occurs, an SQLite error code is returned. The output values
128139** are undefined in this case.
128140*/
128141static int fts3DoclistOrMerge(
128142  int bDescDoclist,               /* True if arguments are desc */
128143  char *a1, int n1,               /* First doclist */
128144  char *a2, int n2,               /* Second doclist */
128145  char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
128146){
128147  sqlite3_int64 i1 = 0;
128148  sqlite3_int64 i2 = 0;
128149  sqlite3_int64 iPrev = 0;
128150  char *pEnd1 = &a1[n1];
128151  char *pEnd2 = &a2[n2];
128152  char *p1 = a1;
128153  char *p2 = a2;
128154  char *p;
128155  char *aOut;
128156  int bFirstOut = 0;
128157
128158  *paOut = 0;
128159  *pnOut = 0;
128160
128161  /* Allocate space for the output. Both the input and output doclists
128162  ** are delta encoded. If they are in ascending order (bDescDoclist==0),
128163  ** then the first docid in each list is simply encoded as a varint. For
128164  ** each subsequent docid, the varint stored is the difference between the
128165  ** current and previous docid (a positive number - since the list is in
128166  ** ascending order).
128167  **
128168  ** The first docid written to the output is therefore encoded using the
128169  ** same number of bytes as it is in whichever of the input lists it is
128170  ** read from. And each subsequent docid read from the same input list
128171  ** consumes either the same or less bytes as it did in the input (since
128172  ** the difference between it and the previous value in the output must
128173  ** be a positive value less than or equal to the delta value read from
128174  ** the input list). The same argument applies to all but the first docid
128175  ** read from the 'other' list. And to the contents of all position lists
128176  ** that will be copied and merged from the input to the output.
128177  **
128178  ** However, if the first docid copied to the output is a negative number,
128179  ** then the encoding of the first docid from the 'other' input list may
128180  ** be larger in the output than it was in the input (since the delta value
128181  ** may be a larger positive integer than the actual docid).
128182  **
128183  ** The space required to store the output is therefore the sum of the
128184  ** sizes of the two inputs, plus enough space for exactly one of the input
128185  ** docids to grow.
128186  **
128187  ** A symetric argument may be made if the doclists are in descending
128188  ** order.
128189  */
128190  aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
128191  if( !aOut ) return SQLITE_NOMEM;
128192
128193  p = aOut;
128194  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
128195  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
128196  while( p1 || p2 ){
128197    sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
128198
128199    if( p2 && p1 && iDiff==0 ){
128200      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
128201      fts3PoslistMerge(&p, &p1, &p2);
128202      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
128203      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
128204    }else if( !p2 || (p1 && iDiff<0) ){
128205      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
128206      fts3PoslistCopy(&p, &p1);
128207      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
128208    }else{
128209      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
128210      fts3PoslistCopy(&p, &p2);
128211      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
128212    }
128213  }
128214
128215  *paOut = aOut;
128216  *pnOut = (int)(p-aOut);
128217  assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
128218  return SQLITE_OK;
128219}
128220
128221/*
128222** This function does a "phrase" merge of two doclists. In a phrase merge,
128223** the output contains a copy of each position from the right-hand input
128224** doclist for which there is a position in the left-hand input doclist
128225** exactly nDist tokens before it.
128226**
128227** If the docids in the input doclists are sorted in ascending order,
128228** parameter bDescDoclist should be false. If they are sorted in ascending
128229** order, it should be passed a non-zero value.
128230**
128231** The right-hand input doclist is overwritten by this function.
128232*/
128233static void fts3DoclistPhraseMerge(
128234  int bDescDoclist,               /* True if arguments are desc */
128235  int nDist,                      /* Distance from left to right (1=adjacent) */
128236  char *aLeft, int nLeft,         /* Left doclist */
128237  char *aRight, int *pnRight      /* IN/OUT: Right/output doclist */
128238){
128239  sqlite3_int64 i1 = 0;
128240  sqlite3_int64 i2 = 0;
128241  sqlite3_int64 iPrev = 0;
128242  char *pEnd1 = &aLeft[nLeft];
128243  char *pEnd2 = &aRight[*pnRight];
128244  char *p1 = aLeft;
128245  char *p2 = aRight;
128246  char *p;
128247  int bFirstOut = 0;
128248  char *aOut = aRight;
128249
128250  assert( nDist>0 );
128251
128252  p = aOut;
128253  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
128254  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
128255
128256  while( p1 && p2 ){
128257    sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
128258    if( iDiff==0 ){
128259      char *pSave = p;
128260      sqlite3_int64 iPrevSave = iPrev;
128261      int bFirstOutSave = bFirstOut;
128262
128263      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
128264      if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
128265        p = pSave;
128266        iPrev = iPrevSave;
128267        bFirstOut = bFirstOutSave;
128268      }
128269      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
128270      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
128271    }else if( iDiff<0 ){
128272      fts3PoslistCopy(0, &p1);
128273      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
128274    }else{
128275      fts3PoslistCopy(0, &p2);
128276      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
128277    }
128278  }
128279
128280  *pnRight = (int)(p - aOut);
128281}
128282
128283/*
128284** Argument pList points to a position list nList bytes in size. This
128285** function checks to see if the position list contains any entries for
128286** a token in position 0 (of any column). If so, it writes argument iDelta
128287** to the output buffer pOut, followed by a position list consisting only
128288** of the entries from pList at position 0, and terminated by an 0x00 byte.
128289** The value returned is the number of bytes written to pOut (if any).
128290*/
128291SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
128292  sqlite3_int64 iDelta,           /* Varint that may be written to pOut */
128293  char *pList,                    /* Position list (no 0x00 term) */
128294  int nList,                      /* Size of pList in bytes */
128295  char *pOut                      /* Write output here */
128296){
128297  int nOut = 0;
128298  int bWritten = 0;               /* True once iDelta has been written */
128299  char *p = pList;
128300  char *pEnd = &pList[nList];
128301
128302  if( *p!=0x01 ){
128303    if( *p==0x02 ){
128304      nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
128305      pOut[nOut++] = 0x02;
128306      bWritten = 1;
128307    }
128308    fts3ColumnlistCopy(0, &p);
128309  }
128310
128311  while( p<pEnd && *p==0x01 ){
128312    sqlite3_int64 iCol;
128313    p++;
128314    p += sqlite3Fts3GetVarint(p, &iCol);
128315    if( *p==0x02 ){
128316      if( bWritten==0 ){
128317        nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
128318        bWritten = 1;
128319      }
128320      pOut[nOut++] = 0x01;
128321      nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
128322      pOut[nOut++] = 0x02;
128323    }
128324    fts3ColumnlistCopy(0, &p);
128325  }
128326  if( bWritten ){
128327    pOut[nOut++] = 0x00;
128328  }
128329
128330  return nOut;
128331}
128332
128333
128334/*
128335** Merge all doclists in the TermSelect.aaOutput[] array into a single
128336** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
128337** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
128338**
128339** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
128340** the responsibility of the caller to free any doclists left in the
128341** TermSelect.aaOutput[] array.
128342*/
128343static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
128344  char *aOut = 0;
128345  int nOut = 0;
128346  int i;
128347
128348  /* Loop through the doclists in the aaOutput[] array. Merge them all
128349  ** into a single doclist.
128350  */
128351  for(i=0; i<SizeofArray(pTS->aaOutput); i++){
128352    if( pTS->aaOutput[i] ){
128353      if( !aOut ){
128354        aOut = pTS->aaOutput[i];
128355        nOut = pTS->anOutput[i];
128356        pTS->aaOutput[i] = 0;
128357      }else{
128358        int nNew;
128359        char *aNew;
128360
128361        int rc = fts3DoclistOrMerge(p->bDescIdx,
128362            pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
128363        );
128364        if( rc!=SQLITE_OK ){
128365          sqlite3_free(aOut);
128366          return rc;
128367        }
128368
128369        sqlite3_free(pTS->aaOutput[i]);
128370        sqlite3_free(aOut);
128371        pTS->aaOutput[i] = 0;
128372        aOut = aNew;
128373        nOut = nNew;
128374      }
128375    }
128376  }
128377
128378  pTS->aaOutput[0] = aOut;
128379  pTS->anOutput[0] = nOut;
128380  return SQLITE_OK;
128381}
128382
128383/*
128384** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
128385** as the first argument. The merge is an "OR" merge (see function
128386** fts3DoclistOrMerge() for details).
128387**
128388** This function is called with the doclist for each term that matches
128389** a queried prefix. It merges all these doclists into one, the doclist
128390** for the specified prefix. Since there can be a very large number of
128391** doclists to merge, the merging is done pair-wise using the TermSelect
128392** object.
128393**
128394** This function returns SQLITE_OK if the merge is successful, or an
128395** SQLite error code (SQLITE_NOMEM) if an error occurs.
128396*/
128397static int fts3TermSelectMerge(
128398  Fts3Table *p,                   /* FTS table handle */
128399  TermSelect *pTS,                /* TermSelect object to merge into */
128400  char *aDoclist,                 /* Pointer to doclist */
128401  int nDoclist                    /* Size of aDoclist in bytes */
128402){
128403  if( pTS->aaOutput[0]==0 ){
128404    /* If this is the first term selected, copy the doclist to the output
128405    ** buffer using memcpy(). */
128406    pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
128407    pTS->anOutput[0] = nDoclist;
128408    if( pTS->aaOutput[0] ){
128409      memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
128410    }else{
128411      return SQLITE_NOMEM;
128412    }
128413  }else{
128414    char *aMerge = aDoclist;
128415    int nMerge = nDoclist;
128416    int iOut;
128417
128418    for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
128419      if( pTS->aaOutput[iOut]==0 ){
128420        assert( iOut>0 );
128421        pTS->aaOutput[iOut] = aMerge;
128422        pTS->anOutput[iOut] = nMerge;
128423        break;
128424      }else{
128425        char *aNew;
128426        int nNew;
128427
128428        int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
128429            pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
128430        );
128431        if( rc!=SQLITE_OK ){
128432          if( aMerge!=aDoclist ) sqlite3_free(aMerge);
128433          return rc;
128434        }
128435
128436        if( aMerge!=aDoclist ) sqlite3_free(aMerge);
128437        sqlite3_free(pTS->aaOutput[iOut]);
128438        pTS->aaOutput[iOut] = 0;
128439
128440        aMerge = aNew;
128441        nMerge = nNew;
128442        if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
128443          pTS->aaOutput[iOut] = aMerge;
128444          pTS->anOutput[iOut] = nMerge;
128445        }
128446      }
128447    }
128448  }
128449  return SQLITE_OK;
128450}
128451
128452/*
128453** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
128454*/
128455static int fts3SegReaderCursorAppend(
128456  Fts3MultiSegReader *pCsr,
128457  Fts3SegReader *pNew
128458){
128459  if( (pCsr->nSegment%16)==0 ){
128460    Fts3SegReader **apNew;
128461    int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
128462    apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
128463    if( !apNew ){
128464      sqlite3Fts3SegReaderFree(pNew);
128465      return SQLITE_NOMEM;
128466    }
128467    pCsr->apSegment = apNew;
128468  }
128469  pCsr->apSegment[pCsr->nSegment++] = pNew;
128470  return SQLITE_OK;
128471}
128472
128473/*
128474** Add seg-reader objects to the Fts3MultiSegReader object passed as the
128475** 8th argument.
128476**
128477** This function returns SQLITE_OK if successful, or an SQLite error code
128478** otherwise.
128479*/
128480static int fts3SegReaderCursor(
128481  Fts3Table *p,                   /* FTS3 table handle */
128482  int iLangid,                    /* Language id */
128483  int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
128484  int iLevel,                     /* Level of segments to scan */
128485  const char *zTerm,              /* Term to query for */
128486  int nTerm,                      /* Size of zTerm in bytes */
128487  int isPrefix,                   /* True for a prefix search */
128488  int isScan,                     /* True to scan from zTerm to EOF */
128489  Fts3MultiSegReader *pCsr        /* Cursor object to populate */
128490){
128491  int rc = SQLITE_OK;             /* Error code */
128492  sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
128493  int rc2;                        /* Result of sqlite3_reset() */
128494
128495  /* If iLevel is less than 0 and this is not a scan, include a seg-reader
128496  ** for the pending-terms. If this is a scan, then this call must be being
128497  ** made by an fts4aux module, not an FTS table. In this case calling
128498  ** Fts3SegReaderPending might segfault, as the data structures used by
128499  ** fts4aux are not completely populated. So it's easiest to filter these
128500  ** calls out here.  */
128501  if( iLevel<0 && p->aIndex ){
128502    Fts3SegReader *pSeg = 0;
128503    rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
128504    if( rc==SQLITE_OK && pSeg ){
128505      rc = fts3SegReaderCursorAppend(pCsr, pSeg);
128506    }
128507  }
128508
128509  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
128510    if( rc==SQLITE_OK ){
128511      rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
128512    }
128513
128514    while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
128515      Fts3SegReader *pSeg = 0;
128516
128517      /* Read the values returned by the SELECT into local variables. */
128518      sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
128519      sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
128520      sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
128521      int nRoot = sqlite3_column_bytes(pStmt, 4);
128522      char const *zRoot = sqlite3_column_blob(pStmt, 4);
128523
128524      /* If zTerm is not NULL, and this segment is not stored entirely on its
128525      ** root node, the range of leaves scanned can be reduced. Do this. */
128526      if( iStartBlock && zTerm ){
128527        sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
128528        rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
128529        if( rc!=SQLITE_OK ) goto finished;
128530        if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
128531      }
128532
128533      rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
128534          (isPrefix==0 && isScan==0),
128535          iStartBlock, iLeavesEndBlock,
128536          iEndBlock, zRoot, nRoot, &pSeg
128537      );
128538      if( rc!=SQLITE_OK ) goto finished;
128539      rc = fts3SegReaderCursorAppend(pCsr, pSeg);
128540    }
128541  }
128542
128543 finished:
128544  rc2 = sqlite3_reset(pStmt);
128545  if( rc==SQLITE_DONE ) rc = rc2;
128546
128547  return rc;
128548}
128549
128550/*
128551** Set up a cursor object for iterating through a full-text index or a
128552** single level therein.
128553*/
128554SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
128555  Fts3Table *p,                   /* FTS3 table handle */
128556  int iLangid,                    /* Language-id to search */
128557  int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
128558  int iLevel,                     /* Level of segments to scan */
128559  const char *zTerm,              /* Term to query for */
128560  int nTerm,                      /* Size of zTerm in bytes */
128561  int isPrefix,                   /* True for a prefix search */
128562  int isScan,                     /* True to scan from zTerm to EOF */
128563  Fts3MultiSegReader *pCsr       /* Cursor object to populate */
128564){
128565  assert( iIndex>=0 && iIndex<p->nIndex );
128566  assert( iLevel==FTS3_SEGCURSOR_ALL
128567      ||  iLevel==FTS3_SEGCURSOR_PENDING
128568      ||  iLevel>=0
128569  );
128570  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
128571  assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
128572  assert( isPrefix==0 || isScan==0 );
128573
128574  memset(pCsr, 0, sizeof(Fts3MultiSegReader));
128575  return fts3SegReaderCursor(
128576      p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
128577  );
128578}
128579
128580/*
128581** In addition to its current configuration, have the Fts3MultiSegReader
128582** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
128583**
128584** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
128585*/
128586static int fts3SegReaderCursorAddZero(
128587  Fts3Table *p,                   /* FTS virtual table handle */
128588  int iLangid,
128589  const char *zTerm,              /* Term to scan doclist of */
128590  int nTerm,                      /* Number of bytes in zTerm */
128591  Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
128592){
128593  return fts3SegReaderCursor(p,
128594      iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
128595  );
128596}
128597
128598/*
128599** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
128600** if isPrefix is true, to scan the doclist for all terms for which
128601** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
128602** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
128603** an SQLite error code.
128604**
128605** It is the responsibility of the caller to free this object by eventually
128606** passing it to fts3SegReaderCursorFree()
128607**
128608** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
128609** Output parameter *ppSegcsr is set to 0 if an error occurs.
128610*/
128611static int fts3TermSegReaderCursor(
128612  Fts3Cursor *pCsr,               /* Virtual table cursor handle */
128613  const char *zTerm,              /* Term to query for */
128614  int nTerm,                      /* Size of zTerm in bytes */
128615  int isPrefix,                   /* True for a prefix search */
128616  Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
128617){
128618  Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
128619  int rc = SQLITE_NOMEM;          /* Return code */
128620
128621  pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
128622  if( pSegcsr ){
128623    int i;
128624    int bFound = 0;               /* True once an index has been found */
128625    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
128626
128627    if( isPrefix ){
128628      for(i=1; bFound==0 && i<p->nIndex; i++){
128629        if( p->aIndex[i].nPrefix==nTerm ){
128630          bFound = 1;
128631          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
128632              i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
128633          );
128634          pSegcsr->bLookup = 1;
128635        }
128636      }
128637
128638      for(i=1; bFound==0 && i<p->nIndex; i++){
128639        if( p->aIndex[i].nPrefix==nTerm+1 ){
128640          bFound = 1;
128641          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
128642              i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
128643          );
128644          if( rc==SQLITE_OK ){
128645            rc = fts3SegReaderCursorAddZero(
128646                p, pCsr->iLangid, zTerm, nTerm, pSegcsr
128647            );
128648          }
128649        }
128650      }
128651    }
128652
128653    if( bFound==0 ){
128654      rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
128655          0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
128656      );
128657      pSegcsr->bLookup = !isPrefix;
128658    }
128659  }
128660
128661  *ppSegcsr = pSegcsr;
128662  return rc;
128663}
128664
128665/*
128666** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
128667*/
128668static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
128669  sqlite3Fts3SegReaderFinish(pSegcsr);
128670  sqlite3_free(pSegcsr);
128671}
128672
128673/*
128674** This function retrieves the doclist for the specified term (or term
128675** prefix) from the database.
128676*/
128677static int fts3TermSelect(
128678  Fts3Table *p,                   /* Virtual table handle */
128679  Fts3PhraseToken *pTok,          /* Token to query for */
128680  int iColumn,                    /* Column to query (or -ve for all columns) */
128681  int *pnOut,                     /* OUT: Size of buffer at *ppOut */
128682  char **ppOut                    /* OUT: Malloced result buffer */
128683){
128684  int rc;                         /* Return code */
128685  Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
128686  TermSelect tsc;                 /* Object for pair-wise doclist merging */
128687  Fts3SegFilter filter;           /* Segment term filter configuration */
128688
128689  pSegcsr = pTok->pSegcsr;
128690  memset(&tsc, 0, sizeof(TermSelect));
128691
128692  filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
128693        | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
128694        | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
128695        | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
128696  filter.iCol = iColumn;
128697  filter.zTerm = pTok->z;
128698  filter.nTerm = pTok->n;
128699
128700  rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
128701  while( SQLITE_OK==rc
128702      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
128703  ){
128704    rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
128705  }
128706
128707  if( rc==SQLITE_OK ){
128708    rc = fts3TermSelectFinishMerge(p, &tsc);
128709  }
128710  if( rc==SQLITE_OK ){
128711    *ppOut = tsc.aaOutput[0];
128712    *pnOut = tsc.anOutput[0];
128713  }else{
128714    int i;
128715    for(i=0; i<SizeofArray(tsc.aaOutput); i++){
128716      sqlite3_free(tsc.aaOutput[i]);
128717    }
128718  }
128719
128720  fts3SegReaderCursorFree(pSegcsr);
128721  pTok->pSegcsr = 0;
128722  return rc;
128723}
128724
128725/*
128726** This function counts the total number of docids in the doclist stored
128727** in buffer aList[], size nList bytes.
128728**
128729** If the isPoslist argument is true, then it is assumed that the doclist
128730** contains a position-list following each docid. Otherwise, it is assumed
128731** that the doclist is simply a list of docids stored as delta encoded
128732** varints.
128733*/
128734static int fts3DoclistCountDocids(char *aList, int nList){
128735  int nDoc = 0;                   /* Return value */
128736  if( aList ){
128737    char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
128738    char *p = aList;              /* Cursor */
128739    while( p<aEnd ){
128740      nDoc++;
128741      while( (*p++)&0x80 );     /* Skip docid varint */
128742      fts3PoslistCopy(0, &p);   /* Skip over position list */
128743    }
128744  }
128745
128746  return nDoc;
128747}
128748
128749/*
128750** Advance the cursor to the next row in the %_content table that
128751** matches the search criteria.  For a MATCH search, this will be
128752** the next row that matches. For a full-table scan, this will be
128753** simply the next row in the %_content table.  For a docid lookup,
128754** this routine simply sets the EOF flag.
128755**
128756** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
128757** even if we reach end-of-file.  The fts3EofMethod() will be called
128758** subsequently to determine whether or not an EOF was hit.
128759*/
128760static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
128761  int rc;
128762  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
128763  if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
128764    if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
128765      pCsr->isEof = 1;
128766      rc = sqlite3_reset(pCsr->pStmt);
128767    }else{
128768      pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
128769      rc = SQLITE_OK;
128770    }
128771  }else{
128772    rc = fts3EvalNext((Fts3Cursor *)pCursor);
128773  }
128774  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
128775  return rc;
128776}
128777
128778/*
128779** The following are copied from sqliteInt.h.
128780**
128781** Constants for the largest and smallest possible 64-bit signed integers.
128782** These macros are designed to work correctly on both 32-bit and 64-bit
128783** compilers.
128784*/
128785#ifndef SQLITE_AMALGAMATION
128786# define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
128787# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
128788#endif
128789
128790/*
128791** If the numeric type of argument pVal is "integer", then return it
128792** converted to a 64-bit signed integer. Otherwise, return a copy of
128793** the second parameter, iDefault.
128794*/
128795static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
128796  if( pVal ){
128797    int eType = sqlite3_value_numeric_type(pVal);
128798    if( eType==SQLITE_INTEGER ){
128799      return sqlite3_value_int64(pVal);
128800    }
128801  }
128802  return iDefault;
128803}
128804
128805/*
128806** This is the xFilter interface for the virtual table.  See
128807** the virtual table xFilter method documentation for additional
128808** information.
128809**
128810** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
128811** the %_content table.
128812**
128813** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
128814** in the %_content table.
128815**
128816** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
128817** column on the left-hand side of the MATCH operator is column
128818** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
128819** side of the MATCH operator.
128820*/
128821static int fts3FilterMethod(
128822  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
128823  int idxNum,                     /* Strategy index */
128824  const char *idxStr,             /* Unused */
128825  int nVal,                       /* Number of elements in apVal */
128826  sqlite3_value **apVal           /* Arguments for the indexing scheme */
128827){
128828  int rc;
128829  char *zSql;                     /* SQL statement used to access %_content */
128830  int eSearch;
128831  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
128832  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
128833
128834  sqlite3_value *pCons = 0;       /* The MATCH or rowid constraint, if any */
128835  sqlite3_value *pLangid = 0;     /* The "langid = ?" constraint, if any */
128836  sqlite3_value *pDocidGe = 0;    /* The "docid >= ?" constraint, if any */
128837  sqlite3_value *pDocidLe = 0;    /* The "docid <= ?" constraint, if any */
128838  int iIdx;
128839
128840  UNUSED_PARAMETER(idxStr);
128841  UNUSED_PARAMETER(nVal);
128842
128843  eSearch = (idxNum & 0x0000FFFF);
128844  assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
128845  assert( p->pSegments==0 );
128846
128847  /* Collect arguments into local variables */
128848  iIdx = 0;
128849  if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
128850  if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
128851  if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
128852  if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
128853  assert( iIdx==nVal );
128854
128855  /* In case the cursor has been used before, clear it now. */
128856  sqlite3_finalize(pCsr->pStmt);
128857  sqlite3_free(pCsr->aDoclist);
128858  sqlite3Fts3ExprFree(pCsr->pExpr);
128859  memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
128860
128861  /* Set the lower and upper bounds on docids to return */
128862  pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
128863  pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
128864
128865  if( idxStr ){
128866    pCsr->bDesc = (idxStr[0]=='D');
128867  }else{
128868    pCsr->bDesc = p->bDescIdx;
128869  }
128870  pCsr->eSearch = (i16)eSearch;
128871
128872  if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
128873    int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
128874    const char *zQuery = (const char *)sqlite3_value_text(pCons);
128875
128876    if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
128877      return SQLITE_NOMEM;
128878    }
128879
128880    pCsr->iLangid = 0;
128881    if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
128882
128883    assert( p->base.zErrMsg==0 );
128884    rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
128885        p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
128886        &p->base.zErrMsg
128887    );
128888    if( rc!=SQLITE_OK ){
128889      return rc;
128890    }
128891
128892    rc = fts3EvalStart(pCsr);
128893    sqlite3Fts3SegmentsClose(p);
128894    if( rc!=SQLITE_OK ) return rc;
128895    pCsr->pNextId = pCsr->aDoclist;
128896    pCsr->iPrevId = 0;
128897  }
128898
128899  /* Compile a SELECT statement for this cursor. For a full-table-scan, the
128900  ** statement loops through all rows of the %_content table. For a
128901  ** full-text query or docid lookup, the statement retrieves a single
128902  ** row by docid.
128903  */
128904  if( eSearch==FTS3_FULLSCAN_SEARCH ){
128905    zSql = sqlite3_mprintf(
128906        "SELECT %s ORDER BY rowid %s",
128907        p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
128908    );
128909    if( zSql ){
128910      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
128911      sqlite3_free(zSql);
128912    }else{
128913      rc = SQLITE_NOMEM;
128914    }
128915  }else if( eSearch==FTS3_DOCID_SEARCH ){
128916    rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
128917    if( rc==SQLITE_OK ){
128918      rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
128919    }
128920  }
128921  if( rc!=SQLITE_OK ) return rc;
128922
128923  return fts3NextMethod(pCursor);
128924}
128925
128926/*
128927** This is the xEof method of the virtual table. SQLite calls this
128928** routine to find out if it has reached the end of a result set.
128929*/
128930static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
128931  return ((Fts3Cursor *)pCursor)->isEof;
128932}
128933
128934/*
128935** This is the xRowid method. The SQLite core calls this routine to
128936** retrieve the rowid for the current row of the result set. fts3
128937** exposes %_content.docid as the rowid for the virtual table. The
128938** rowid should be written to *pRowid.
128939*/
128940static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
128941  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
128942  *pRowid = pCsr->iPrevId;
128943  return SQLITE_OK;
128944}
128945
128946/*
128947** This is the xColumn method, called by SQLite to request a value from
128948** the row that the supplied cursor currently points to.
128949**
128950** If:
128951**
128952**   (iCol <  p->nColumn)   -> The value of the iCol'th user column.
128953**   (iCol == p->nColumn)   -> Magic column with the same name as the table.
128954**   (iCol == p->nColumn+1) -> Docid column
128955**   (iCol == p->nColumn+2) -> Langid column
128956*/
128957static int fts3ColumnMethod(
128958  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
128959  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
128960  int iCol                        /* Index of column to read value from */
128961){
128962  int rc = SQLITE_OK;             /* Return Code */
128963  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
128964  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
128965
128966  /* The column value supplied by SQLite must be in range. */
128967  assert( iCol>=0 && iCol<=p->nColumn+2 );
128968
128969  if( iCol==p->nColumn+1 ){
128970    /* This call is a request for the "docid" column. Since "docid" is an
128971    ** alias for "rowid", use the xRowid() method to obtain the value.
128972    */
128973    sqlite3_result_int64(pCtx, pCsr->iPrevId);
128974  }else if( iCol==p->nColumn ){
128975    /* The extra column whose name is the same as the table.
128976    ** Return a blob which is a pointer to the cursor.  */
128977    sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
128978  }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
128979    sqlite3_result_int64(pCtx, pCsr->iLangid);
128980  }else{
128981    /* The requested column is either a user column (one that contains
128982    ** indexed data), or the language-id column.  */
128983    rc = fts3CursorSeek(0, pCsr);
128984
128985    if( rc==SQLITE_OK ){
128986      if( iCol==p->nColumn+2 ){
128987        int iLangid = 0;
128988        if( p->zLanguageid ){
128989          iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
128990        }
128991        sqlite3_result_int(pCtx, iLangid);
128992      }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
128993        sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
128994      }
128995    }
128996  }
128997
128998  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
128999  return rc;
129000}
129001
129002/*
129003** This function is the implementation of the xUpdate callback used by
129004** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
129005** inserted, updated or deleted.
129006*/
129007static int fts3UpdateMethod(
129008  sqlite3_vtab *pVtab,            /* Virtual table handle */
129009  int nArg,                       /* Size of argument array */
129010  sqlite3_value **apVal,          /* Array of arguments */
129011  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
129012){
129013  return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
129014}
129015
129016/*
129017** Implementation of xSync() method. Flush the contents of the pending-terms
129018** hash-table to the database.
129019*/
129020static int fts3SyncMethod(sqlite3_vtab *pVtab){
129021
129022  /* Following an incremental-merge operation, assuming that the input
129023  ** segments are not completely consumed (the usual case), they are updated
129024  ** in place to remove the entries that have already been merged. This
129025  ** involves updating the leaf block that contains the smallest unmerged
129026  ** entry and each block (if any) between the leaf and the root node. So
129027  ** if the height of the input segment b-trees is N, and input segments
129028  ** are merged eight at a time, updating the input segments at the end
129029  ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
129030  ** small - often between 0 and 2. So the overhead of the incremental
129031  ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
129032  ** dwarfing the actual productive work accomplished, the incremental merge
129033  ** is only attempted if it will write at least 64 leaf blocks. Hence
129034  ** nMinMerge.
129035  **
129036  ** Of course, updating the input segments also involves deleting a bunch
129037  ** of blocks from the segments table. But this is not considered overhead
129038  ** as it would also be required by a crisis-merge that used the same input
129039  ** segments.
129040  */
129041  const u32 nMinMerge = 64;       /* Minimum amount of incr-merge work to do */
129042
129043  Fts3Table *p = (Fts3Table*)pVtab;
129044  int rc = sqlite3Fts3PendingTermsFlush(p);
129045
129046  if( rc==SQLITE_OK
129047   && p->nLeafAdd>(nMinMerge/16)
129048   && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
129049  ){
129050    int mxLevel = 0;              /* Maximum relative level value in db */
129051    int A;                        /* Incr-merge parameter A */
129052
129053    rc = sqlite3Fts3MaxLevel(p, &mxLevel);
129054    assert( rc==SQLITE_OK || mxLevel==0 );
129055    A = p->nLeafAdd * mxLevel;
129056    A += (A/2);
129057    if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
129058  }
129059  sqlite3Fts3SegmentsClose(p);
129060  return rc;
129061}
129062
129063/*
129064** If it is currently unknown whether or not the FTS table has an %_stat
129065** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
129066** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
129067** if an error occurs.
129068*/
129069static int fts3SetHasStat(Fts3Table *p){
129070  int rc = SQLITE_OK;
129071  if( p->bHasStat==2 ){
129072    const char *zFmt ="SELECT 1 FROM %Q.sqlite_master WHERE tbl_name='%q_stat'";
129073    char *zSql = sqlite3_mprintf(zFmt, p->zDb, p->zName);
129074    if( zSql ){
129075      sqlite3_stmt *pStmt = 0;
129076      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
129077      if( rc==SQLITE_OK ){
129078        int bHasStat = (sqlite3_step(pStmt)==SQLITE_ROW);
129079        rc = sqlite3_finalize(pStmt);
129080        if( rc==SQLITE_OK ) p->bHasStat = bHasStat;
129081      }
129082      sqlite3_free(zSql);
129083    }else{
129084      rc = SQLITE_NOMEM;
129085    }
129086  }
129087  return rc;
129088}
129089
129090/*
129091** Implementation of xBegin() method.
129092*/
129093static int fts3BeginMethod(sqlite3_vtab *pVtab){
129094  Fts3Table *p = (Fts3Table*)pVtab;
129095  UNUSED_PARAMETER(pVtab);
129096  assert( p->pSegments==0 );
129097  assert( p->nPendingData==0 );
129098  assert( p->inTransaction!=1 );
129099  TESTONLY( p->inTransaction = 1 );
129100  TESTONLY( p->mxSavepoint = -1; );
129101  p->nLeafAdd = 0;
129102  return fts3SetHasStat(p);
129103}
129104
129105/*
129106** Implementation of xCommit() method. This is a no-op. The contents of
129107** the pending-terms hash-table have already been flushed into the database
129108** by fts3SyncMethod().
129109*/
129110static int fts3CommitMethod(sqlite3_vtab *pVtab){
129111  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
129112  UNUSED_PARAMETER(pVtab);
129113  assert( p->nPendingData==0 );
129114  assert( p->inTransaction!=0 );
129115  assert( p->pSegments==0 );
129116  TESTONLY( p->inTransaction = 0 );
129117  TESTONLY( p->mxSavepoint = -1; );
129118  return SQLITE_OK;
129119}
129120
129121/*
129122** Implementation of xRollback(). Discard the contents of the pending-terms
129123** hash-table. Any changes made to the database are reverted by SQLite.
129124*/
129125static int fts3RollbackMethod(sqlite3_vtab *pVtab){
129126  Fts3Table *p = (Fts3Table*)pVtab;
129127  sqlite3Fts3PendingTermsClear(p);
129128  assert( p->inTransaction!=0 );
129129  TESTONLY( p->inTransaction = 0 );
129130  TESTONLY( p->mxSavepoint = -1; );
129131  return SQLITE_OK;
129132}
129133
129134/*
129135** When called, *ppPoslist must point to the byte immediately following the
129136** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
129137** moves *ppPoslist so that it instead points to the first byte of the
129138** same position list.
129139*/
129140static void fts3ReversePoslist(char *pStart, char **ppPoslist){
129141  char *p = &(*ppPoslist)[-2];
129142  char c = 0;
129143
129144  while( p>pStart && (c=*p--)==0 );
129145  while( p>pStart && (*p & 0x80) | c ){
129146    c = *p--;
129147  }
129148  if( p>pStart ){ p = &p[2]; }
129149  while( *p++&0x80 );
129150  *ppPoslist = p;
129151}
129152
129153/*
129154** Helper function used by the implementation of the overloaded snippet(),
129155** offsets() and optimize() SQL functions.
129156**
129157** If the value passed as the third argument is a blob of size
129158** sizeof(Fts3Cursor*), then the blob contents are copied to the
129159** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
129160** message is written to context pContext and SQLITE_ERROR returned. The
129161** string passed via zFunc is used as part of the error message.
129162*/
129163static int fts3FunctionArg(
129164  sqlite3_context *pContext,      /* SQL function call context */
129165  const char *zFunc,              /* Function name */
129166  sqlite3_value *pVal,            /* argv[0] passed to function */
129167  Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
129168){
129169  Fts3Cursor *pRet;
129170  if( sqlite3_value_type(pVal)!=SQLITE_BLOB
129171   || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
129172  ){
129173    char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
129174    sqlite3_result_error(pContext, zErr, -1);
129175    sqlite3_free(zErr);
129176    return SQLITE_ERROR;
129177  }
129178  memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
129179  *ppCsr = pRet;
129180  return SQLITE_OK;
129181}
129182
129183/*
129184** Implementation of the snippet() function for FTS3
129185*/
129186static void fts3SnippetFunc(
129187  sqlite3_context *pContext,      /* SQLite function call context */
129188  int nVal,                       /* Size of apVal[] array */
129189  sqlite3_value **apVal           /* Array of arguments */
129190){
129191  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
129192  const char *zStart = "<b>";
129193  const char *zEnd = "</b>";
129194  const char *zEllipsis = "<b>...</b>";
129195  int iCol = -1;
129196  int nToken = 15;                /* Default number of tokens in snippet */
129197
129198  /* There must be at least one argument passed to this function (otherwise
129199  ** the non-overloaded version would have been called instead of this one).
129200  */
129201  assert( nVal>=1 );
129202
129203  if( nVal>6 ){
129204    sqlite3_result_error(pContext,
129205        "wrong number of arguments to function snippet()", -1);
129206    return;
129207  }
129208  if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
129209
129210  switch( nVal ){
129211    case 6: nToken = sqlite3_value_int(apVal[5]);
129212    case 5: iCol = sqlite3_value_int(apVal[4]);
129213    case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
129214    case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
129215    case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
129216  }
129217  if( !zEllipsis || !zEnd || !zStart ){
129218    sqlite3_result_error_nomem(pContext);
129219  }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
129220    sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
129221  }
129222}
129223
129224/*
129225** Implementation of the offsets() function for FTS3
129226*/
129227static void fts3OffsetsFunc(
129228  sqlite3_context *pContext,      /* SQLite function call context */
129229  int nVal,                       /* Size of argument array */
129230  sqlite3_value **apVal           /* Array of arguments */
129231){
129232  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
129233
129234  UNUSED_PARAMETER(nVal);
129235
129236  assert( nVal==1 );
129237  if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
129238  assert( pCsr );
129239  if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
129240    sqlite3Fts3Offsets(pContext, pCsr);
129241  }
129242}
129243
129244/*
129245** Implementation of the special optimize() function for FTS3. This
129246** function merges all segments in the database to a single segment.
129247** Example usage is:
129248**
129249**   SELECT optimize(t) FROM t LIMIT 1;
129250**
129251** where 't' is the name of an FTS3 table.
129252*/
129253static void fts3OptimizeFunc(
129254  sqlite3_context *pContext,      /* SQLite function call context */
129255  int nVal,                       /* Size of argument array */
129256  sqlite3_value **apVal           /* Array of arguments */
129257){
129258  int rc;                         /* Return code */
129259  Fts3Table *p;                   /* Virtual table handle */
129260  Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
129261
129262  UNUSED_PARAMETER(nVal);
129263
129264  assert( nVal==1 );
129265  if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
129266  p = (Fts3Table *)pCursor->base.pVtab;
129267  assert( p );
129268
129269  rc = sqlite3Fts3Optimize(p);
129270
129271  switch( rc ){
129272    case SQLITE_OK:
129273      sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
129274      break;
129275    case SQLITE_DONE:
129276      sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
129277      break;
129278    default:
129279      sqlite3_result_error_code(pContext, rc);
129280      break;
129281  }
129282}
129283
129284/*
129285** Implementation of the matchinfo() function for FTS3
129286*/
129287static void fts3MatchinfoFunc(
129288  sqlite3_context *pContext,      /* SQLite function call context */
129289  int nVal,                       /* Size of argument array */
129290  sqlite3_value **apVal           /* Array of arguments */
129291){
129292  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
129293  assert( nVal==1 || nVal==2 );
129294  if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
129295    const char *zArg = 0;
129296    if( nVal>1 ){
129297      zArg = (const char *)sqlite3_value_text(apVal[1]);
129298    }
129299    sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
129300  }
129301}
129302
129303/*
129304** This routine implements the xFindFunction method for the FTS3
129305** virtual table.
129306*/
129307static int fts3FindFunctionMethod(
129308  sqlite3_vtab *pVtab,            /* Virtual table handle */
129309  int nArg,                       /* Number of SQL function arguments */
129310  const char *zName,              /* Name of SQL function */
129311  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
129312  void **ppArg                    /* Unused */
129313){
129314  struct Overloaded {
129315    const char *zName;
129316    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
129317  } aOverload[] = {
129318    { "snippet", fts3SnippetFunc },
129319    { "offsets", fts3OffsetsFunc },
129320    { "optimize", fts3OptimizeFunc },
129321    { "matchinfo", fts3MatchinfoFunc },
129322  };
129323  int i;                          /* Iterator variable */
129324
129325  UNUSED_PARAMETER(pVtab);
129326  UNUSED_PARAMETER(nArg);
129327  UNUSED_PARAMETER(ppArg);
129328
129329  for(i=0; i<SizeofArray(aOverload); i++){
129330    if( strcmp(zName, aOverload[i].zName)==0 ){
129331      *pxFunc = aOverload[i].xFunc;
129332      return 1;
129333    }
129334  }
129335
129336  /* No function of the specified name was found. Return 0. */
129337  return 0;
129338}
129339
129340/*
129341** Implementation of FTS3 xRename method. Rename an fts3 table.
129342*/
129343static int fts3RenameMethod(
129344  sqlite3_vtab *pVtab,            /* Virtual table handle */
129345  const char *zName               /* New name of table */
129346){
129347  Fts3Table *p = (Fts3Table *)pVtab;
129348  sqlite3 *db = p->db;            /* Database connection */
129349  int rc;                         /* Return Code */
129350
129351  /* At this point it must be known if the %_stat table exists or not.
129352  ** So bHasStat may not be 2.  */
129353  rc = fts3SetHasStat(p);
129354
129355  /* As it happens, the pending terms table is always empty here. This is
129356  ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
129357  ** always opens a savepoint transaction. And the xSavepoint() method
129358  ** flushes the pending terms table. But leave the (no-op) call to
129359  ** PendingTermsFlush() in in case that changes.
129360  */
129361  assert( p->nPendingData==0 );
129362  if( rc==SQLITE_OK ){
129363    rc = sqlite3Fts3PendingTermsFlush(p);
129364  }
129365
129366  if( p->zContentTbl==0 ){
129367    fts3DbExec(&rc, db,
129368      "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
129369      p->zDb, p->zName, zName
129370    );
129371  }
129372
129373  if( p->bHasDocsize ){
129374    fts3DbExec(&rc, db,
129375      "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
129376      p->zDb, p->zName, zName
129377    );
129378  }
129379  if( p->bHasStat ){
129380    fts3DbExec(&rc, db,
129381      "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
129382      p->zDb, p->zName, zName
129383    );
129384  }
129385  fts3DbExec(&rc, db,
129386    "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
129387    p->zDb, p->zName, zName
129388  );
129389  fts3DbExec(&rc, db,
129390    "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
129391    p->zDb, p->zName, zName
129392  );
129393  return rc;
129394}
129395
129396/*
129397** The xSavepoint() method.
129398**
129399** Flush the contents of the pending-terms table to disk.
129400*/
129401static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
129402  int rc = SQLITE_OK;
129403  UNUSED_PARAMETER(iSavepoint);
129404  assert( ((Fts3Table *)pVtab)->inTransaction );
129405  assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
129406  TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
129407  if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
129408    rc = fts3SyncMethod(pVtab);
129409  }
129410  return rc;
129411}
129412
129413/*
129414** The xRelease() method.
129415**
129416** This is a no-op.
129417*/
129418static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
129419  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
129420  UNUSED_PARAMETER(iSavepoint);
129421  UNUSED_PARAMETER(pVtab);
129422  assert( p->inTransaction );
129423  assert( p->mxSavepoint >= iSavepoint );
129424  TESTONLY( p->mxSavepoint = iSavepoint-1 );
129425  return SQLITE_OK;
129426}
129427
129428/*
129429** The xRollbackTo() method.
129430**
129431** Discard the contents of the pending terms table.
129432*/
129433static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
129434  Fts3Table *p = (Fts3Table*)pVtab;
129435  UNUSED_PARAMETER(iSavepoint);
129436  assert( p->inTransaction );
129437  assert( p->mxSavepoint >= iSavepoint );
129438  TESTONLY( p->mxSavepoint = iSavepoint );
129439  sqlite3Fts3PendingTermsClear(p);
129440  return SQLITE_OK;
129441}
129442
129443static const sqlite3_module fts3Module = {
129444  /* iVersion      */ 2,
129445  /* xCreate       */ fts3CreateMethod,
129446  /* xConnect      */ fts3ConnectMethod,
129447  /* xBestIndex    */ fts3BestIndexMethod,
129448  /* xDisconnect   */ fts3DisconnectMethod,
129449  /* xDestroy      */ fts3DestroyMethod,
129450  /* xOpen         */ fts3OpenMethod,
129451  /* xClose        */ fts3CloseMethod,
129452  /* xFilter       */ fts3FilterMethod,
129453  /* xNext         */ fts3NextMethod,
129454  /* xEof          */ fts3EofMethod,
129455  /* xColumn       */ fts3ColumnMethod,
129456  /* xRowid        */ fts3RowidMethod,
129457  /* xUpdate       */ fts3UpdateMethod,
129458  /* xBegin        */ fts3BeginMethod,
129459  /* xSync         */ fts3SyncMethod,
129460  /* xCommit       */ fts3CommitMethod,
129461  /* xRollback     */ fts3RollbackMethod,
129462  /* xFindFunction */ fts3FindFunctionMethod,
129463  /* xRename */       fts3RenameMethod,
129464  /* xSavepoint    */ fts3SavepointMethod,
129465  /* xRelease      */ fts3ReleaseMethod,
129466  /* xRollbackTo   */ fts3RollbackToMethod,
129467};
129468
129469/*
129470** This function is registered as the module destructor (called when an
129471** FTS3 enabled database connection is closed). It frees the memory
129472** allocated for the tokenizer hash table.
129473*/
129474static void hashDestroy(void *p){
129475  Fts3Hash *pHash = (Fts3Hash *)p;
129476  sqlite3Fts3HashClear(pHash);
129477  sqlite3_free(pHash);
129478}
129479
129480/*
129481** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
129482** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
129483** respectively. The following three forward declarations are for functions
129484** declared in these files used to retrieve the respective implementations.
129485**
129486** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
129487** to by the argument to point to the "simple" tokenizer implementation.
129488** And so on.
129489*/
129490SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
129491SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
129492#ifdef SQLITE_ENABLE_FTS4_UNICODE61
129493SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
129494#endif
129495#ifdef SQLITE_ENABLE_ICU
129496SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
129497#endif
129498
129499/*
129500** Initialize the fts3 extension. If this extension is built as part
129501** of the sqlite library, then this function is called directly by
129502** SQLite. If fts3 is built as a dynamically loadable extension, this
129503** function is called by the sqlite3_extension_init() entry point.
129504*/
129505SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
129506  int rc = SQLITE_OK;
129507  Fts3Hash *pHash = 0;
129508  const sqlite3_tokenizer_module *pSimple = 0;
129509  const sqlite3_tokenizer_module *pPorter = 0;
129510#ifdef SQLITE_ENABLE_FTS4_UNICODE61
129511  const sqlite3_tokenizer_module *pUnicode = 0;
129512#endif
129513
129514#ifdef SQLITE_ENABLE_ICU
129515  const sqlite3_tokenizer_module *pIcu = 0;
129516  sqlite3Fts3IcuTokenizerModule(&pIcu);
129517#endif
129518
129519#ifdef SQLITE_ENABLE_FTS4_UNICODE61
129520  sqlite3Fts3UnicodeTokenizer(&pUnicode);
129521#endif
129522
129523#ifdef SQLITE_TEST
129524  rc = sqlite3Fts3InitTerm(db);
129525  if( rc!=SQLITE_OK ) return rc;
129526#endif
129527
129528  rc = sqlite3Fts3InitAux(db);
129529  if( rc!=SQLITE_OK ) return rc;
129530
129531  sqlite3Fts3SimpleTokenizerModule(&pSimple);
129532  sqlite3Fts3PorterTokenizerModule(&pPorter);
129533
129534  /* Allocate and initialize the hash-table used to store tokenizers. */
129535  pHash = sqlite3_malloc(sizeof(Fts3Hash));
129536  if( !pHash ){
129537    rc = SQLITE_NOMEM;
129538  }else{
129539    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
129540  }
129541
129542  /* Load the built-in tokenizers into the hash table */
129543  if( rc==SQLITE_OK ){
129544    if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
129545     || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
129546
129547#ifdef SQLITE_ENABLE_FTS4_UNICODE61
129548     || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
129549#endif
129550#ifdef SQLITE_ENABLE_ICU
129551     || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
129552#endif
129553    ){
129554      rc = SQLITE_NOMEM;
129555    }
129556  }
129557
129558#ifdef SQLITE_TEST
129559  if( rc==SQLITE_OK ){
129560    rc = sqlite3Fts3ExprInitTestInterface(db);
129561  }
129562#endif
129563
129564  /* Create the virtual table wrapper around the hash-table and overload
129565  ** the two scalar functions. If this is successful, register the
129566  ** module with sqlite.
129567  */
129568  if( SQLITE_OK==rc
129569   && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
129570   && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
129571   && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
129572   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
129573   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
129574   && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
129575  ){
129576    rc = sqlite3_create_module_v2(
129577        db, "fts3", &fts3Module, (void *)pHash, hashDestroy
129578    );
129579    if( rc==SQLITE_OK ){
129580      rc = sqlite3_create_module_v2(
129581          db, "fts4", &fts3Module, (void *)pHash, 0
129582      );
129583    }
129584    if( rc==SQLITE_OK ){
129585      rc = sqlite3Fts3InitTok(db, (void *)pHash);
129586    }
129587    return rc;
129588  }
129589
129590
129591  /* An error has occurred. Delete the hash table and return the error code. */
129592  assert( rc!=SQLITE_OK );
129593  if( pHash ){
129594    sqlite3Fts3HashClear(pHash);
129595    sqlite3_free(pHash);
129596  }
129597  return rc;
129598}
129599
129600/*
129601** Allocate an Fts3MultiSegReader for each token in the expression headed
129602** by pExpr.
129603**
129604** An Fts3SegReader object is a cursor that can seek or scan a range of
129605** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
129606** Fts3SegReader objects internally to provide an interface to seek or scan
129607** within the union of all segments of a b-tree. Hence the name.
129608**
129609** If the allocated Fts3MultiSegReader just seeks to a single entry in a
129610** segment b-tree (if the term is not a prefix or it is a prefix for which
129611** there exists prefix b-tree of the right length) then it may be traversed
129612** and merged incrementally. Otherwise, it has to be merged into an in-memory
129613** doclist and then traversed.
129614*/
129615static void fts3EvalAllocateReaders(
129616  Fts3Cursor *pCsr,               /* FTS cursor handle */
129617  Fts3Expr *pExpr,                /* Allocate readers for this expression */
129618  int *pnToken,                   /* OUT: Total number of tokens in phrase. */
129619  int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
129620  int *pRc                        /* IN/OUT: Error code */
129621){
129622  if( pExpr && SQLITE_OK==*pRc ){
129623    if( pExpr->eType==FTSQUERY_PHRASE ){
129624      int i;
129625      int nToken = pExpr->pPhrase->nToken;
129626      *pnToken += nToken;
129627      for(i=0; i<nToken; i++){
129628        Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
129629        int rc = fts3TermSegReaderCursor(pCsr,
129630            pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
129631        );
129632        if( rc!=SQLITE_OK ){
129633          *pRc = rc;
129634          return;
129635        }
129636      }
129637      assert( pExpr->pPhrase->iDoclistToken==0 );
129638      pExpr->pPhrase->iDoclistToken = -1;
129639    }else{
129640      *pnOr += (pExpr->eType==FTSQUERY_OR);
129641      fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
129642      fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
129643    }
129644  }
129645}
129646
129647/*
129648** Arguments pList/nList contain the doclist for token iToken of phrase p.
129649** It is merged into the main doclist stored in p->doclist.aAll/nAll.
129650**
129651** This function assumes that pList points to a buffer allocated using
129652** sqlite3_malloc(). This function takes responsibility for eventually
129653** freeing the buffer.
129654*/
129655static void fts3EvalPhraseMergeToken(
129656  Fts3Table *pTab,                /* FTS Table pointer */
129657  Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
129658  int iToken,                     /* Token pList/nList corresponds to */
129659  char *pList,                    /* Pointer to doclist */
129660  int nList                       /* Number of bytes in pList */
129661){
129662  assert( iToken!=p->iDoclistToken );
129663
129664  if( pList==0 ){
129665    sqlite3_free(p->doclist.aAll);
129666    p->doclist.aAll = 0;
129667    p->doclist.nAll = 0;
129668  }
129669
129670  else if( p->iDoclistToken<0 ){
129671    p->doclist.aAll = pList;
129672    p->doclist.nAll = nList;
129673  }
129674
129675  else if( p->doclist.aAll==0 ){
129676    sqlite3_free(pList);
129677  }
129678
129679  else {
129680    char *pLeft;
129681    char *pRight;
129682    int nLeft;
129683    int nRight;
129684    int nDiff;
129685
129686    if( p->iDoclistToken<iToken ){
129687      pLeft = p->doclist.aAll;
129688      nLeft = p->doclist.nAll;
129689      pRight = pList;
129690      nRight = nList;
129691      nDiff = iToken - p->iDoclistToken;
129692    }else{
129693      pRight = p->doclist.aAll;
129694      nRight = p->doclist.nAll;
129695      pLeft = pList;
129696      nLeft = nList;
129697      nDiff = p->iDoclistToken - iToken;
129698    }
129699
129700    fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
129701    sqlite3_free(pLeft);
129702    p->doclist.aAll = pRight;
129703    p->doclist.nAll = nRight;
129704  }
129705
129706  if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
129707}
129708
129709/*
129710** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
129711** does not take deferred tokens into account.
129712**
129713** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
129714*/
129715static int fts3EvalPhraseLoad(
129716  Fts3Cursor *pCsr,               /* FTS Cursor handle */
129717  Fts3Phrase *p                   /* Phrase object */
129718){
129719  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
129720  int iToken;
129721  int rc = SQLITE_OK;
129722
129723  for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
129724    Fts3PhraseToken *pToken = &p->aToken[iToken];
129725    assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
129726
129727    if( pToken->pSegcsr ){
129728      int nThis = 0;
129729      char *pThis = 0;
129730      rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
129731      if( rc==SQLITE_OK ){
129732        fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
129733      }
129734    }
129735    assert( pToken->pSegcsr==0 );
129736  }
129737
129738  return rc;
129739}
129740
129741/*
129742** This function is called on each phrase after the position lists for
129743** any deferred tokens have been loaded into memory. It updates the phrases
129744** current position list to include only those positions that are really
129745** instances of the phrase (after considering deferred tokens). If this
129746** means that the phrase does not appear in the current row, doclist.pList
129747** and doclist.nList are both zeroed.
129748**
129749** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
129750*/
129751static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
129752  int iToken;                     /* Used to iterate through phrase tokens */
129753  char *aPoslist = 0;             /* Position list for deferred tokens */
129754  int nPoslist = 0;               /* Number of bytes in aPoslist */
129755  int iPrev = -1;                 /* Token number of previous deferred token */
129756
129757  assert( pPhrase->doclist.bFreeList==0 );
129758
129759  for(iToken=0; iToken<pPhrase->nToken; iToken++){
129760    Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
129761    Fts3DeferredToken *pDeferred = pToken->pDeferred;
129762
129763    if( pDeferred ){
129764      char *pList;
129765      int nList;
129766      int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
129767      if( rc!=SQLITE_OK ) return rc;
129768
129769      if( pList==0 ){
129770        sqlite3_free(aPoslist);
129771        pPhrase->doclist.pList = 0;
129772        pPhrase->doclist.nList = 0;
129773        return SQLITE_OK;
129774
129775      }else if( aPoslist==0 ){
129776        aPoslist = pList;
129777        nPoslist = nList;
129778
129779      }else{
129780        char *aOut = pList;
129781        char *p1 = aPoslist;
129782        char *p2 = aOut;
129783
129784        assert( iPrev>=0 );
129785        fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
129786        sqlite3_free(aPoslist);
129787        aPoslist = pList;
129788        nPoslist = (int)(aOut - aPoslist);
129789        if( nPoslist==0 ){
129790          sqlite3_free(aPoslist);
129791          pPhrase->doclist.pList = 0;
129792          pPhrase->doclist.nList = 0;
129793          return SQLITE_OK;
129794        }
129795      }
129796      iPrev = iToken;
129797    }
129798  }
129799
129800  if( iPrev>=0 ){
129801    int nMaxUndeferred = pPhrase->iDoclistToken;
129802    if( nMaxUndeferred<0 ){
129803      pPhrase->doclist.pList = aPoslist;
129804      pPhrase->doclist.nList = nPoslist;
129805      pPhrase->doclist.iDocid = pCsr->iPrevId;
129806      pPhrase->doclist.bFreeList = 1;
129807    }else{
129808      int nDistance;
129809      char *p1;
129810      char *p2;
129811      char *aOut;
129812
129813      if( nMaxUndeferred>iPrev ){
129814        p1 = aPoslist;
129815        p2 = pPhrase->doclist.pList;
129816        nDistance = nMaxUndeferred - iPrev;
129817      }else{
129818        p1 = pPhrase->doclist.pList;
129819        p2 = aPoslist;
129820        nDistance = iPrev - nMaxUndeferred;
129821      }
129822
129823      aOut = (char *)sqlite3_malloc(nPoslist+8);
129824      if( !aOut ){
129825        sqlite3_free(aPoslist);
129826        return SQLITE_NOMEM;
129827      }
129828
129829      pPhrase->doclist.pList = aOut;
129830      if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
129831        pPhrase->doclist.bFreeList = 1;
129832        pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
129833      }else{
129834        sqlite3_free(aOut);
129835        pPhrase->doclist.pList = 0;
129836        pPhrase->doclist.nList = 0;
129837      }
129838      sqlite3_free(aPoslist);
129839    }
129840  }
129841
129842  return SQLITE_OK;
129843}
129844
129845/*
129846** Maximum number of tokens a phrase may have to be considered for the
129847** incremental doclists strategy.
129848*/
129849#define MAX_INCR_PHRASE_TOKENS 4
129850
129851/*
129852** This function is called for each Fts3Phrase in a full-text query
129853** expression to initialize the mechanism for returning rows. Once this
129854** function has been called successfully on an Fts3Phrase, it may be
129855** used with fts3EvalPhraseNext() to iterate through the matching docids.
129856**
129857** If parameter bOptOk is true, then the phrase may (or may not) use the
129858** incremental loading strategy. Otherwise, the entire doclist is loaded into
129859** memory within this call.
129860**
129861** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
129862*/
129863static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
129864  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
129865  int rc = SQLITE_OK;             /* Error code */
129866  int i;
129867
129868  /* Determine if doclists may be loaded from disk incrementally. This is
129869  ** possible if the bOptOk argument is true, the FTS doclists will be
129870  ** scanned in forward order, and the phrase consists of
129871  ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
129872  ** tokens or prefix tokens that cannot use a prefix-index.  */
129873  int bHaveIncr = 0;
129874  int bIncrOk = (bOptOk
129875   && pCsr->bDesc==pTab->bDescIdx
129876   && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
129877   && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
129878#ifdef SQLITE_TEST
129879   && pTab->bNoIncrDoclist==0
129880#endif
129881  );
129882  for(i=0; bIncrOk==1 && i<p->nToken; i++){
129883    Fts3PhraseToken *pToken = &p->aToken[i];
129884    if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
129885      bIncrOk = 0;
129886    }
129887    if( pToken->pSegcsr ) bHaveIncr = 1;
129888  }
129889
129890  if( bIncrOk && bHaveIncr ){
129891    /* Use the incremental approach. */
129892    int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
129893    for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
129894      Fts3PhraseToken *pToken = &p->aToken[i];
129895      Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
129896      if( pSegcsr ){
129897        rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
129898      }
129899    }
129900    p->bIncr = 1;
129901  }else{
129902    /* Load the full doclist for the phrase into memory. */
129903    rc = fts3EvalPhraseLoad(pCsr, p);
129904    p->bIncr = 0;
129905  }
129906
129907  assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
129908  return rc;
129909}
129910
129911/*
129912** This function is used to iterate backwards (from the end to start)
129913** through doclists. It is used by this module to iterate through phrase
129914** doclists in reverse and by the fts3_write.c module to iterate through
129915** pending-terms lists when writing to databases with "order=desc".
129916**
129917** The doclist may be sorted in ascending (parameter bDescIdx==0) or
129918** descending (parameter bDescIdx==1) order of docid. Regardless, this
129919** function iterates from the end of the doclist to the beginning.
129920*/
129921SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
129922  int bDescIdx,                   /* True if the doclist is desc */
129923  char *aDoclist,                 /* Pointer to entire doclist */
129924  int nDoclist,                   /* Length of aDoclist in bytes */
129925  char **ppIter,                  /* IN/OUT: Iterator pointer */
129926  sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
129927  int *pnList,                    /* OUT: List length pointer */
129928  u8 *pbEof                       /* OUT: End-of-file flag */
129929){
129930  char *p = *ppIter;
129931
129932  assert( nDoclist>0 );
129933  assert( *pbEof==0 );
129934  assert( p || *piDocid==0 );
129935  assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
129936
129937  if( p==0 ){
129938    sqlite3_int64 iDocid = 0;
129939    char *pNext = 0;
129940    char *pDocid = aDoclist;
129941    char *pEnd = &aDoclist[nDoclist];
129942    int iMul = 1;
129943
129944    while( pDocid<pEnd ){
129945      sqlite3_int64 iDelta;
129946      pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
129947      iDocid += (iMul * iDelta);
129948      pNext = pDocid;
129949      fts3PoslistCopy(0, &pDocid);
129950      while( pDocid<pEnd && *pDocid==0 ) pDocid++;
129951      iMul = (bDescIdx ? -1 : 1);
129952    }
129953
129954    *pnList = (int)(pEnd - pNext);
129955    *ppIter = pNext;
129956    *piDocid = iDocid;
129957  }else{
129958    int iMul = (bDescIdx ? -1 : 1);
129959    sqlite3_int64 iDelta;
129960    fts3GetReverseVarint(&p, aDoclist, &iDelta);
129961    *piDocid -= (iMul * iDelta);
129962
129963    if( p==aDoclist ){
129964      *pbEof = 1;
129965    }else{
129966      char *pSave = p;
129967      fts3ReversePoslist(aDoclist, &p);
129968      *pnList = (int)(pSave - p);
129969    }
129970    *ppIter = p;
129971  }
129972}
129973
129974/*
129975** Iterate forwards through a doclist.
129976*/
129977SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
129978  int bDescIdx,                   /* True if the doclist is desc */
129979  char *aDoclist,                 /* Pointer to entire doclist */
129980  int nDoclist,                   /* Length of aDoclist in bytes */
129981  char **ppIter,                  /* IN/OUT: Iterator pointer */
129982  sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
129983  u8 *pbEof                       /* OUT: End-of-file flag */
129984){
129985  char *p = *ppIter;
129986
129987  assert( nDoclist>0 );
129988  assert( *pbEof==0 );
129989  assert( p || *piDocid==0 );
129990  assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
129991
129992  if( p==0 ){
129993    p = aDoclist;
129994    p += sqlite3Fts3GetVarint(p, piDocid);
129995  }else{
129996    fts3PoslistCopy(0, &p);
129997    if( p>=&aDoclist[nDoclist] ){
129998      *pbEof = 1;
129999    }else{
130000      sqlite3_int64 iVar;
130001      p += sqlite3Fts3GetVarint(p, &iVar);
130002      *piDocid += ((bDescIdx ? -1 : 1) * iVar);
130003    }
130004  }
130005
130006  *ppIter = p;
130007}
130008
130009/*
130010** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
130011** to true if EOF is reached.
130012*/
130013static void fts3EvalDlPhraseNext(
130014  Fts3Table *pTab,
130015  Fts3Doclist *pDL,
130016  u8 *pbEof
130017){
130018  char *pIter;                            /* Used to iterate through aAll */
130019  char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
130020
130021  if( pDL->pNextDocid ){
130022    pIter = pDL->pNextDocid;
130023  }else{
130024    pIter = pDL->aAll;
130025  }
130026
130027  if( pIter>=pEnd ){
130028    /* We have already reached the end of this doclist. EOF. */
130029    *pbEof = 1;
130030  }else{
130031    sqlite3_int64 iDelta;
130032    pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
130033    if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
130034      pDL->iDocid += iDelta;
130035    }else{
130036      pDL->iDocid -= iDelta;
130037    }
130038    pDL->pList = pIter;
130039    fts3PoslistCopy(0, &pIter);
130040    pDL->nList = (int)(pIter - pDL->pList);
130041
130042    /* pIter now points just past the 0x00 that terminates the position-
130043    ** list for document pDL->iDocid. However, if this position-list was
130044    ** edited in place by fts3EvalNearTrim(), then pIter may not actually
130045    ** point to the start of the next docid value. The following line deals
130046    ** with this case by advancing pIter past the zero-padding added by
130047    ** fts3EvalNearTrim().  */
130048    while( pIter<pEnd && *pIter==0 ) pIter++;
130049
130050    pDL->pNextDocid = pIter;
130051    assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
130052    *pbEof = 0;
130053  }
130054}
130055
130056/*
130057** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
130058*/
130059typedef struct TokenDoclist TokenDoclist;
130060struct TokenDoclist {
130061  int bIgnore;
130062  sqlite3_int64 iDocid;
130063  char *pList;
130064  int nList;
130065};
130066
130067/*
130068** Token pToken is an incrementally loaded token that is part of a
130069** multi-token phrase. Advance it to the next matching document in the
130070** database and populate output variable *p with the details of the new
130071** entry. Or, if the iterator has reached EOF, set *pbEof to true.
130072**
130073** If an error occurs, return an SQLite error code. Otherwise, return
130074** SQLITE_OK.
130075*/
130076static int incrPhraseTokenNext(
130077  Fts3Table *pTab,                /* Virtual table handle */
130078  Fts3Phrase *pPhrase,            /* Phrase to advance token of */
130079  int iToken,                     /* Specific token to advance */
130080  TokenDoclist *p,                /* OUT: Docid and doclist for new entry */
130081  u8 *pbEof                       /* OUT: True if iterator is at EOF */
130082){
130083  int rc = SQLITE_OK;
130084
130085  if( pPhrase->iDoclistToken==iToken ){
130086    assert( p->bIgnore==0 );
130087    assert( pPhrase->aToken[iToken].pSegcsr==0 );
130088    fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
130089    p->pList = pPhrase->doclist.pList;
130090    p->nList = pPhrase->doclist.nList;
130091    p->iDocid = pPhrase->doclist.iDocid;
130092  }else{
130093    Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
130094    assert( pToken->pDeferred==0 );
130095    assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
130096    if( pToken->pSegcsr ){
130097      assert( p->bIgnore==0 );
130098      rc = sqlite3Fts3MsrIncrNext(
130099          pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
130100      );
130101      if( p->pList==0 ) *pbEof = 1;
130102    }else{
130103      p->bIgnore = 1;
130104    }
130105  }
130106
130107  return rc;
130108}
130109
130110
130111/*
130112** The phrase iterator passed as the second argument:
130113**
130114**   * features at least one token that uses an incremental doclist, and
130115**
130116**   * does not contain any deferred tokens.
130117**
130118** Advance it to the next matching documnent in the database and populate
130119** the Fts3Doclist.pList and nList fields.
130120**
130121** If there is no "next" entry and no error occurs, then *pbEof is set to
130122** 1 before returning. Otherwise, if no error occurs and the iterator is
130123** successfully advanced, *pbEof is set to 0.
130124**
130125** If an error occurs, return an SQLite error code. Otherwise, return
130126** SQLITE_OK.
130127*/
130128static int fts3EvalIncrPhraseNext(
130129  Fts3Cursor *pCsr,               /* FTS Cursor handle */
130130  Fts3Phrase *p,                  /* Phrase object to advance to next docid */
130131  u8 *pbEof                       /* OUT: Set to 1 if EOF */
130132){
130133  int rc = SQLITE_OK;
130134  Fts3Doclist *pDL = &p->doclist;
130135  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
130136  u8 bEof = 0;
130137
130138  /* This is only called if it is guaranteed that the phrase has at least
130139  ** one incremental token. In which case the bIncr flag is set. */
130140  assert( p->bIncr==1 );
130141
130142  if( p->nToken==1 && p->bIncr ){
130143    rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
130144        &pDL->iDocid, &pDL->pList, &pDL->nList
130145    );
130146    if( pDL->pList==0 ) bEof = 1;
130147  }else{
130148    int bDescDoclist = pCsr->bDesc;
130149    struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
130150
130151    memset(a, 0, sizeof(a));
130152    assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
130153    assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
130154
130155    while( bEof==0 ){
130156      int bMaxSet = 0;
130157      sqlite3_int64 iMax = 0;     /* Largest docid for all iterators */
130158      int i;                      /* Used to iterate through tokens */
130159
130160      /* Advance the iterator for each token in the phrase once. */
130161      for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
130162        rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
130163        if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
130164          iMax = a[i].iDocid;
130165          bMaxSet = 1;
130166        }
130167      }
130168      assert( rc!=SQLITE_OK || a[p->nToken-1].bIgnore==0 );
130169      assert( rc!=SQLITE_OK || bMaxSet );
130170
130171      /* Keep advancing iterators until they all point to the same document */
130172      for(i=0; i<p->nToken; i++){
130173        while( rc==SQLITE_OK && bEof==0
130174            && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
130175        ){
130176          rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
130177          if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
130178            iMax = a[i].iDocid;
130179            i = 0;
130180          }
130181        }
130182      }
130183
130184      /* Check if the current entries really are a phrase match */
130185      if( bEof==0 ){
130186        int nList = 0;
130187        int nByte = a[p->nToken-1].nList;
130188        char *aDoclist = sqlite3_malloc(nByte+1);
130189        if( !aDoclist ) return SQLITE_NOMEM;
130190        memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
130191
130192        for(i=0; i<(p->nToken-1); i++){
130193          if( a[i].bIgnore==0 ){
130194            char *pL = a[i].pList;
130195            char *pR = aDoclist;
130196            char *pOut = aDoclist;
130197            int nDist = p->nToken-1-i;
130198            int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
130199            if( res==0 ) break;
130200            nList = (int)(pOut - aDoclist);
130201          }
130202        }
130203        if( i==(p->nToken-1) ){
130204          pDL->iDocid = iMax;
130205          pDL->pList = aDoclist;
130206          pDL->nList = nList;
130207          pDL->bFreeList = 1;
130208          break;
130209        }
130210        sqlite3_free(aDoclist);
130211      }
130212    }
130213  }
130214
130215  *pbEof = bEof;
130216  return rc;
130217}
130218
130219/*
130220** Attempt to move the phrase iterator to point to the next matching docid.
130221** If an error occurs, return an SQLite error code. Otherwise, return
130222** SQLITE_OK.
130223**
130224** If there is no "next" entry and no error occurs, then *pbEof is set to
130225** 1 before returning. Otherwise, if no error occurs and the iterator is
130226** successfully advanced, *pbEof is set to 0.
130227*/
130228static int fts3EvalPhraseNext(
130229  Fts3Cursor *pCsr,               /* FTS Cursor handle */
130230  Fts3Phrase *p,                  /* Phrase object to advance to next docid */
130231  u8 *pbEof                       /* OUT: Set to 1 if EOF */
130232){
130233  int rc = SQLITE_OK;
130234  Fts3Doclist *pDL = &p->doclist;
130235  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
130236
130237  if( p->bIncr ){
130238    rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
130239  }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
130240    sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
130241        &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
130242    );
130243    pDL->pList = pDL->pNextDocid;
130244  }else{
130245    fts3EvalDlPhraseNext(pTab, pDL, pbEof);
130246  }
130247
130248  return rc;
130249}
130250
130251/*
130252**
130253** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
130254** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
130255** expression. Also the Fts3Expr.bDeferred variable is set to true for any
130256** expressions for which all descendent tokens are deferred.
130257**
130258** If parameter bOptOk is zero, then it is guaranteed that the
130259** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
130260** each phrase in the expression (subject to deferred token processing).
130261** Or, if bOptOk is non-zero, then one or more tokens within the expression
130262** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
130263**
130264** If an error occurs within this function, *pRc is set to an SQLite error
130265** code before returning.
130266*/
130267static void fts3EvalStartReaders(
130268  Fts3Cursor *pCsr,               /* FTS Cursor handle */
130269  Fts3Expr *pExpr,                /* Expression to initialize phrases in */
130270  int *pRc                        /* IN/OUT: Error code */
130271){
130272  if( pExpr && SQLITE_OK==*pRc ){
130273    if( pExpr->eType==FTSQUERY_PHRASE ){
130274      int i;
130275      int nToken = pExpr->pPhrase->nToken;
130276      for(i=0; i<nToken; i++){
130277        if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
130278      }
130279      pExpr->bDeferred = (i==nToken);
130280      *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
130281    }else{
130282      fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
130283      fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
130284      pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
130285    }
130286  }
130287}
130288
130289/*
130290** An array of the following structures is assembled as part of the process
130291** of selecting tokens to defer before the query starts executing (as part
130292** of the xFilter() method). There is one element in the array for each
130293** token in the FTS expression.
130294**
130295** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
130296** to phrases that are connected only by AND and NEAR operators (not OR or
130297** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
130298** separately. The root of a tokens AND/NEAR cluster is stored in
130299** Fts3TokenAndCost.pRoot.
130300*/
130301typedef struct Fts3TokenAndCost Fts3TokenAndCost;
130302struct Fts3TokenAndCost {
130303  Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
130304  int iToken;                     /* Position of token in phrase */
130305  Fts3PhraseToken *pToken;        /* The token itself */
130306  Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
130307  int nOvfl;                      /* Number of overflow pages to load doclist */
130308  int iCol;                       /* The column the token must match */
130309};
130310
130311/*
130312** This function is used to populate an allocated Fts3TokenAndCost array.
130313**
130314** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
130315** Otherwise, if an error occurs during execution, *pRc is set to an
130316** SQLite error code.
130317*/
130318static void fts3EvalTokenCosts(
130319  Fts3Cursor *pCsr,               /* FTS Cursor handle */
130320  Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
130321  Fts3Expr *pExpr,                /* Expression to consider */
130322  Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
130323  Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
130324  int *pRc                        /* IN/OUT: Error code */
130325){
130326  if( *pRc==SQLITE_OK ){
130327    if( pExpr->eType==FTSQUERY_PHRASE ){
130328      Fts3Phrase *pPhrase = pExpr->pPhrase;
130329      int i;
130330      for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
130331        Fts3TokenAndCost *pTC = (*ppTC)++;
130332        pTC->pPhrase = pPhrase;
130333        pTC->iToken = i;
130334        pTC->pRoot = pRoot;
130335        pTC->pToken = &pPhrase->aToken[i];
130336        pTC->iCol = pPhrase->iColumn;
130337        *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
130338      }
130339    }else if( pExpr->eType!=FTSQUERY_NOT ){
130340      assert( pExpr->eType==FTSQUERY_OR
130341           || pExpr->eType==FTSQUERY_AND
130342           || pExpr->eType==FTSQUERY_NEAR
130343      );
130344      assert( pExpr->pLeft && pExpr->pRight );
130345      if( pExpr->eType==FTSQUERY_OR ){
130346        pRoot = pExpr->pLeft;
130347        **ppOr = pRoot;
130348        (*ppOr)++;
130349      }
130350      fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
130351      if( pExpr->eType==FTSQUERY_OR ){
130352        pRoot = pExpr->pRight;
130353        **ppOr = pRoot;
130354        (*ppOr)++;
130355      }
130356      fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
130357    }
130358  }
130359}
130360
130361/*
130362** Determine the average document (row) size in pages. If successful,
130363** write this value to *pnPage and return SQLITE_OK. Otherwise, return
130364** an SQLite error code.
130365**
130366** The average document size in pages is calculated by first calculating
130367** determining the average size in bytes, B. If B is less than the amount
130368** of data that will fit on a single leaf page of an intkey table in
130369** this database, then the average docsize is 1. Otherwise, it is 1 plus
130370** the number of overflow pages consumed by a record B bytes in size.
130371*/
130372static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
130373  if( pCsr->nRowAvg==0 ){
130374    /* The average document size, which is required to calculate the cost
130375    ** of each doclist, has not yet been determined. Read the required
130376    ** data from the %_stat table to calculate it.
130377    **
130378    ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
130379    ** varints, where nCol is the number of columns in the FTS3 table.
130380    ** The first varint is the number of documents currently stored in
130381    ** the table. The following nCol varints contain the total amount of
130382    ** data stored in all rows of each column of the table, from left
130383    ** to right.
130384    */
130385    int rc;
130386    Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
130387    sqlite3_stmt *pStmt;
130388    sqlite3_int64 nDoc = 0;
130389    sqlite3_int64 nByte = 0;
130390    const char *pEnd;
130391    const char *a;
130392
130393    rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
130394    if( rc!=SQLITE_OK ) return rc;
130395    a = sqlite3_column_blob(pStmt, 0);
130396    assert( a );
130397
130398    pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
130399    a += sqlite3Fts3GetVarint(a, &nDoc);
130400    while( a<pEnd ){
130401      a += sqlite3Fts3GetVarint(a, &nByte);
130402    }
130403    if( nDoc==0 || nByte==0 ){
130404      sqlite3_reset(pStmt);
130405      return FTS_CORRUPT_VTAB;
130406    }
130407
130408    pCsr->nDoc = nDoc;
130409    pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
130410    assert( pCsr->nRowAvg>0 );
130411    rc = sqlite3_reset(pStmt);
130412    if( rc!=SQLITE_OK ) return rc;
130413  }
130414
130415  *pnPage = pCsr->nRowAvg;
130416  return SQLITE_OK;
130417}
130418
130419/*
130420** This function is called to select the tokens (if any) that will be
130421** deferred. The array aTC[] has already been populated when this is
130422** called.
130423**
130424** This function is called once for each AND/NEAR cluster in the
130425** expression. Each invocation determines which tokens to defer within
130426** the cluster with root node pRoot. See comments above the definition
130427** of struct Fts3TokenAndCost for more details.
130428**
130429** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
130430** called on each token to defer. Otherwise, an SQLite error code is
130431** returned.
130432*/
130433static int fts3EvalSelectDeferred(
130434  Fts3Cursor *pCsr,               /* FTS Cursor handle */
130435  Fts3Expr *pRoot,                /* Consider tokens with this root node */
130436  Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
130437  int nTC                         /* Number of entries in aTC[] */
130438){
130439  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
130440  int nDocSize = 0;               /* Number of pages per doc loaded */
130441  int rc = SQLITE_OK;             /* Return code */
130442  int ii;                         /* Iterator variable for various purposes */
130443  int nOvfl = 0;                  /* Total overflow pages used by doclists */
130444  int nToken = 0;                 /* Total number of tokens in cluster */
130445
130446  int nMinEst = 0;                /* The minimum count for any phrase so far. */
130447  int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
130448
130449  /* Tokens are never deferred for FTS tables created using the content=xxx
130450  ** option. The reason being that it is not guaranteed that the content
130451  ** table actually contains the same data as the index. To prevent this from
130452  ** causing any problems, the deferred token optimization is completely
130453  ** disabled for content=xxx tables. */
130454  if( pTab->zContentTbl ){
130455    return SQLITE_OK;
130456  }
130457
130458  /* Count the tokens in this AND/NEAR cluster. If none of the doclists
130459  ** associated with the tokens spill onto overflow pages, or if there is
130460  ** only 1 token, exit early. No tokens to defer in this case. */
130461  for(ii=0; ii<nTC; ii++){
130462    if( aTC[ii].pRoot==pRoot ){
130463      nOvfl += aTC[ii].nOvfl;
130464      nToken++;
130465    }
130466  }
130467  if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
130468
130469  /* Obtain the average docsize (in pages). */
130470  rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
130471  assert( rc!=SQLITE_OK || nDocSize>0 );
130472
130473
130474  /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
130475  ** of the number of overflow pages that will be loaded by the pager layer
130476  ** to retrieve the entire doclist for the token from the full-text index.
130477  ** Load the doclists for tokens that are either:
130478  **
130479  **   a. The cheapest token in the entire query (i.e. the one visited by the
130480  **      first iteration of this loop), or
130481  **
130482  **   b. Part of a multi-token phrase.
130483  **
130484  ** After each token doclist is loaded, merge it with the others from the
130485  ** same phrase and count the number of documents that the merged doclist
130486  ** contains. Set variable "nMinEst" to the smallest number of documents in
130487  ** any phrase doclist for which 1 or more token doclists have been loaded.
130488  ** Let nOther be the number of other phrases for which it is certain that
130489  ** one or more tokens will not be deferred.
130490  **
130491  ** Then, for each token, defer it if loading the doclist would result in
130492  ** loading N or more overflow pages into memory, where N is computed as:
130493  **
130494  **    (nMinEst + 4^nOther - 1) / (4^nOther)
130495  */
130496  for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
130497    int iTC;                      /* Used to iterate through aTC[] array. */
130498    Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
130499
130500    /* Set pTC to point to the cheapest remaining token. */
130501    for(iTC=0; iTC<nTC; iTC++){
130502      if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
130503       && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
130504      ){
130505        pTC = &aTC[iTC];
130506      }
130507    }
130508    assert( pTC );
130509
130510    if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
130511      /* The number of overflow pages to load for this (and therefore all
130512      ** subsequent) tokens is greater than the estimated number of pages
130513      ** that will be loaded if all subsequent tokens are deferred.
130514      */
130515      Fts3PhraseToken *pToken = pTC->pToken;
130516      rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
130517      fts3SegReaderCursorFree(pToken->pSegcsr);
130518      pToken->pSegcsr = 0;
130519    }else{
130520      /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
130521      ** for-loop. Except, limit the value to 2^24 to prevent it from
130522      ** overflowing the 32-bit integer it is stored in. */
130523      if( ii<12 ) nLoad4 = nLoad4*4;
130524
130525      if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
130526        /* Either this is the cheapest token in the entire query, or it is
130527        ** part of a multi-token phrase. Either way, the entire doclist will
130528        ** (eventually) be loaded into memory. It may as well be now. */
130529        Fts3PhraseToken *pToken = pTC->pToken;
130530        int nList = 0;
130531        char *pList = 0;
130532        rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
130533        assert( rc==SQLITE_OK || pList==0 );
130534        if( rc==SQLITE_OK ){
130535          int nCount;
130536          fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
130537          nCount = fts3DoclistCountDocids(
130538              pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
130539          );
130540          if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
130541        }
130542      }
130543    }
130544    pTC->pToken = 0;
130545  }
130546
130547  return rc;
130548}
130549
130550/*
130551** This function is called from within the xFilter method. It initializes
130552** the full-text query currently stored in pCsr->pExpr. To iterate through
130553** the results of a query, the caller does:
130554**
130555**    fts3EvalStart(pCsr);
130556**    while( 1 ){
130557**      fts3EvalNext(pCsr);
130558**      if( pCsr->bEof ) break;
130559**      ... return row pCsr->iPrevId to the caller ...
130560**    }
130561*/
130562static int fts3EvalStart(Fts3Cursor *pCsr){
130563  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
130564  int rc = SQLITE_OK;
130565  int nToken = 0;
130566  int nOr = 0;
130567
130568  /* Allocate a MultiSegReader for each token in the expression. */
130569  fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
130570
130571  /* Determine which, if any, tokens in the expression should be deferred. */
130572#ifndef SQLITE_DISABLE_FTS4_DEFERRED
130573  if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
130574    Fts3TokenAndCost *aTC;
130575    Fts3Expr **apOr;
130576    aTC = (Fts3TokenAndCost *)sqlite3_malloc(
130577        sizeof(Fts3TokenAndCost) * nToken
130578      + sizeof(Fts3Expr *) * nOr * 2
130579    );
130580    apOr = (Fts3Expr **)&aTC[nToken];
130581
130582    if( !aTC ){
130583      rc = SQLITE_NOMEM;
130584    }else{
130585      int ii;
130586      Fts3TokenAndCost *pTC = aTC;
130587      Fts3Expr **ppOr = apOr;
130588
130589      fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
130590      nToken = (int)(pTC-aTC);
130591      nOr = (int)(ppOr-apOr);
130592
130593      if( rc==SQLITE_OK ){
130594        rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
130595        for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
130596          rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
130597        }
130598      }
130599
130600      sqlite3_free(aTC);
130601    }
130602  }
130603#endif
130604
130605  fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
130606  return rc;
130607}
130608
130609/*
130610** Invalidate the current position list for phrase pPhrase.
130611*/
130612static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
130613  if( pPhrase->doclist.bFreeList ){
130614    sqlite3_free(pPhrase->doclist.pList);
130615  }
130616  pPhrase->doclist.pList = 0;
130617  pPhrase->doclist.nList = 0;
130618  pPhrase->doclist.bFreeList = 0;
130619}
130620
130621/*
130622** This function is called to edit the position list associated with
130623** the phrase object passed as the fifth argument according to a NEAR
130624** condition. For example:
130625**
130626**     abc NEAR/5 "def ghi"
130627**
130628** Parameter nNear is passed the NEAR distance of the expression (5 in
130629** the example above). When this function is called, *paPoslist points to
130630** the position list, and *pnToken is the number of phrase tokens in, the
130631** phrase on the other side of the NEAR operator to pPhrase. For example,
130632** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
130633** the position list associated with phrase "abc".
130634**
130635** All positions in the pPhrase position list that are not sufficiently
130636** close to a position in the *paPoslist position list are removed. If this
130637** leaves 0 positions, zero is returned. Otherwise, non-zero.
130638**
130639** Before returning, *paPoslist is set to point to the position lsit
130640** associated with pPhrase. And *pnToken is set to the number of tokens in
130641** pPhrase.
130642*/
130643static int fts3EvalNearTrim(
130644  int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
130645  char *aTmp,                     /* Temporary space to use */
130646  char **paPoslist,               /* IN/OUT: Position list */
130647  int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
130648  Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
130649){
130650  int nParam1 = nNear + pPhrase->nToken;
130651  int nParam2 = nNear + *pnToken;
130652  int nNew;
130653  char *p2;
130654  char *pOut;
130655  int res;
130656
130657  assert( pPhrase->doclist.pList );
130658
130659  p2 = pOut = pPhrase->doclist.pList;
130660  res = fts3PoslistNearMerge(
130661    &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
130662  );
130663  if( res ){
130664    nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
130665    assert( pPhrase->doclist.pList[nNew]=='\0' );
130666    assert( nNew<=pPhrase->doclist.nList && nNew>0 );
130667    memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
130668    pPhrase->doclist.nList = nNew;
130669    *paPoslist = pPhrase->doclist.pList;
130670    *pnToken = pPhrase->nToken;
130671  }
130672
130673  return res;
130674}
130675
130676/*
130677** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
130678** Otherwise, it advances the expression passed as the second argument to
130679** point to the next matching row in the database. Expressions iterate through
130680** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
130681** or descending if it is non-zero.
130682**
130683** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
130684** successful, the following variables in pExpr are set:
130685**
130686**   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
130687**   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
130688**
130689** If the expression is of type FTSQUERY_PHRASE, and the expression is not
130690** at EOF, then the following variables are populated with the position list
130691** for the phrase for the visited row:
130692**
130693**   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
130694**   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
130695**
130696** It says above that this function advances the expression to the next
130697** matching row. This is usually true, but there are the following exceptions:
130698**
130699**   1. Deferred tokens are not taken into account. If a phrase consists
130700**      entirely of deferred tokens, it is assumed to match every row in
130701**      the db. In this case the position-list is not populated at all.
130702**
130703**      Or, if a phrase contains one or more deferred tokens and one or
130704**      more non-deferred tokens, then the expression is advanced to the
130705**      next possible match, considering only non-deferred tokens. In other
130706**      words, if the phrase is "A B C", and "B" is deferred, the expression
130707**      is advanced to the next row that contains an instance of "A * C",
130708**      where "*" may match any single token. The position list in this case
130709**      is populated as for "A * C" before returning.
130710**
130711**   2. NEAR is treated as AND. If the expression is "x NEAR y", it is
130712**      advanced to point to the next row that matches "x AND y".
130713**
130714** See fts3EvalTestDeferredAndNear() for details on testing if a row is
130715** really a match, taking into account deferred tokens and NEAR operators.
130716*/
130717static void fts3EvalNextRow(
130718  Fts3Cursor *pCsr,               /* FTS Cursor handle */
130719  Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
130720  int *pRc                        /* IN/OUT: Error code */
130721){
130722  if( *pRc==SQLITE_OK ){
130723    int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
130724    assert( pExpr->bEof==0 );
130725    pExpr->bStart = 1;
130726
130727    switch( pExpr->eType ){
130728      case FTSQUERY_NEAR:
130729      case FTSQUERY_AND: {
130730        Fts3Expr *pLeft = pExpr->pLeft;
130731        Fts3Expr *pRight = pExpr->pRight;
130732        assert( !pLeft->bDeferred || !pRight->bDeferred );
130733
130734        if( pLeft->bDeferred ){
130735          /* LHS is entirely deferred. So we assume it matches every row.
130736          ** Advance the RHS iterator to find the next row visited. */
130737          fts3EvalNextRow(pCsr, pRight, pRc);
130738          pExpr->iDocid = pRight->iDocid;
130739          pExpr->bEof = pRight->bEof;
130740        }else if( pRight->bDeferred ){
130741          /* RHS is entirely deferred. So we assume it matches every row.
130742          ** Advance the LHS iterator to find the next row visited. */
130743          fts3EvalNextRow(pCsr, pLeft, pRc);
130744          pExpr->iDocid = pLeft->iDocid;
130745          pExpr->bEof = pLeft->bEof;
130746        }else{
130747          /* Neither the RHS or LHS are deferred. */
130748          fts3EvalNextRow(pCsr, pLeft, pRc);
130749          fts3EvalNextRow(pCsr, pRight, pRc);
130750          while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
130751            sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
130752            if( iDiff==0 ) break;
130753            if( iDiff<0 ){
130754              fts3EvalNextRow(pCsr, pLeft, pRc);
130755            }else{
130756              fts3EvalNextRow(pCsr, pRight, pRc);
130757            }
130758          }
130759          pExpr->iDocid = pLeft->iDocid;
130760          pExpr->bEof = (pLeft->bEof || pRight->bEof);
130761        }
130762        break;
130763      }
130764
130765      case FTSQUERY_OR: {
130766        Fts3Expr *pLeft = pExpr->pLeft;
130767        Fts3Expr *pRight = pExpr->pRight;
130768        sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
130769
130770        assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
130771        assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
130772
130773        if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
130774          fts3EvalNextRow(pCsr, pLeft, pRc);
130775        }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
130776          fts3EvalNextRow(pCsr, pRight, pRc);
130777        }else{
130778          fts3EvalNextRow(pCsr, pLeft, pRc);
130779          fts3EvalNextRow(pCsr, pRight, pRc);
130780        }
130781
130782        pExpr->bEof = (pLeft->bEof && pRight->bEof);
130783        iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
130784        if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
130785          pExpr->iDocid = pLeft->iDocid;
130786        }else{
130787          pExpr->iDocid = pRight->iDocid;
130788        }
130789
130790        break;
130791      }
130792
130793      case FTSQUERY_NOT: {
130794        Fts3Expr *pLeft = pExpr->pLeft;
130795        Fts3Expr *pRight = pExpr->pRight;
130796
130797        if( pRight->bStart==0 ){
130798          fts3EvalNextRow(pCsr, pRight, pRc);
130799          assert( *pRc!=SQLITE_OK || pRight->bStart );
130800        }
130801
130802        fts3EvalNextRow(pCsr, pLeft, pRc);
130803        if( pLeft->bEof==0 ){
130804          while( !*pRc
130805              && !pRight->bEof
130806              && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
130807          ){
130808            fts3EvalNextRow(pCsr, pRight, pRc);
130809          }
130810        }
130811        pExpr->iDocid = pLeft->iDocid;
130812        pExpr->bEof = pLeft->bEof;
130813        break;
130814      }
130815
130816      default: {
130817        Fts3Phrase *pPhrase = pExpr->pPhrase;
130818        fts3EvalInvalidatePoslist(pPhrase);
130819        *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
130820        pExpr->iDocid = pPhrase->doclist.iDocid;
130821        break;
130822      }
130823    }
130824  }
130825}
130826
130827/*
130828** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
130829** cluster, then this function returns 1 immediately.
130830**
130831** Otherwise, it checks if the current row really does match the NEAR
130832** expression, using the data currently stored in the position lists
130833** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
130834**
130835** If the current row is a match, the position list associated with each
130836** phrase in the NEAR expression is edited in place to contain only those
130837** phrase instances sufficiently close to their peers to satisfy all NEAR
130838** constraints. In this case it returns 1. If the NEAR expression does not
130839** match the current row, 0 is returned. The position lists may or may not
130840** be edited if 0 is returned.
130841*/
130842static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
130843  int res = 1;
130844
130845  /* The following block runs if pExpr is the root of a NEAR query.
130846  ** For example, the query:
130847  **
130848  **         "w" NEAR "x" NEAR "y" NEAR "z"
130849  **
130850  ** which is represented in tree form as:
130851  **
130852  **                               |
130853  **                          +--NEAR--+      <-- root of NEAR query
130854  **                          |        |
130855  **                     +--NEAR--+   "z"
130856  **                     |        |
130857  **                +--NEAR--+   "y"
130858  **                |        |
130859  **               "w"      "x"
130860  **
130861  ** The right-hand child of a NEAR node is always a phrase. The
130862  ** left-hand child may be either a phrase or a NEAR node. There are
130863  ** no exceptions to this - it's the way the parser in fts3_expr.c works.
130864  */
130865  if( *pRc==SQLITE_OK
130866   && pExpr->eType==FTSQUERY_NEAR
130867   && pExpr->bEof==0
130868   && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
130869  ){
130870    Fts3Expr *p;
130871    int nTmp = 0;                 /* Bytes of temp space */
130872    char *aTmp;                   /* Temp space for PoslistNearMerge() */
130873
130874    /* Allocate temporary working space. */
130875    for(p=pExpr; p->pLeft; p=p->pLeft){
130876      nTmp += p->pRight->pPhrase->doclist.nList;
130877    }
130878    nTmp += p->pPhrase->doclist.nList;
130879    if( nTmp==0 ){
130880      res = 0;
130881    }else{
130882      aTmp = sqlite3_malloc(nTmp*2);
130883      if( !aTmp ){
130884        *pRc = SQLITE_NOMEM;
130885        res = 0;
130886      }else{
130887        char *aPoslist = p->pPhrase->doclist.pList;
130888        int nToken = p->pPhrase->nToken;
130889
130890        for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
130891          Fts3Phrase *pPhrase = p->pRight->pPhrase;
130892          int nNear = p->nNear;
130893          res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
130894        }
130895
130896        aPoslist = pExpr->pRight->pPhrase->doclist.pList;
130897        nToken = pExpr->pRight->pPhrase->nToken;
130898        for(p=pExpr->pLeft; p && res; p=p->pLeft){
130899          int nNear;
130900          Fts3Phrase *pPhrase;
130901          assert( p->pParent && p->pParent->pLeft==p );
130902          nNear = p->pParent->nNear;
130903          pPhrase = (
130904              p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
130905              );
130906          res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
130907        }
130908      }
130909
130910      sqlite3_free(aTmp);
130911    }
130912  }
130913
130914  return res;
130915}
130916
130917/*
130918** This function is a helper function for fts3EvalTestDeferredAndNear().
130919** Assuming no error occurs or has occurred, It returns non-zero if the
130920** expression passed as the second argument matches the row that pCsr
130921** currently points to, or zero if it does not.
130922**
130923** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
130924** If an error occurs during execution of this function, *pRc is set to
130925** the appropriate SQLite error code. In this case the returned value is
130926** undefined.
130927*/
130928static int fts3EvalTestExpr(
130929  Fts3Cursor *pCsr,               /* FTS cursor handle */
130930  Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
130931  int *pRc                        /* IN/OUT: Error code */
130932){
130933  int bHit = 1;                   /* Return value */
130934  if( *pRc==SQLITE_OK ){
130935    switch( pExpr->eType ){
130936      case FTSQUERY_NEAR:
130937      case FTSQUERY_AND:
130938        bHit = (
130939            fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
130940         && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
130941         && fts3EvalNearTest(pExpr, pRc)
130942        );
130943
130944        /* If the NEAR expression does not match any rows, zero the doclist for
130945        ** all phrases involved in the NEAR. This is because the snippet(),
130946        ** offsets() and matchinfo() functions are not supposed to recognize
130947        ** any instances of phrases that are part of unmatched NEAR queries.
130948        ** For example if this expression:
130949        **
130950        **    ... MATCH 'a OR (b NEAR c)'
130951        **
130952        ** is matched against a row containing:
130953        **
130954        **        'a b d e'
130955        **
130956        ** then any snippet() should ony highlight the "a" term, not the "b"
130957        ** (as "b" is part of a non-matching NEAR clause).
130958        */
130959        if( bHit==0
130960         && pExpr->eType==FTSQUERY_NEAR
130961         && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
130962        ){
130963          Fts3Expr *p;
130964          for(p=pExpr; p->pPhrase==0; p=p->pLeft){
130965            if( p->pRight->iDocid==pCsr->iPrevId ){
130966              fts3EvalInvalidatePoslist(p->pRight->pPhrase);
130967            }
130968          }
130969          if( p->iDocid==pCsr->iPrevId ){
130970            fts3EvalInvalidatePoslist(p->pPhrase);
130971          }
130972        }
130973
130974        break;
130975
130976      case FTSQUERY_OR: {
130977        int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
130978        int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
130979        bHit = bHit1 || bHit2;
130980        break;
130981      }
130982
130983      case FTSQUERY_NOT:
130984        bHit = (
130985            fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
130986         && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
130987        );
130988        break;
130989
130990      default: {
130991#ifndef SQLITE_DISABLE_FTS4_DEFERRED
130992        if( pCsr->pDeferred
130993         && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
130994        ){
130995          Fts3Phrase *pPhrase = pExpr->pPhrase;
130996          assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
130997          if( pExpr->bDeferred ){
130998            fts3EvalInvalidatePoslist(pPhrase);
130999          }
131000          *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
131001          bHit = (pPhrase->doclist.pList!=0);
131002          pExpr->iDocid = pCsr->iPrevId;
131003        }else
131004#endif
131005        {
131006          bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
131007        }
131008        break;
131009      }
131010    }
131011  }
131012  return bHit;
131013}
131014
131015/*
131016** This function is called as the second part of each xNext operation when
131017** iterating through the results of a full-text query. At this point the
131018** cursor points to a row that matches the query expression, with the
131019** following caveats:
131020**
131021**   * Up until this point, "NEAR" operators in the expression have been
131022**     treated as "AND".
131023**
131024**   * Deferred tokens have not yet been considered.
131025**
131026** If *pRc is not SQLITE_OK when this function is called, it immediately
131027** returns 0. Otherwise, it tests whether or not after considering NEAR
131028** operators and deferred tokens the current row is still a match for the
131029** expression. It returns 1 if both of the following are true:
131030**
131031**   1. *pRc is SQLITE_OK when this function returns, and
131032**
131033**   2. After scanning the current FTS table row for the deferred tokens,
131034**      it is determined that the row does *not* match the query.
131035**
131036** Or, if no error occurs and it seems the current row does match the FTS
131037** query, return 0.
131038*/
131039static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
131040  int rc = *pRc;
131041  int bMiss = 0;
131042  if( rc==SQLITE_OK ){
131043
131044    /* If there are one or more deferred tokens, load the current row into
131045    ** memory and scan it to determine the position list for each deferred
131046    ** token. Then, see if this row is really a match, considering deferred
131047    ** tokens and NEAR operators (neither of which were taken into account
131048    ** earlier, by fts3EvalNextRow()).
131049    */
131050    if( pCsr->pDeferred ){
131051      rc = fts3CursorSeek(0, pCsr);
131052      if( rc==SQLITE_OK ){
131053        rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
131054      }
131055    }
131056    bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
131057
131058    /* Free the position-lists accumulated for each deferred token above. */
131059    sqlite3Fts3FreeDeferredDoclists(pCsr);
131060    *pRc = rc;
131061  }
131062  return (rc==SQLITE_OK && bMiss);
131063}
131064
131065/*
131066** Advance to the next document that matches the FTS expression in
131067** Fts3Cursor.pExpr.
131068*/
131069static int fts3EvalNext(Fts3Cursor *pCsr){
131070  int rc = SQLITE_OK;             /* Return Code */
131071  Fts3Expr *pExpr = pCsr->pExpr;
131072  assert( pCsr->isEof==0 );
131073  if( pExpr==0 ){
131074    pCsr->isEof = 1;
131075  }else{
131076    do {
131077      if( pCsr->isRequireSeek==0 ){
131078        sqlite3_reset(pCsr->pStmt);
131079      }
131080      assert( sqlite3_data_count(pCsr->pStmt)==0 );
131081      fts3EvalNextRow(pCsr, pExpr, &rc);
131082      pCsr->isEof = pExpr->bEof;
131083      pCsr->isRequireSeek = 1;
131084      pCsr->isMatchinfoNeeded = 1;
131085      pCsr->iPrevId = pExpr->iDocid;
131086    }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
131087  }
131088
131089  /* Check if the cursor is past the end of the docid range specified
131090  ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag.  */
131091  if( rc==SQLITE_OK && (
131092        (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
131093     || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
131094  )){
131095    pCsr->isEof = 1;
131096  }
131097
131098  return rc;
131099}
131100
131101/*
131102** Restart interation for expression pExpr so that the next call to
131103** fts3EvalNext() visits the first row. Do not allow incremental
131104** loading or merging of phrase doclists for this iteration.
131105**
131106** If *pRc is other than SQLITE_OK when this function is called, it is
131107** a no-op. If an error occurs within this function, *pRc is set to an
131108** SQLite error code before returning.
131109*/
131110static void fts3EvalRestart(
131111  Fts3Cursor *pCsr,
131112  Fts3Expr *pExpr,
131113  int *pRc
131114){
131115  if( pExpr && *pRc==SQLITE_OK ){
131116    Fts3Phrase *pPhrase = pExpr->pPhrase;
131117
131118    if( pPhrase ){
131119      fts3EvalInvalidatePoslist(pPhrase);
131120      if( pPhrase->bIncr ){
131121        int i;
131122        for(i=0; i<pPhrase->nToken; i++){
131123          Fts3PhraseToken *pToken = &pPhrase->aToken[i];
131124          assert( pToken->pDeferred==0 );
131125          if( pToken->pSegcsr ){
131126            sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
131127          }
131128        }
131129        *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
131130      }
131131      pPhrase->doclist.pNextDocid = 0;
131132      pPhrase->doclist.iDocid = 0;
131133    }
131134
131135    pExpr->iDocid = 0;
131136    pExpr->bEof = 0;
131137    pExpr->bStart = 0;
131138
131139    fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
131140    fts3EvalRestart(pCsr, pExpr->pRight, pRc);
131141  }
131142}
131143
131144/*
131145** After allocating the Fts3Expr.aMI[] array for each phrase in the
131146** expression rooted at pExpr, the cursor iterates through all rows matched
131147** by pExpr, calling this function for each row. This function increments
131148** the values in Fts3Expr.aMI[] according to the position-list currently
131149** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
131150** expression nodes.
131151*/
131152static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
131153  if( pExpr ){
131154    Fts3Phrase *pPhrase = pExpr->pPhrase;
131155    if( pPhrase && pPhrase->doclist.pList ){
131156      int iCol = 0;
131157      char *p = pPhrase->doclist.pList;
131158
131159      assert( *p );
131160      while( 1 ){
131161        u8 c = 0;
131162        int iCnt = 0;
131163        while( 0xFE & (*p | c) ){
131164          if( (c&0x80)==0 ) iCnt++;
131165          c = *p++ & 0x80;
131166        }
131167
131168        /* aMI[iCol*3 + 1] = Number of occurrences
131169        ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
131170        */
131171        pExpr->aMI[iCol*3 + 1] += iCnt;
131172        pExpr->aMI[iCol*3 + 2] += (iCnt>0);
131173        if( *p==0x00 ) break;
131174        p++;
131175        p += fts3GetVarint32(p, &iCol);
131176      }
131177    }
131178
131179    fts3EvalUpdateCounts(pExpr->pLeft);
131180    fts3EvalUpdateCounts(pExpr->pRight);
131181  }
131182}
131183
131184/*
131185** Expression pExpr must be of type FTSQUERY_PHRASE.
131186**
131187** If it is not already allocated and populated, this function allocates and
131188** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
131189** of a NEAR expression, then it also allocates and populates the same array
131190** for all other phrases that are part of the NEAR expression.
131191**
131192** SQLITE_OK is returned if the aMI[] array is successfully allocated and
131193** populated. Otherwise, if an error occurs, an SQLite error code is returned.
131194*/
131195static int fts3EvalGatherStats(
131196  Fts3Cursor *pCsr,               /* Cursor object */
131197  Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
131198){
131199  int rc = SQLITE_OK;             /* Return code */
131200
131201  assert( pExpr->eType==FTSQUERY_PHRASE );
131202  if( pExpr->aMI==0 ){
131203    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
131204    Fts3Expr *pRoot;                /* Root of NEAR expression */
131205    Fts3Expr *p;                    /* Iterator used for several purposes */
131206
131207    sqlite3_int64 iPrevId = pCsr->iPrevId;
131208    sqlite3_int64 iDocid;
131209    u8 bEof;
131210
131211    /* Find the root of the NEAR expression */
131212    pRoot = pExpr;
131213    while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
131214      pRoot = pRoot->pParent;
131215    }
131216    iDocid = pRoot->iDocid;
131217    bEof = pRoot->bEof;
131218    assert( pRoot->bStart );
131219
131220    /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
131221    for(p=pRoot; p; p=p->pLeft){
131222      Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
131223      assert( pE->aMI==0 );
131224      pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
131225      if( !pE->aMI ) return SQLITE_NOMEM;
131226      memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
131227    }
131228
131229    fts3EvalRestart(pCsr, pRoot, &rc);
131230
131231    while( pCsr->isEof==0 && rc==SQLITE_OK ){
131232
131233      do {
131234        /* Ensure the %_content statement is reset. */
131235        if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
131236        assert( sqlite3_data_count(pCsr->pStmt)==0 );
131237
131238        /* Advance to the next document */
131239        fts3EvalNextRow(pCsr, pRoot, &rc);
131240        pCsr->isEof = pRoot->bEof;
131241        pCsr->isRequireSeek = 1;
131242        pCsr->isMatchinfoNeeded = 1;
131243        pCsr->iPrevId = pRoot->iDocid;
131244      }while( pCsr->isEof==0
131245           && pRoot->eType==FTSQUERY_NEAR
131246           && fts3EvalTestDeferredAndNear(pCsr, &rc)
131247      );
131248
131249      if( rc==SQLITE_OK && pCsr->isEof==0 ){
131250        fts3EvalUpdateCounts(pRoot);
131251      }
131252    }
131253
131254    pCsr->isEof = 0;
131255    pCsr->iPrevId = iPrevId;
131256
131257    if( bEof ){
131258      pRoot->bEof = bEof;
131259    }else{
131260      /* Caution: pRoot may iterate through docids in ascending or descending
131261      ** order. For this reason, even though it seems more defensive, the
131262      ** do loop can not be written:
131263      **
131264      **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
131265      */
131266      fts3EvalRestart(pCsr, pRoot, &rc);
131267      do {
131268        fts3EvalNextRow(pCsr, pRoot, &rc);
131269        assert( pRoot->bEof==0 );
131270      }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
131271      fts3EvalTestDeferredAndNear(pCsr, &rc);
131272    }
131273  }
131274  return rc;
131275}
131276
131277/*
131278** This function is used by the matchinfo() module to query a phrase
131279** expression node for the following information:
131280**
131281**   1. The total number of occurrences of the phrase in each column of
131282**      the FTS table (considering all rows), and
131283**
131284**   2. For each column, the number of rows in the table for which the
131285**      column contains at least one instance of the phrase.
131286**
131287** If no error occurs, SQLITE_OK is returned and the values for each column
131288** written into the array aiOut as follows:
131289**
131290**   aiOut[iCol*3 + 1] = Number of occurrences
131291**   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
131292**
131293** Caveats:
131294**
131295**   * If a phrase consists entirely of deferred tokens, then all output
131296**     values are set to the number of documents in the table. In other
131297**     words we assume that very common tokens occur exactly once in each
131298**     column of each row of the table.
131299**
131300**   * If a phrase contains some deferred tokens (and some non-deferred
131301**     tokens), count the potential occurrence identified by considering
131302**     the non-deferred tokens instead of actual phrase occurrences.
131303**
131304**   * If the phrase is part of a NEAR expression, then only phrase instances
131305**     that meet the NEAR constraint are included in the counts.
131306*/
131307SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
131308  Fts3Cursor *pCsr,               /* FTS cursor handle */
131309  Fts3Expr *pExpr,                /* Phrase expression */
131310  u32 *aiOut                      /* Array to write results into (see above) */
131311){
131312  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
131313  int rc = SQLITE_OK;
131314  int iCol;
131315
131316  if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
131317    assert( pCsr->nDoc>0 );
131318    for(iCol=0; iCol<pTab->nColumn; iCol++){
131319      aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
131320      aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
131321    }
131322  }else{
131323    rc = fts3EvalGatherStats(pCsr, pExpr);
131324    if( rc==SQLITE_OK ){
131325      assert( pExpr->aMI );
131326      for(iCol=0; iCol<pTab->nColumn; iCol++){
131327        aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
131328        aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
131329      }
131330    }
131331  }
131332
131333  return rc;
131334}
131335
131336/*
131337** The expression pExpr passed as the second argument to this function
131338** must be of type FTSQUERY_PHRASE.
131339**
131340** The returned value is either NULL or a pointer to a buffer containing
131341** a position-list indicating the occurrences of the phrase in column iCol
131342** of the current row.
131343**
131344** More specifically, the returned buffer contains 1 varint for each
131345** occurrence of the phrase in the column, stored using the normal (delta+2)
131346** compression and is terminated by either an 0x01 or 0x00 byte. For example,
131347** if the requested column contains "a b X c d X X" and the position-list
131348** for 'X' is requested, the buffer returned may contain:
131349**
131350**     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
131351**
131352** This function works regardless of whether or not the phrase is deferred,
131353** incremental, or neither.
131354*/
131355SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
131356  Fts3Cursor *pCsr,               /* FTS3 cursor object */
131357  Fts3Expr *pExpr,                /* Phrase to return doclist for */
131358  int iCol,                       /* Column to return position list for */
131359  char **ppOut                    /* OUT: Pointer to position list */
131360){
131361  Fts3Phrase *pPhrase = pExpr->pPhrase;
131362  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
131363  char *pIter;
131364  int iThis;
131365  sqlite3_int64 iDocid;
131366
131367  /* If this phrase is applies specifically to some column other than
131368  ** column iCol, return a NULL pointer.  */
131369  *ppOut = 0;
131370  assert( iCol>=0 && iCol<pTab->nColumn );
131371  if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
131372    return SQLITE_OK;
131373  }
131374
131375  iDocid = pExpr->iDocid;
131376  pIter = pPhrase->doclist.pList;
131377  if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
131378    int bDescDoclist = pTab->bDescIdx;      /* For DOCID_CMP macro */
131379    int iMul;                     /* +1 if csr dir matches index dir, else -1 */
131380    int bOr = 0;
131381    u8 bEof = 0;
131382    u8 bTreeEof = 0;
131383    Fts3Expr *p;                  /* Used to iterate from pExpr to root */
131384    Fts3Expr *pNear;              /* Most senior NEAR ancestor (or pExpr) */
131385
131386    /* Check if this phrase descends from an OR expression node. If not,
131387    ** return NULL. Otherwise, the entry that corresponds to docid
131388    ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
131389    ** tree that the node is part of has been marked as EOF, but the node
131390    ** itself is not EOF, then it may point to an earlier entry. */
131391    pNear = pExpr;
131392    for(p=pExpr->pParent; p; p=p->pParent){
131393      if( p->eType==FTSQUERY_OR ) bOr = 1;
131394      if( p->eType==FTSQUERY_NEAR ) pNear = p;
131395      if( p->bEof ) bTreeEof = 1;
131396    }
131397    if( bOr==0 ) return SQLITE_OK;
131398
131399    /* This is the descendent of an OR node. In this case we cannot use
131400    ** an incremental phrase. Load the entire doclist for the phrase
131401    ** into memory in this case.  */
131402    if( pPhrase->bIncr ){
131403      int rc = SQLITE_OK;
131404      int bEofSave = pExpr->bEof;
131405      fts3EvalRestart(pCsr, pExpr, &rc);
131406      while( rc==SQLITE_OK && !pExpr->bEof ){
131407        fts3EvalNextRow(pCsr, pExpr, &rc);
131408        if( bEofSave==0 && pExpr->iDocid==iDocid ) break;
131409      }
131410      pIter = pPhrase->doclist.pList;
131411      assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
131412      if( rc!=SQLITE_OK ) return rc;
131413    }
131414
131415    iMul = ((pCsr->bDesc==bDescDoclist) ? 1 : -1);
131416    while( bTreeEof==1
131417        && pNear->bEof==0
131418        && (DOCID_CMP(pNear->iDocid, pCsr->iPrevId) * iMul)<0
131419    ){
131420      int rc = SQLITE_OK;
131421      fts3EvalNextRow(pCsr, pExpr, &rc);
131422      if( rc!=SQLITE_OK ) return rc;
131423      iDocid = pExpr->iDocid;
131424      pIter = pPhrase->doclist.pList;
131425    }
131426
131427    bEof = (pPhrase->doclist.nAll==0);
131428    assert( bDescDoclist==0 || bDescDoclist==1 );
131429    assert( pCsr->bDesc==0 || pCsr->bDesc==1 );
131430
131431    if( bEof==0 ){
131432      if( pCsr->bDesc==bDescDoclist ){
131433        int dummy;
131434        if( pNear->bEof ){
131435          /* This expression is already at EOF. So position it to point to the
131436          ** last entry in the doclist at pPhrase->doclist.aAll[]. Variable
131437          ** iDocid is already set for this entry, so all that is required is
131438          ** to set pIter to point to the first byte of the last position-list
131439          ** in the doclist.
131440          **
131441          ** It would also be correct to set pIter and iDocid to zero. In
131442          ** this case, the first call to sqltie3Fts4DoclistPrev() below
131443          ** would also move the iterator to point to the last entry in the
131444          ** doclist. However, this is expensive, as to do so it has to
131445          ** iterate through the entire doclist from start to finish (since
131446          ** it does not know the docid for the last entry).  */
131447          pIter = &pPhrase->doclist.aAll[pPhrase->doclist.nAll-1];
131448          fts3ReversePoslist(pPhrase->doclist.aAll, &pIter);
131449        }
131450        while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
131451          sqlite3Fts3DoclistPrev(
131452              bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
131453              &pIter, &iDocid, &dummy, &bEof
131454          );
131455        }
131456      }else{
131457        if( pNear->bEof ){
131458          pIter = 0;
131459          iDocid = 0;
131460        }
131461        while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
131462          sqlite3Fts3DoclistNext(
131463              bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
131464              &pIter, &iDocid, &bEof
131465          );
131466        }
131467      }
131468    }
131469
131470    if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0;
131471  }
131472  if( pIter==0 ) return SQLITE_OK;
131473
131474  if( *pIter==0x01 ){
131475    pIter++;
131476    pIter += fts3GetVarint32(pIter, &iThis);
131477  }else{
131478    iThis = 0;
131479  }
131480  while( iThis<iCol ){
131481    fts3ColumnlistCopy(0, &pIter);
131482    if( *pIter==0x00 ) return 0;
131483    pIter++;
131484    pIter += fts3GetVarint32(pIter, &iThis);
131485  }
131486
131487  *ppOut = ((iCol==iThis)?pIter:0);
131488  return SQLITE_OK;
131489}
131490
131491/*
131492** Free all components of the Fts3Phrase structure that were allocated by
131493** the eval module. Specifically, this means to free:
131494**
131495**   * the contents of pPhrase->doclist, and
131496**   * any Fts3MultiSegReader objects held by phrase tokens.
131497*/
131498SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
131499  if( pPhrase ){
131500    int i;
131501    sqlite3_free(pPhrase->doclist.aAll);
131502    fts3EvalInvalidatePoslist(pPhrase);
131503    memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
131504    for(i=0; i<pPhrase->nToken; i++){
131505      fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
131506      pPhrase->aToken[i].pSegcsr = 0;
131507    }
131508  }
131509}
131510
131511
131512/*
131513** Return SQLITE_CORRUPT_VTAB.
131514*/
131515#ifdef SQLITE_DEBUG
131516SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
131517  return SQLITE_CORRUPT_VTAB;
131518}
131519#endif
131520
131521#if !SQLITE_CORE
131522/*
131523** Initialize API pointer table, if required.
131524*/
131525#ifdef _WIN32
131526__declspec(dllexport)
131527#endif
131528SQLITE_API int sqlite3_fts3_init(
131529  sqlite3 *db,
131530  char **pzErrMsg,
131531  const sqlite3_api_routines *pApi
131532){
131533  SQLITE_EXTENSION_INIT2(pApi)
131534  return sqlite3Fts3Init(db);
131535}
131536#endif
131537
131538#endif
131539
131540/************** End of fts3.c ************************************************/
131541/************** Begin file fts3_aux.c ****************************************/
131542/*
131543** 2011 Jan 27
131544**
131545** The author disclaims copyright to this source code.  In place of
131546** a legal notice, here is a blessing:
131547**
131548**    May you do good and not evil.
131549**    May you find forgiveness for yourself and forgive others.
131550**    May you share freely, never taking more than you give.
131551**
131552******************************************************************************
131553**
131554*/
131555#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
131556
131557/* #include <string.h> */
131558/* #include <assert.h> */
131559
131560typedef struct Fts3auxTable Fts3auxTable;
131561typedef struct Fts3auxCursor Fts3auxCursor;
131562
131563struct Fts3auxTable {
131564  sqlite3_vtab base;              /* Base class used by SQLite core */
131565  Fts3Table *pFts3Tab;
131566};
131567
131568struct Fts3auxCursor {
131569  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
131570  Fts3MultiSegReader csr;        /* Must be right after "base" */
131571  Fts3SegFilter filter;
131572  char *zStop;
131573  int nStop;                      /* Byte-length of string zStop */
131574  int iLangid;                    /* Language id to query */
131575  int isEof;                      /* True if cursor is at EOF */
131576  sqlite3_int64 iRowid;           /* Current rowid */
131577
131578  int iCol;                       /* Current value of 'col' column */
131579  int nStat;                      /* Size of aStat[] array */
131580  struct Fts3auxColstats {
131581    sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
131582    sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
131583  } *aStat;
131584};
131585
131586/*
131587** Schema of the terms table.
131588*/
131589#define FTS3_AUX_SCHEMA \
131590  "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
131591
131592/*
131593** This function does all the work for both the xConnect and xCreate methods.
131594** These tables have no persistent representation of their own, so xConnect
131595** and xCreate are identical operations.
131596*/
131597static int fts3auxConnectMethod(
131598  sqlite3 *db,                    /* Database connection */
131599  void *pUnused,                  /* Unused */
131600  int argc,                       /* Number of elements in argv array */
131601  const char * const *argv,       /* xCreate/xConnect argument array */
131602  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
131603  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
131604){
131605  char const *zDb;                /* Name of database (e.g. "main") */
131606  char const *zFts3;              /* Name of fts3 table */
131607  int nDb;                        /* Result of strlen(zDb) */
131608  int nFts3;                      /* Result of strlen(zFts3) */
131609  int nByte;                      /* Bytes of space to allocate here */
131610  int rc;                         /* value returned by declare_vtab() */
131611  Fts3auxTable *p;                /* Virtual table object to return */
131612
131613  UNUSED_PARAMETER(pUnused);
131614
131615  /* The user should invoke this in one of two forms:
131616  **
131617  **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
131618  **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
131619  */
131620  if( argc!=4 && argc!=5 ) goto bad_args;
131621
131622  zDb = argv[1];
131623  nDb = (int)strlen(zDb);
131624  if( argc==5 ){
131625    if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
131626      zDb = argv[3];
131627      nDb = (int)strlen(zDb);
131628      zFts3 = argv[4];
131629    }else{
131630      goto bad_args;
131631    }
131632  }else{
131633    zFts3 = argv[3];
131634  }
131635  nFts3 = (int)strlen(zFts3);
131636
131637  rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
131638  if( rc!=SQLITE_OK ) return rc;
131639
131640  nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
131641  p = (Fts3auxTable *)sqlite3_malloc(nByte);
131642  if( !p ) return SQLITE_NOMEM;
131643  memset(p, 0, nByte);
131644
131645  p->pFts3Tab = (Fts3Table *)&p[1];
131646  p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
131647  p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
131648  p->pFts3Tab->db = db;
131649  p->pFts3Tab->nIndex = 1;
131650
131651  memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
131652  memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
131653  sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
131654
131655  *ppVtab = (sqlite3_vtab *)p;
131656  return SQLITE_OK;
131657
131658 bad_args:
131659  *pzErr = sqlite3_mprintf("invalid arguments to fts4aux constructor");
131660  return SQLITE_ERROR;
131661}
131662
131663/*
131664** This function does the work for both the xDisconnect and xDestroy methods.
131665** These tables have no persistent representation of their own, so xDisconnect
131666** and xDestroy are identical operations.
131667*/
131668static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
131669  Fts3auxTable *p = (Fts3auxTable *)pVtab;
131670  Fts3Table *pFts3 = p->pFts3Tab;
131671  int i;
131672
131673  /* Free any prepared statements held */
131674  for(i=0; i<SizeofArray(pFts3->aStmt); i++){
131675    sqlite3_finalize(pFts3->aStmt[i]);
131676  }
131677  sqlite3_free(pFts3->zSegmentsTbl);
131678  sqlite3_free(p);
131679  return SQLITE_OK;
131680}
131681
131682#define FTS4AUX_EQ_CONSTRAINT 1
131683#define FTS4AUX_GE_CONSTRAINT 2
131684#define FTS4AUX_LE_CONSTRAINT 4
131685
131686/*
131687** xBestIndex - Analyze a WHERE and ORDER BY clause.
131688*/
131689static int fts3auxBestIndexMethod(
131690  sqlite3_vtab *pVTab,
131691  sqlite3_index_info *pInfo
131692){
131693  int i;
131694  int iEq = -1;
131695  int iGe = -1;
131696  int iLe = -1;
131697  int iLangid = -1;
131698  int iNext = 1;                  /* Next free argvIndex value */
131699
131700  UNUSED_PARAMETER(pVTab);
131701
131702  /* This vtab delivers always results in "ORDER BY term ASC" order. */
131703  if( pInfo->nOrderBy==1
131704   && pInfo->aOrderBy[0].iColumn==0
131705   && pInfo->aOrderBy[0].desc==0
131706  ){
131707    pInfo->orderByConsumed = 1;
131708  }
131709
131710  /* Search for equality and range constraints on the "term" column.
131711  ** And equality constraints on the hidden "languageid" column. */
131712  for(i=0; i<pInfo->nConstraint; i++){
131713    if( pInfo->aConstraint[i].usable ){
131714      int op = pInfo->aConstraint[i].op;
131715      int iCol = pInfo->aConstraint[i].iColumn;
131716
131717      if( iCol==0 ){
131718        if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
131719        if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
131720        if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
131721        if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
131722        if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
131723      }
131724      if( iCol==4 ){
131725        if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
131726      }
131727    }
131728  }
131729
131730  if( iEq>=0 ){
131731    pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
131732    pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
131733    pInfo->estimatedCost = 5;
131734  }else{
131735    pInfo->idxNum = 0;
131736    pInfo->estimatedCost = 20000;
131737    if( iGe>=0 ){
131738      pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
131739      pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
131740      pInfo->estimatedCost /= 2;
131741    }
131742    if( iLe>=0 ){
131743      pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
131744      pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
131745      pInfo->estimatedCost /= 2;
131746    }
131747  }
131748  if( iLangid>=0 ){
131749    pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
131750    pInfo->estimatedCost--;
131751  }
131752
131753  return SQLITE_OK;
131754}
131755
131756/*
131757** xOpen - Open a cursor.
131758*/
131759static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
131760  Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
131761
131762  UNUSED_PARAMETER(pVTab);
131763
131764  pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
131765  if( !pCsr ) return SQLITE_NOMEM;
131766  memset(pCsr, 0, sizeof(Fts3auxCursor));
131767
131768  *ppCsr = (sqlite3_vtab_cursor *)pCsr;
131769  return SQLITE_OK;
131770}
131771
131772/*
131773** xClose - Close a cursor.
131774*/
131775static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
131776  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
131777  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
131778
131779  sqlite3Fts3SegmentsClose(pFts3);
131780  sqlite3Fts3SegReaderFinish(&pCsr->csr);
131781  sqlite3_free((void *)pCsr->filter.zTerm);
131782  sqlite3_free(pCsr->zStop);
131783  sqlite3_free(pCsr->aStat);
131784  sqlite3_free(pCsr);
131785  return SQLITE_OK;
131786}
131787
131788static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
131789  if( nSize>pCsr->nStat ){
131790    struct Fts3auxColstats *aNew;
131791    aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
131792        sizeof(struct Fts3auxColstats) * nSize
131793    );
131794    if( aNew==0 ) return SQLITE_NOMEM;
131795    memset(&aNew[pCsr->nStat], 0,
131796        sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
131797    );
131798    pCsr->aStat = aNew;
131799    pCsr->nStat = nSize;
131800  }
131801  return SQLITE_OK;
131802}
131803
131804/*
131805** xNext - Advance the cursor to the next row, if any.
131806*/
131807static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
131808  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
131809  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
131810  int rc;
131811
131812  /* Increment our pretend rowid value. */
131813  pCsr->iRowid++;
131814
131815  for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
131816    if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
131817  }
131818
131819  rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
131820  if( rc==SQLITE_ROW ){
131821    int i = 0;
131822    int nDoclist = pCsr->csr.nDoclist;
131823    char *aDoclist = pCsr->csr.aDoclist;
131824    int iCol;
131825
131826    int eState = 0;
131827
131828    if( pCsr->zStop ){
131829      int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
131830      int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
131831      if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
131832        pCsr->isEof = 1;
131833        return SQLITE_OK;
131834      }
131835    }
131836
131837    if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
131838    memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
131839    iCol = 0;
131840
131841    while( i<nDoclist ){
131842      sqlite3_int64 v = 0;
131843
131844      i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
131845      switch( eState ){
131846        /* State 0. In this state the integer just read was a docid. */
131847        case 0:
131848          pCsr->aStat[0].nDoc++;
131849          eState = 1;
131850          iCol = 0;
131851          break;
131852
131853        /* State 1. In this state we are expecting either a 1, indicating
131854        ** that the following integer will be a column number, or the
131855        ** start of a position list for column 0.
131856        **
131857        ** The only difference between state 1 and state 2 is that if the
131858        ** integer encountered in state 1 is not 0 or 1, then we need to
131859        ** increment the column 0 "nDoc" count for this term.
131860        */
131861        case 1:
131862          assert( iCol==0 );
131863          if( v>1 ){
131864            pCsr->aStat[1].nDoc++;
131865          }
131866          eState = 2;
131867          /* fall through */
131868
131869        case 2:
131870          if( v==0 ){       /* 0x00. Next integer will be a docid. */
131871            eState = 0;
131872          }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
131873            eState = 3;
131874          }else{            /* 2 or greater. A position. */
131875            pCsr->aStat[iCol+1].nOcc++;
131876            pCsr->aStat[0].nOcc++;
131877          }
131878          break;
131879
131880        /* State 3. The integer just read is a column number. */
131881        default: assert( eState==3 );
131882          iCol = (int)v;
131883          if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
131884          pCsr->aStat[iCol+1].nDoc++;
131885          eState = 2;
131886          break;
131887      }
131888    }
131889
131890    pCsr->iCol = 0;
131891    rc = SQLITE_OK;
131892  }else{
131893    pCsr->isEof = 1;
131894  }
131895  return rc;
131896}
131897
131898/*
131899** xFilter - Initialize a cursor to point at the start of its data.
131900*/
131901static int fts3auxFilterMethod(
131902  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
131903  int idxNum,                     /* Strategy index */
131904  const char *idxStr,             /* Unused */
131905  int nVal,                       /* Number of elements in apVal */
131906  sqlite3_value **apVal           /* Arguments for the indexing scheme */
131907){
131908  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
131909  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
131910  int rc;
131911  int isScan = 0;
131912  int iLangVal = 0;               /* Language id to query */
131913
131914  int iEq = -1;                   /* Index of term=? value in apVal */
131915  int iGe = -1;                   /* Index of term>=? value in apVal */
131916  int iLe = -1;                   /* Index of term<=? value in apVal */
131917  int iLangid = -1;               /* Index of languageid=? value in apVal */
131918  int iNext = 0;
131919
131920  UNUSED_PARAMETER(nVal);
131921  UNUSED_PARAMETER(idxStr);
131922
131923  assert( idxStr==0 );
131924  assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
131925       || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
131926       || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
131927  );
131928
131929  if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
131930    iEq = iNext++;
131931  }else{
131932    isScan = 1;
131933    if( idxNum & FTS4AUX_GE_CONSTRAINT ){
131934      iGe = iNext++;
131935    }
131936    if( idxNum & FTS4AUX_LE_CONSTRAINT ){
131937      iLe = iNext++;
131938    }
131939  }
131940  if( iNext<nVal ){
131941    iLangid = iNext++;
131942  }
131943
131944  /* In case this cursor is being reused, close and zero it. */
131945  testcase(pCsr->filter.zTerm);
131946  sqlite3Fts3SegReaderFinish(&pCsr->csr);
131947  sqlite3_free((void *)pCsr->filter.zTerm);
131948  sqlite3_free(pCsr->aStat);
131949  memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
131950
131951  pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
131952  if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
131953
131954  if( iEq>=0 || iGe>=0 ){
131955    const unsigned char *zStr = sqlite3_value_text(apVal[0]);
131956    assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
131957    if( zStr ){
131958      pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
131959      pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
131960      if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
131961    }
131962  }
131963
131964  if( iLe>=0 ){
131965    pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
131966    pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
131967    if( pCsr->zStop==0 ) return SQLITE_NOMEM;
131968  }
131969
131970  if( iLangid>=0 ){
131971    iLangVal = sqlite3_value_int(apVal[iLangid]);
131972
131973    /* If the user specified a negative value for the languageid, use zero
131974    ** instead. This works, as the "languageid=?" constraint will also
131975    ** be tested by the VDBE layer. The test will always be false (since
131976    ** this module will not return a row with a negative languageid), and
131977    ** so the overall query will return zero rows.  */
131978    if( iLangVal<0 ) iLangVal = 0;
131979  }
131980  pCsr->iLangid = iLangVal;
131981
131982  rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
131983      pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
131984  );
131985  if( rc==SQLITE_OK ){
131986    rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
131987  }
131988
131989  if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
131990  return rc;
131991}
131992
131993/*
131994** xEof - Return true if the cursor is at EOF, or false otherwise.
131995*/
131996static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
131997  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
131998  return pCsr->isEof;
131999}
132000
132001/*
132002** xColumn - Return a column value.
132003*/
132004static int fts3auxColumnMethod(
132005  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
132006  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
132007  int iCol                        /* Index of column to read value from */
132008){
132009  Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
132010
132011  assert( p->isEof==0 );
132012  switch( iCol ){
132013    case 0: /* term */
132014      sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
132015      break;
132016
132017    case 1: /* col */
132018      if( p->iCol ){
132019        sqlite3_result_int(pCtx, p->iCol-1);
132020      }else{
132021        sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
132022      }
132023      break;
132024
132025    case 2: /* documents */
132026      sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
132027      break;
132028
132029    case 3: /* occurrences */
132030      sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
132031      break;
132032
132033    default: /* languageid */
132034      assert( iCol==4 );
132035      sqlite3_result_int(pCtx, p->iLangid);
132036      break;
132037  }
132038
132039  return SQLITE_OK;
132040}
132041
132042/*
132043** xRowid - Return the current rowid for the cursor.
132044*/
132045static int fts3auxRowidMethod(
132046  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
132047  sqlite_int64 *pRowid            /* OUT: Rowid value */
132048){
132049  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
132050  *pRowid = pCsr->iRowid;
132051  return SQLITE_OK;
132052}
132053
132054/*
132055** Register the fts3aux module with database connection db. Return SQLITE_OK
132056** if successful or an error code if sqlite3_create_module() fails.
132057*/
132058SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
132059  static const sqlite3_module fts3aux_module = {
132060     0,                           /* iVersion      */
132061     fts3auxConnectMethod,        /* xCreate       */
132062     fts3auxConnectMethod,        /* xConnect      */
132063     fts3auxBestIndexMethod,      /* xBestIndex    */
132064     fts3auxDisconnectMethod,     /* xDisconnect   */
132065     fts3auxDisconnectMethod,     /* xDestroy      */
132066     fts3auxOpenMethod,           /* xOpen         */
132067     fts3auxCloseMethod,          /* xClose        */
132068     fts3auxFilterMethod,         /* xFilter       */
132069     fts3auxNextMethod,           /* xNext         */
132070     fts3auxEofMethod,            /* xEof          */
132071     fts3auxColumnMethod,         /* xColumn       */
132072     fts3auxRowidMethod,          /* xRowid        */
132073     0,                           /* xUpdate       */
132074     0,                           /* xBegin        */
132075     0,                           /* xSync         */
132076     0,                           /* xCommit       */
132077     0,                           /* xRollback     */
132078     0,                           /* xFindFunction */
132079     0,                           /* xRename       */
132080     0,                           /* xSavepoint    */
132081     0,                           /* xRelease      */
132082     0                            /* xRollbackTo   */
132083  };
132084  int rc;                         /* Return code */
132085
132086  rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
132087  return rc;
132088}
132089
132090#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
132091
132092/************** End of fts3_aux.c ********************************************/
132093/************** Begin file fts3_expr.c ***************************************/
132094/*
132095** 2008 Nov 28
132096**
132097** The author disclaims copyright to this source code.  In place of
132098** a legal notice, here is a blessing:
132099**
132100**    May you do good and not evil.
132101**    May you find forgiveness for yourself and forgive others.
132102**    May you share freely, never taking more than you give.
132103**
132104******************************************************************************
132105**
132106** This module contains code that implements a parser for fts3 query strings
132107** (the right-hand argument to the MATCH operator). Because the supported
132108** syntax is relatively simple, the whole tokenizer/parser system is
132109** hand-coded.
132110*/
132111#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
132112
132113/*
132114** By default, this module parses the legacy syntax that has been
132115** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
132116** is defined, then it uses the new syntax. The differences between
132117** the new and the old syntaxes are:
132118**
132119**  a) The new syntax supports parenthesis. The old does not.
132120**
132121**  b) The new syntax supports the AND and NOT operators. The old does not.
132122**
132123**  c) The old syntax supports the "-" token qualifier. This is not
132124**     supported by the new syntax (it is replaced by the NOT operator).
132125**
132126**  d) When using the old syntax, the OR operator has a greater precedence
132127**     than an implicit AND. When using the new, both implicity and explicit
132128**     AND operators have a higher precedence than OR.
132129**
132130** If compiled with SQLITE_TEST defined, then this module exports the
132131** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
132132** to zero causes the module to use the old syntax. If it is set to
132133** non-zero the new syntax is activated. This is so both syntaxes can
132134** be tested using a single build of testfixture.
132135**
132136** The following describes the syntax supported by the fts3 MATCH
132137** operator in a similar format to that used by the lemon parser
132138** generator. This module does not use actually lemon, it uses a
132139** custom parser.
132140**
132141**   query ::= andexpr (OR andexpr)*.
132142**
132143**   andexpr ::= notexpr (AND? notexpr)*.
132144**
132145**   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
132146**   notexpr ::= LP query RP.
132147**
132148**   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
132149**
132150**   distance_opt ::= .
132151**   distance_opt ::= / INTEGER.
132152**
132153**   phrase ::= TOKEN.
132154**   phrase ::= COLUMN:TOKEN.
132155**   phrase ::= "TOKEN TOKEN TOKEN...".
132156*/
132157
132158#ifdef SQLITE_TEST
132159SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
132160#else
132161# ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
132162#  define sqlite3_fts3_enable_parentheses 1
132163# else
132164#  define sqlite3_fts3_enable_parentheses 0
132165# endif
132166#endif
132167
132168/*
132169** Default span for NEAR operators.
132170*/
132171#define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
132172
132173/* #include <string.h> */
132174/* #include <assert.h> */
132175
132176/*
132177** isNot:
132178**   This variable is used by function getNextNode(). When getNextNode() is
132179**   called, it sets ParseContext.isNot to true if the 'next node' is a
132180**   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
132181**   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
132182**   zero.
132183*/
132184typedef struct ParseContext ParseContext;
132185struct ParseContext {
132186  sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
132187  int iLangid;                        /* Language id used with tokenizer */
132188  const char **azCol;                 /* Array of column names for fts3 table */
132189  int bFts4;                          /* True to allow FTS4-only syntax */
132190  int nCol;                           /* Number of entries in azCol[] */
132191  int iDefaultCol;                    /* Default column to query */
132192  int isNot;                          /* True if getNextNode() sees a unary - */
132193  sqlite3_context *pCtx;              /* Write error message here */
132194  int nNest;                          /* Number of nested brackets */
132195};
132196
132197/*
132198** This function is equivalent to the standard isspace() function.
132199**
132200** The standard isspace() can be awkward to use safely, because although it
132201** is defined to accept an argument of type int, its behavior when passed
132202** an integer that falls outside of the range of the unsigned char type
132203** is undefined (and sometimes, "undefined" means segfault). This wrapper
132204** is defined to accept an argument of type char, and always returns 0 for
132205** any values that fall outside of the range of the unsigned char type (i.e.
132206** negative values).
132207*/
132208static int fts3isspace(char c){
132209  return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
132210}
132211
132212/*
132213** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
132214** zero the memory before returning a pointer to it. If unsuccessful,
132215** return NULL.
132216*/
132217static void *fts3MallocZero(int nByte){
132218  void *pRet = sqlite3_malloc(nByte);
132219  if( pRet ) memset(pRet, 0, nByte);
132220  return pRet;
132221}
132222
132223SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
132224  sqlite3_tokenizer *pTokenizer,
132225  int iLangid,
132226  const char *z,
132227  int n,
132228  sqlite3_tokenizer_cursor **ppCsr
132229){
132230  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
132231  sqlite3_tokenizer_cursor *pCsr = 0;
132232  int rc;
132233
132234  rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
132235  assert( rc==SQLITE_OK || pCsr==0 );
132236  if( rc==SQLITE_OK ){
132237    pCsr->pTokenizer = pTokenizer;
132238    if( pModule->iVersion>=1 ){
132239      rc = pModule->xLanguageid(pCsr, iLangid);
132240      if( rc!=SQLITE_OK ){
132241        pModule->xClose(pCsr);
132242        pCsr = 0;
132243      }
132244    }
132245  }
132246  *ppCsr = pCsr;
132247  return rc;
132248}
132249
132250/*
132251** Function getNextNode(), which is called by fts3ExprParse(), may itself
132252** call fts3ExprParse(). So this forward declaration is required.
132253*/
132254static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
132255
132256/*
132257** Extract the next token from buffer z (length n) using the tokenizer
132258** and other information (column names etc.) in pParse. Create an Fts3Expr
132259** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
132260** single token and set *ppExpr to point to it. If the end of the buffer is
132261** reached before a token is found, set *ppExpr to zero. It is the
132262** responsibility of the caller to eventually deallocate the allocated
132263** Fts3Expr structure (if any) by passing it to sqlite3_free().
132264**
132265** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
132266** fails.
132267*/
132268static int getNextToken(
132269  ParseContext *pParse,                   /* fts3 query parse context */
132270  int iCol,                               /* Value for Fts3Phrase.iColumn */
132271  const char *z, int n,                   /* Input string */
132272  Fts3Expr **ppExpr,                      /* OUT: expression */
132273  int *pnConsumed                         /* OUT: Number of bytes consumed */
132274){
132275  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
132276  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
132277  int rc;
132278  sqlite3_tokenizer_cursor *pCursor;
132279  Fts3Expr *pRet = 0;
132280  int i = 0;
132281
132282  /* Set variable i to the maximum number of bytes of input to tokenize. */
132283  for(i=0; i<n; i++){
132284    if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
132285    if( z[i]=='*' || z[i]=='"' ) break;
132286  }
132287
132288  *pnConsumed = i;
132289  rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
132290  if( rc==SQLITE_OK ){
132291    const char *zToken;
132292    int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
132293    int nByte;                               /* total space to allocate */
132294
132295    rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
132296    if( rc==SQLITE_OK ){
132297      nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
132298      pRet = (Fts3Expr *)fts3MallocZero(nByte);
132299      if( !pRet ){
132300        rc = SQLITE_NOMEM;
132301      }else{
132302        pRet->eType = FTSQUERY_PHRASE;
132303        pRet->pPhrase = (Fts3Phrase *)&pRet[1];
132304        pRet->pPhrase->nToken = 1;
132305        pRet->pPhrase->iColumn = iCol;
132306        pRet->pPhrase->aToken[0].n = nToken;
132307        pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
132308        memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
132309
132310        if( iEnd<n && z[iEnd]=='*' ){
132311          pRet->pPhrase->aToken[0].isPrefix = 1;
132312          iEnd++;
132313        }
132314
132315        while( 1 ){
132316          if( !sqlite3_fts3_enable_parentheses
132317           && iStart>0 && z[iStart-1]=='-'
132318          ){
132319            pParse->isNot = 1;
132320            iStart--;
132321          }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
132322            pRet->pPhrase->aToken[0].bFirst = 1;
132323            iStart--;
132324          }else{
132325            break;
132326          }
132327        }
132328
132329      }
132330      *pnConsumed = iEnd;
132331    }else if( i && rc==SQLITE_DONE ){
132332      rc = SQLITE_OK;
132333    }
132334
132335    pModule->xClose(pCursor);
132336  }
132337
132338  *ppExpr = pRet;
132339  return rc;
132340}
132341
132342
132343/*
132344** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
132345** then free the old allocation.
132346*/
132347static void *fts3ReallocOrFree(void *pOrig, int nNew){
132348  void *pRet = sqlite3_realloc(pOrig, nNew);
132349  if( !pRet ){
132350    sqlite3_free(pOrig);
132351  }
132352  return pRet;
132353}
132354
132355/*
132356** Buffer zInput, length nInput, contains the contents of a quoted string
132357** that appeared as part of an fts3 query expression. Neither quote character
132358** is included in the buffer. This function attempts to tokenize the entire
132359** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
132360** containing the results.
132361**
132362** If successful, SQLITE_OK is returned and *ppExpr set to point at the
132363** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
132364** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
132365** to 0.
132366*/
132367static int getNextString(
132368  ParseContext *pParse,                   /* fts3 query parse context */
132369  const char *zInput, int nInput,         /* Input string */
132370  Fts3Expr **ppExpr                       /* OUT: expression */
132371){
132372  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
132373  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
132374  int rc;
132375  Fts3Expr *p = 0;
132376  sqlite3_tokenizer_cursor *pCursor = 0;
132377  char *zTemp = 0;
132378  int nTemp = 0;
132379
132380  const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
132381  int nToken = 0;
132382
132383  /* The final Fts3Expr data structure, including the Fts3Phrase,
132384  ** Fts3PhraseToken structures token buffers are all stored as a single
132385  ** allocation so that the expression can be freed with a single call to
132386  ** sqlite3_free(). Setting this up requires a two pass approach.
132387  **
132388  ** The first pass, in the block below, uses a tokenizer cursor to iterate
132389  ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
132390  ** to assemble data in two dynamic buffers:
132391  **
132392  **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
132393  **             structure, followed by the array of Fts3PhraseToken
132394  **             structures. This pass only populates the Fts3PhraseToken array.
132395  **
132396  **   Buffer zTemp: Contains copies of all tokens.
132397  **
132398  ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
132399  ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
132400  ** structures.
132401  */
132402  rc = sqlite3Fts3OpenTokenizer(
132403      pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
132404  if( rc==SQLITE_OK ){
132405    int ii;
132406    for(ii=0; rc==SQLITE_OK; ii++){
132407      const char *zByte;
132408      int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
132409      rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
132410      if( rc==SQLITE_OK ){
132411        Fts3PhraseToken *pToken;
132412
132413        p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
132414        if( !p ) goto no_mem;
132415
132416        zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
132417        if( !zTemp ) goto no_mem;
132418
132419        assert( nToken==ii );
132420        pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
132421        memset(pToken, 0, sizeof(Fts3PhraseToken));
132422
132423        memcpy(&zTemp[nTemp], zByte, nByte);
132424        nTemp += nByte;
132425
132426        pToken->n = nByte;
132427        pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
132428        pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
132429        nToken = ii+1;
132430      }
132431    }
132432
132433    pModule->xClose(pCursor);
132434    pCursor = 0;
132435  }
132436
132437  if( rc==SQLITE_DONE ){
132438    int jj;
132439    char *zBuf = 0;
132440
132441    p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
132442    if( !p ) goto no_mem;
132443    memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
132444    p->eType = FTSQUERY_PHRASE;
132445    p->pPhrase = (Fts3Phrase *)&p[1];
132446    p->pPhrase->iColumn = pParse->iDefaultCol;
132447    p->pPhrase->nToken = nToken;
132448
132449    zBuf = (char *)&p->pPhrase->aToken[nToken];
132450    if( zTemp ){
132451      memcpy(zBuf, zTemp, nTemp);
132452      sqlite3_free(zTemp);
132453    }else{
132454      assert( nTemp==0 );
132455    }
132456
132457    for(jj=0; jj<p->pPhrase->nToken; jj++){
132458      p->pPhrase->aToken[jj].z = zBuf;
132459      zBuf += p->pPhrase->aToken[jj].n;
132460    }
132461    rc = SQLITE_OK;
132462  }
132463
132464  *ppExpr = p;
132465  return rc;
132466no_mem:
132467
132468  if( pCursor ){
132469    pModule->xClose(pCursor);
132470  }
132471  sqlite3_free(zTemp);
132472  sqlite3_free(p);
132473  *ppExpr = 0;
132474  return SQLITE_NOMEM;
132475}
132476
132477/*
132478** The output variable *ppExpr is populated with an allocated Fts3Expr
132479** structure, or set to 0 if the end of the input buffer is reached.
132480**
132481** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
132482** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
132483** If SQLITE_ERROR is returned, pContext is populated with an error message.
132484*/
132485static int getNextNode(
132486  ParseContext *pParse,                   /* fts3 query parse context */
132487  const char *z, int n,                   /* Input string */
132488  Fts3Expr **ppExpr,                      /* OUT: expression */
132489  int *pnConsumed                         /* OUT: Number of bytes consumed */
132490){
132491  static const struct Fts3Keyword {
132492    char *z;                              /* Keyword text */
132493    unsigned char n;                      /* Length of the keyword */
132494    unsigned char parenOnly;              /* Only valid in paren mode */
132495    unsigned char eType;                  /* Keyword code */
132496  } aKeyword[] = {
132497    { "OR" ,  2, 0, FTSQUERY_OR   },
132498    { "AND",  3, 1, FTSQUERY_AND  },
132499    { "NOT",  3, 1, FTSQUERY_NOT  },
132500    { "NEAR", 4, 0, FTSQUERY_NEAR }
132501  };
132502  int ii;
132503  int iCol;
132504  int iColLen;
132505  int rc;
132506  Fts3Expr *pRet = 0;
132507
132508  const char *zInput = z;
132509  int nInput = n;
132510
132511  pParse->isNot = 0;
132512
132513  /* Skip over any whitespace before checking for a keyword, an open or
132514  ** close bracket, or a quoted string.
132515  */
132516  while( nInput>0 && fts3isspace(*zInput) ){
132517    nInput--;
132518    zInput++;
132519  }
132520  if( nInput==0 ){
132521    return SQLITE_DONE;
132522  }
132523
132524  /* See if we are dealing with a keyword. */
132525  for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
132526    const struct Fts3Keyword *pKey = &aKeyword[ii];
132527
132528    if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
132529      continue;
132530    }
132531
132532    if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
132533      int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
132534      int nKey = pKey->n;
132535      char cNext;
132536
132537      /* If this is a "NEAR" keyword, check for an explicit nearness. */
132538      if( pKey->eType==FTSQUERY_NEAR ){
132539        assert( nKey==4 );
132540        if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
132541          nNear = 0;
132542          for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
132543            nNear = nNear * 10 + (zInput[nKey] - '0');
132544          }
132545        }
132546      }
132547
132548      /* At this point this is probably a keyword. But for that to be true,
132549      ** the next byte must contain either whitespace, an open or close
132550      ** parenthesis, a quote character, or EOF.
132551      */
132552      cNext = zInput[nKey];
132553      if( fts3isspace(cNext)
132554       || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
132555      ){
132556        pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
132557        if( !pRet ){
132558          return SQLITE_NOMEM;
132559        }
132560        pRet->eType = pKey->eType;
132561        pRet->nNear = nNear;
132562        *ppExpr = pRet;
132563        *pnConsumed = (int)((zInput - z) + nKey);
132564        return SQLITE_OK;
132565      }
132566
132567      /* Turns out that wasn't a keyword after all. This happens if the
132568      ** user has supplied a token such as "ORacle". Continue.
132569      */
132570    }
132571  }
132572
132573  /* See if we are dealing with a quoted phrase. If this is the case, then
132574  ** search for the closing quote and pass the whole string to getNextString()
132575  ** for processing. This is easy to do, as fts3 has no syntax for escaping
132576  ** a quote character embedded in a string.
132577  */
132578  if( *zInput=='"' ){
132579    for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
132580    *pnConsumed = (int)((zInput - z) + ii + 1);
132581    if( ii==nInput ){
132582      return SQLITE_ERROR;
132583    }
132584    return getNextString(pParse, &zInput[1], ii-1, ppExpr);
132585  }
132586
132587  if( sqlite3_fts3_enable_parentheses ){
132588    if( *zInput=='(' ){
132589      int nConsumed = 0;
132590      pParse->nNest++;
132591      rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
132592      if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
132593      *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
132594      return rc;
132595    }else if( *zInput==')' ){
132596      pParse->nNest--;
132597      *pnConsumed = (int)((zInput - z) + 1);
132598      *ppExpr = 0;
132599      return SQLITE_DONE;
132600    }
132601  }
132602
132603  /* If control flows to this point, this must be a regular token, or
132604  ** the end of the input. Read a regular token using the sqlite3_tokenizer
132605  ** interface. Before doing so, figure out if there is an explicit
132606  ** column specifier for the token.
132607  **
132608  ** TODO: Strangely, it is not possible to associate a column specifier
132609  ** with a quoted phrase, only with a single token. Not sure if this was
132610  ** an implementation artifact or an intentional decision when fts3 was
132611  ** first implemented. Whichever it was, this module duplicates the
132612  ** limitation.
132613  */
132614  iCol = pParse->iDefaultCol;
132615  iColLen = 0;
132616  for(ii=0; ii<pParse->nCol; ii++){
132617    const char *zStr = pParse->azCol[ii];
132618    int nStr = (int)strlen(zStr);
132619    if( nInput>nStr && zInput[nStr]==':'
132620     && sqlite3_strnicmp(zStr, zInput, nStr)==0
132621    ){
132622      iCol = ii;
132623      iColLen = (int)((zInput - z) + nStr + 1);
132624      break;
132625    }
132626  }
132627  rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
132628  *pnConsumed += iColLen;
132629  return rc;
132630}
132631
132632/*
132633** The argument is an Fts3Expr structure for a binary operator (any type
132634** except an FTSQUERY_PHRASE). Return an integer value representing the
132635** precedence of the operator. Lower values have a higher precedence (i.e.
132636** group more tightly). For example, in the C language, the == operator
132637** groups more tightly than ||, and would therefore have a higher precedence.
132638**
132639** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
132640** is defined), the order of the operators in precedence from highest to
132641** lowest is:
132642**
132643**   NEAR
132644**   NOT
132645**   AND (including implicit ANDs)
132646**   OR
132647**
132648** Note that when using the old query syntax, the OR operator has a higher
132649** precedence than the AND operator.
132650*/
132651static int opPrecedence(Fts3Expr *p){
132652  assert( p->eType!=FTSQUERY_PHRASE );
132653  if( sqlite3_fts3_enable_parentheses ){
132654    return p->eType;
132655  }else if( p->eType==FTSQUERY_NEAR ){
132656    return 1;
132657  }else if( p->eType==FTSQUERY_OR ){
132658    return 2;
132659  }
132660  assert( p->eType==FTSQUERY_AND );
132661  return 3;
132662}
132663
132664/*
132665** Argument ppHead contains a pointer to the current head of a query
132666** expression tree being parsed. pPrev is the expression node most recently
132667** inserted into the tree. This function adds pNew, which is always a binary
132668** operator node, into the expression tree based on the relative precedence
132669** of pNew and the existing nodes of the tree. This may result in the head
132670** of the tree changing, in which case *ppHead is set to the new root node.
132671*/
132672static void insertBinaryOperator(
132673  Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
132674  Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
132675  Fts3Expr *pNew           /* New binary node to insert into expression tree */
132676){
132677  Fts3Expr *pSplit = pPrev;
132678  while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
132679    pSplit = pSplit->pParent;
132680  }
132681
132682  if( pSplit->pParent ){
132683    assert( pSplit->pParent->pRight==pSplit );
132684    pSplit->pParent->pRight = pNew;
132685    pNew->pParent = pSplit->pParent;
132686  }else{
132687    *ppHead = pNew;
132688  }
132689  pNew->pLeft = pSplit;
132690  pSplit->pParent = pNew;
132691}
132692
132693/*
132694** Parse the fts3 query expression found in buffer z, length n. This function
132695** returns either when the end of the buffer is reached or an unmatched
132696** closing bracket - ')' - is encountered.
132697**
132698** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
132699** parsed form of the expression and *pnConsumed is set to the number of
132700** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
132701** (out of memory error) or SQLITE_ERROR (parse error) is returned.
132702*/
132703static int fts3ExprParse(
132704  ParseContext *pParse,                   /* fts3 query parse context */
132705  const char *z, int n,                   /* Text of MATCH query */
132706  Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
132707  int *pnConsumed                         /* OUT: Number of bytes consumed */
132708){
132709  Fts3Expr *pRet = 0;
132710  Fts3Expr *pPrev = 0;
132711  Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
132712  int nIn = n;
132713  const char *zIn = z;
132714  int rc = SQLITE_OK;
132715  int isRequirePhrase = 1;
132716
132717  while( rc==SQLITE_OK ){
132718    Fts3Expr *p = 0;
132719    int nByte = 0;
132720
132721    rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
132722    assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
132723    if( rc==SQLITE_OK ){
132724      if( p ){
132725        int isPhrase;
132726
132727        if( !sqlite3_fts3_enable_parentheses
132728            && p->eType==FTSQUERY_PHRASE && pParse->isNot
132729        ){
132730          /* Create an implicit NOT operator. */
132731          Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
132732          if( !pNot ){
132733            sqlite3Fts3ExprFree(p);
132734            rc = SQLITE_NOMEM;
132735            goto exprparse_out;
132736          }
132737          pNot->eType = FTSQUERY_NOT;
132738          pNot->pRight = p;
132739          p->pParent = pNot;
132740          if( pNotBranch ){
132741            pNot->pLeft = pNotBranch;
132742            pNotBranch->pParent = pNot;
132743          }
132744          pNotBranch = pNot;
132745          p = pPrev;
132746        }else{
132747          int eType = p->eType;
132748          isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
132749
132750          /* The isRequirePhrase variable is set to true if a phrase or
132751          ** an expression contained in parenthesis is required. If a
132752          ** binary operator (AND, OR, NOT or NEAR) is encounted when
132753          ** isRequirePhrase is set, this is a syntax error.
132754          */
132755          if( !isPhrase && isRequirePhrase ){
132756            sqlite3Fts3ExprFree(p);
132757            rc = SQLITE_ERROR;
132758            goto exprparse_out;
132759          }
132760
132761          if( isPhrase && !isRequirePhrase ){
132762            /* Insert an implicit AND operator. */
132763            Fts3Expr *pAnd;
132764            assert( pRet && pPrev );
132765            pAnd = fts3MallocZero(sizeof(Fts3Expr));
132766            if( !pAnd ){
132767              sqlite3Fts3ExprFree(p);
132768              rc = SQLITE_NOMEM;
132769              goto exprparse_out;
132770            }
132771            pAnd->eType = FTSQUERY_AND;
132772            insertBinaryOperator(&pRet, pPrev, pAnd);
132773            pPrev = pAnd;
132774          }
132775
132776          /* This test catches attempts to make either operand of a NEAR
132777           ** operator something other than a phrase. For example, either of
132778           ** the following:
132779           **
132780           **    (bracketed expression) NEAR phrase
132781           **    phrase NEAR (bracketed expression)
132782           **
132783           ** Return an error in either case.
132784           */
132785          if( pPrev && (
132786            (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
132787         || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
132788          )){
132789            sqlite3Fts3ExprFree(p);
132790            rc = SQLITE_ERROR;
132791            goto exprparse_out;
132792          }
132793
132794          if( isPhrase ){
132795            if( pRet ){
132796              assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
132797              pPrev->pRight = p;
132798              p->pParent = pPrev;
132799            }else{
132800              pRet = p;
132801            }
132802          }else{
132803            insertBinaryOperator(&pRet, pPrev, p);
132804          }
132805          isRequirePhrase = !isPhrase;
132806        }
132807        pPrev = p;
132808      }
132809      assert( nByte>0 );
132810    }
132811    assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
132812    nIn -= nByte;
132813    zIn += nByte;
132814  }
132815
132816  if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
132817    rc = SQLITE_ERROR;
132818  }
132819
132820  if( rc==SQLITE_DONE ){
132821    rc = SQLITE_OK;
132822    if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
132823      if( !pRet ){
132824        rc = SQLITE_ERROR;
132825      }else{
132826        Fts3Expr *pIter = pNotBranch;
132827        while( pIter->pLeft ){
132828          pIter = pIter->pLeft;
132829        }
132830        pIter->pLeft = pRet;
132831        pRet->pParent = pIter;
132832        pRet = pNotBranch;
132833      }
132834    }
132835  }
132836  *pnConsumed = n - nIn;
132837
132838exprparse_out:
132839  if( rc!=SQLITE_OK ){
132840    sqlite3Fts3ExprFree(pRet);
132841    sqlite3Fts3ExprFree(pNotBranch);
132842    pRet = 0;
132843  }
132844  *ppExpr = pRet;
132845  return rc;
132846}
132847
132848/*
132849** Return SQLITE_ERROR if the maximum depth of the expression tree passed
132850** as the only argument is more than nMaxDepth.
132851*/
132852static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
132853  int rc = SQLITE_OK;
132854  if( p ){
132855    if( nMaxDepth<0 ){
132856      rc = SQLITE_TOOBIG;
132857    }else{
132858      rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
132859      if( rc==SQLITE_OK ){
132860        rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
132861      }
132862    }
132863  }
132864  return rc;
132865}
132866
132867/*
132868** This function attempts to transform the expression tree at (*pp) to
132869** an equivalent but more balanced form. The tree is modified in place.
132870** If successful, SQLITE_OK is returned and (*pp) set to point to the
132871** new root expression node.
132872**
132873** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
132874**
132875** Otherwise, if an error occurs, an SQLite error code is returned and
132876** expression (*pp) freed.
132877*/
132878static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
132879  int rc = SQLITE_OK;             /* Return code */
132880  Fts3Expr *pRoot = *pp;          /* Initial root node */
132881  Fts3Expr *pFree = 0;            /* List of free nodes. Linked by pParent. */
132882  int eType = pRoot->eType;       /* Type of node in this tree */
132883
132884  if( nMaxDepth==0 ){
132885    rc = SQLITE_ERROR;
132886  }
132887
132888  if( rc==SQLITE_OK && (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
132889    Fts3Expr **apLeaf;
132890    apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
132891    if( 0==apLeaf ){
132892      rc = SQLITE_NOMEM;
132893    }else{
132894      memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
132895    }
132896
132897    if( rc==SQLITE_OK ){
132898      int i;
132899      Fts3Expr *p;
132900
132901      /* Set $p to point to the left-most leaf in the tree of eType nodes. */
132902      for(p=pRoot; p->eType==eType; p=p->pLeft){
132903        assert( p->pParent==0 || p->pParent->pLeft==p );
132904        assert( p->pLeft && p->pRight );
132905      }
132906
132907      /* This loop runs once for each leaf in the tree of eType nodes. */
132908      while( 1 ){
132909        int iLvl;
132910        Fts3Expr *pParent = p->pParent;     /* Current parent of p */
132911
132912        assert( pParent==0 || pParent->pLeft==p );
132913        p->pParent = 0;
132914        if( pParent ){
132915          pParent->pLeft = 0;
132916        }else{
132917          pRoot = 0;
132918        }
132919        rc = fts3ExprBalance(&p, nMaxDepth-1);
132920        if( rc!=SQLITE_OK ) break;
132921
132922        for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
132923          if( apLeaf[iLvl]==0 ){
132924            apLeaf[iLvl] = p;
132925            p = 0;
132926          }else{
132927            assert( pFree );
132928            pFree->pLeft = apLeaf[iLvl];
132929            pFree->pRight = p;
132930            pFree->pLeft->pParent = pFree;
132931            pFree->pRight->pParent = pFree;
132932
132933            p = pFree;
132934            pFree = pFree->pParent;
132935            p->pParent = 0;
132936            apLeaf[iLvl] = 0;
132937          }
132938        }
132939        if( p ){
132940          sqlite3Fts3ExprFree(p);
132941          rc = SQLITE_TOOBIG;
132942          break;
132943        }
132944
132945        /* If that was the last leaf node, break out of the loop */
132946        if( pParent==0 ) break;
132947
132948        /* Set $p to point to the next leaf in the tree of eType nodes */
132949        for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
132950
132951        /* Remove pParent from the original tree. */
132952        assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
132953        pParent->pRight->pParent = pParent->pParent;
132954        if( pParent->pParent ){
132955          pParent->pParent->pLeft = pParent->pRight;
132956        }else{
132957          assert( pParent==pRoot );
132958          pRoot = pParent->pRight;
132959        }
132960
132961        /* Link pParent into the free node list. It will be used as an
132962        ** internal node of the new tree.  */
132963        pParent->pParent = pFree;
132964        pFree = pParent;
132965      }
132966
132967      if( rc==SQLITE_OK ){
132968        p = 0;
132969        for(i=0; i<nMaxDepth; i++){
132970          if( apLeaf[i] ){
132971            if( p==0 ){
132972              p = apLeaf[i];
132973              p->pParent = 0;
132974            }else{
132975              assert( pFree!=0 );
132976              pFree->pRight = p;
132977              pFree->pLeft = apLeaf[i];
132978              pFree->pLeft->pParent = pFree;
132979              pFree->pRight->pParent = pFree;
132980
132981              p = pFree;
132982              pFree = pFree->pParent;
132983              p->pParent = 0;
132984            }
132985          }
132986        }
132987        pRoot = p;
132988      }else{
132989        /* An error occurred. Delete the contents of the apLeaf[] array
132990        ** and pFree list. Everything else is cleaned up by the call to
132991        ** sqlite3Fts3ExprFree(pRoot) below.  */
132992        Fts3Expr *pDel;
132993        for(i=0; i<nMaxDepth; i++){
132994          sqlite3Fts3ExprFree(apLeaf[i]);
132995        }
132996        while( (pDel=pFree)!=0 ){
132997          pFree = pDel->pParent;
132998          sqlite3_free(pDel);
132999        }
133000      }
133001
133002      assert( pFree==0 );
133003      sqlite3_free( apLeaf );
133004    }
133005  }
133006
133007  if( rc!=SQLITE_OK ){
133008    sqlite3Fts3ExprFree(pRoot);
133009    pRoot = 0;
133010  }
133011  *pp = pRoot;
133012  return rc;
133013}
133014
133015/*
133016** This function is similar to sqlite3Fts3ExprParse(), with the following
133017** differences:
133018**
133019**   1. It does not do expression rebalancing.
133020**   2. It does not check that the expression does not exceed the
133021**      maximum allowable depth.
133022**   3. Even if it fails, *ppExpr may still be set to point to an
133023**      expression tree. It should be deleted using sqlite3Fts3ExprFree()
133024**      in this case.
133025*/
133026static int fts3ExprParseUnbalanced(
133027  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
133028  int iLangid,                        /* Language id for tokenizer */
133029  char **azCol,                       /* Array of column names for fts3 table */
133030  int bFts4,                          /* True to allow FTS4-only syntax */
133031  int nCol,                           /* Number of entries in azCol[] */
133032  int iDefaultCol,                    /* Default column to query */
133033  const char *z, int n,               /* Text of MATCH query */
133034  Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
133035){
133036  int nParsed;
133037  int rc;
133038  ParseContext sParse;
133039
133040  memset(&sParse, 0, sizeof(ParseContext));
133041  sParse.pTokenizer = pTokenizer;
133042  sParse.iLangid = iLangid;
133043  sParse.azCol = (const char **)azCol;
133044  sParse.nCol = nCol;
133045  sParse.iDefaultCol = iDefaultCol;
133046  sParse.bFts4 = bFts4;
133047  if( z==0 ){
133048    *ppExpr = 0;
133049    return SQLITE_OK;
133050  }
133051  if( n<0 ){
133052    n = (int)strlen(z);
133053  }
133054  rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
133055  assert( rc==SQLITE_OK || *ppExpr==0 );
133056
133057  /* Check for mismatched parenthesis */
133058  if( rc==SQLITE_OK && sParse.nNest ){
133059    rc = SQLITE_ERROR;
133060  }
133061
133062  return rc;
133063}
133064
133065/*
133066** Parameters z and n contain a pointer to and length of a buffer containing
133067** an fts3 query expression, respectively. This function attempts to parse the
133068** query expression and create a tree of Fts3Expr structures representing the
133069** parsed expression. If successful, *ppExpr is set to point to the head
133070** of the parsed expression tree and SQLITE_OK is returned. If an error
133071** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
133072** error) is returned and *ppExpr is set to 0.
133073**
133074** If parameter n is a negative number, then z is assumed to point to a
133075** nul-terminated string and the length is determined using strlen().
133076**
133077** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
133078** use to normalize query tokens while parsing the expression. The azCol[]
133079** array, which is assumed to contain nCol entries, should contain the names
133080** of each column in the target fts3 table, in order from left to right.
133081** Column names must be nul-terminated strings.
133082**
133083** The iDefaultCol parameter should be passed the index of the table column
133084** that appears on the left-hand-side of the MATCH operator (the default
133085** column to match against for tokens for which a column name is not explicitly
133086** specified as part of the query string), or -1 if tokens may by default
133087** match any table column.
133088*/
133089SQLITE_PRIVATE int sqlite3Fts3ExprParse(
133090  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
133091  int iLangid,                        /* Language id for tokenizer */
133092  char **azCol,                       /* Array of column names for fts3 table */
133093  int bFts4,                          /* True to allow FTS4-only syntax */
133094  int nCol,                           /* Number of entries in azCol[] */
133095  int iDefaultCol,                    /* Default column to query */
133096  const char *z, int n,               /* Text of MATCH query */
133097  Fts3Expr **ppExpr,                  /* OUT: Parsed query structure */
133098  char **pzErr                        /* OUT: Error message (sqlite3_malloc) */
133099){
133100  int rc = fts3ExprParseUnbalanced(
133101      pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
133102  );
133103
133104  /* Rebalance the expression. And check that its depth does not exceed
133105  ** SQLITE_FTS3_MAX_EXPR_DEPTH.  */
133106  if( rc==SQLITE_OK && *ppExpr ){
133107    rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
133108    if( rc==SQLITE_OK ){
133109      rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
133110    }
133111  }
133112
133113  if( rc!=SQLITE_OK ){
133114    sqlite3Fts3ExprFree(*ppExpr);
133115    *ppExpr = 0;
133116    if( rc==SQLITE_TOOBIG ){
133117      *pzErr = sqlite3_mprintf(
133118          "FTS expression tree is too large (maximum depth %d)",
133119          SQLITE_FTS3_MAX_EXPR_DEPTH
133120      );
133121      rc = SQLITE_ERROR;
133122    }else if( rc==SQLITE_ERROR ){
133123      *pzErr = sqlite3_mprintf("malformed MATCH expression: [%s]", z);
133124    }
133125  }
133126
133127  return rc;
133128}
133129
133130/*
133131** Free a single node of an expression tree.
133132*/
133133static void fts3FreeExprNode(Fts3Expr *p){
133134  assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
133135  sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
133136  sqlite3_free(p->aMI);
133137  sqlite3_free(p);
133138}
133139
133140/*
133141** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
133142**
133143** This function would be simpler if it recursively called itself. But
133144** that would mean passing a sufficiently large expression to ExprParse()
133145** could cause a stack overflow.
133146*/
133147SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
133148  Fts3Expr *p;
133149  assert( pDel==0 || pDel->pParent==0 );
133150  for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
133151    assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
133152  }
133153  while( p ){
133154    Fts3Expr *pParent = p->pParent;
133155    fts3FreeExprNode(p);
133156    if( pParent && p==pParent->pLeft && pParent->pRight ){
133157      p = pParent->pRight;
133158      while( p && (p->pLeft || p->pRight) ){
133159        assert( p==p->pParent->pRight || p==p->pParent->pLeft );
133160        p = (p->pLeft ? p->pLeft : p->pRight);
133161      }
133162    }else{
133163      p = pParent;
133164    }
133165  }
133166}
133167
133168/****************************************************************************
133169*****************************************************************************
133170** Everything after this point is just test code.
133171*/
133172
133173#ifdef SQLITE_TEST
133174
133175/* #include <stdio.h> */
133176
133177/*
133178** Function to query the hash-table of tokenizers (see README.tokenizers).
133179*/
133180static int queryTestTokenizer(
133181  sqlite3 *db,
133182  const char *zName,
133183  const sqlite3_tokenizer_module **pp
133184){
133185  int rc;
133186  sqlite3_stmt *pStmt;
133187  const char zSql[] = "SELECT fts3_tokenizer(?)";
133188
133189  *pp = 0;
133190  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
133191  if( rc!=SQLITE_OK ){
133192    return rc;
133193  }
133194
133195  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
133196  if( SQLITE_ROW==sqlite3_step(pStmt) ){
133197    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
133198      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
133199    }
133200  }
133201
133202  return sqlite3_finalize(pStmt);
133203}
133204
133205/*
133206** Return a pointer to a buffer containing a text representation of the
133207** expression passed as the first argument. The buffer is obtained from
133208** sqlite3_malloc(). It is the responsibility of the caller to use
133209** sqlite3_free() to release the memory. If an OOM condition is encountered,
133210** NULL is returned.
133211**
133212** If the second argument is not NULL, then its contents are prepended to
133213** the returned expression text and then freed using sqlite3_free().
133214*/
133215static char *exprToString(Fts3Expr *pExpr, char *zBuf){
133216  if( pExpr==0 ){
133217    return sqlite3_mprintf("");
133218  }
133219  switch( pExpr->eType ){
133220    case FTSQUERY_PHRASE: {
133221      Fts3Phrase *pPhrase = pExpr->pPhrase;
133222      int i;
133223      zBuf = sqlite3_mprintf(
133224          "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
133225      for(i=0; zBuf && i<pPhrase->nToken; i++){
133226        zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
133227            pPhrase->aToken[i].n, pPhrase->aToken[i].z,
133228            (pPhrase->aToken[i].isPrefix?"+":"")
133229        );
133230      }
133231      return zBuf;
133232    }
133233
133234    case FTSQUERY_NEAR:
133235      zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
133236      break;
133237    case FTSQUERY_NOT:
133238      zBuf = sqlite3_mprintf("%zNOT ", zBuf);
133239      break;
133240    case FTSQUERY_AND:
133241      zBuf = sqlite3_mprintf("%zAND ", zBuf);
133242      break;
133243    case FTSQUERY_OR:
133244      zBuf = sqlite3_mprintf("%zOR ", zBuf);
133245      break;
133246  }
133247
133248  if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
133249  if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
133250  if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
133251
133252  if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
133253  if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
133254
133255  return zBuf;
133256}
133257
133258/*
133259** This is the implementation of a scalar SQL function used to test the
133260** expression parser. It should be called as follows:
133261**
133262**   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
133263**
133264** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
133265** to parse the query expression (see README.tokenizers). The second argument
133266** is the query expression to parse. Each subsequent argument is the name
133267** of a column of the fts3 table that the query expression may refer to.
133268** For example:
133269**
133270**   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
133271*/
133272static void fts3ExprTest(
133273  sqlite3_context *context,
133274  int argc,
133275  sqlite3_value **argv
133276){
133277  sqlite3_tokenizer_module const *pModule = 0;
133278  sqlite3_tokenizer *pTokenizer = 0;
133279  int rc;
133280  char **azCol = 0;
133281  const char *zExpr;
133282  int nExpr;
133283  int nCol;
133284  int ii;
133285  Fts3Expr *pExpr;
133286  char *zBuf = 0;
133287  sqlite3 *db = sqlite3_context_db_handle(context);
133288
133289  if( argc<3 ){
133290    sqlite3_result_error(context,
133291        "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
133292    );
133293    return;
133294  }
133295
133296  rc = queryTestTokenizer(db,
133297                          (const char *)sqlite3_value_text(argv[0]), &pModule);
133298  if( rc==SQLITE_NOMEM ){
133299    sqlite3_result_error_nomem(context);
133300    goto exprtest_out;
133301  }else if( !pModule ){
133302    sqlite3_result_error(context, "No such tokenizer module", -1);
133303    goto exprtest_out;
133304  }
133305
133306  rc = pModule->xCreate(0, 0, &pTokenizer);
133307  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
133308  if( rc==SQLITE_NOMEM ){
133309    sqlite3_result_error_nomem(context);
133310    goto exprtest_out;
133311  }
133312  pTokenizer->pModule = pModule;
133313
133314  zExpr = (const char *)sqlite3_value_text(argv[1]);
133315  nExpr = sqlite3_value_bytes(argv[1]);
133316  nCol = argc-2;
133317  azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
133318  if( !azCol ){
133319    sqlite3_result_error_nomem(context);
133320    goto exprtest_out;
133321  }
133322  for(ii=0; ii<nCol; ii++){
133323    azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
133324  }
133325
133326  if( sqlite3_user_data(context) ){
133327    char *zDummy = 0;
133328    rc = sqlite3Fts3ExprParse(
133329        pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
133330    );
133331    assert( rc==SQLITE_OK || pExpr==0 );
133332    sqlite3_free(zDummy);
133333  }else{
133334    rc = fts3ExprParseUnbalanced(
133335        pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
133336    );
133337  }
133338
133339  if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
133340    sqlite3Fts3ExprFree(pExpr);
133341    sqlite3_result_error(context, "Error parsing expression", -1);
133342  }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
133343    sqlite3_result_error_nomem(context);
133344  }else{
133345    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
133346    sqlite3_free(zBuf);
133347  }
133348
133349  sqlite3Fts3ExprFree(pExpr);
133350
133351exprtest_out:
133352  if( pModule && pTokenizer ){
133353    rc = pModule->xDestroy(pTokenizer);
133354  }
133355  sqlite3_free(azCol);
133356}
133357
133358/*
133359** Register the query expression parser test function fts3_exprtest()
133360** with database connection db.
133361*/
133362SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
133363  int rc = sqlite3_create_function(
133364      db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
133365  );
133366  if( rc==SQLITE_OK ){
133367    rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
133368        -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
133369    );
133370  }
133371  return rc;
133372}
133373
133374#endif
133375#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
133376
133377/************** End of fts3_expr.c *******************************************/
133378/************** Begin file fts3_hash.c ***************************************/
133379/*
133380** 2001 September 22
133381**
133382** The author disclaims copyright to this source code.  In place of
133383** a legal notice, here is a blessing:
133384**
133385**    May you do good and not evil.
133386**    May you find forgiveness for yourself and forgive others.
133387**    May you share freely, never taking more than you give.
133388**
133389*************************************************************************
133390** This is the implementation of generic hash-tables used in SQLite.
133391** We've modified it slightly to serve as a standalone hash table
133392** implementation for the full-text indexing module.
133393*/
133394
133395/*
133396** The code in this file is only compiled if:
133397**
133398**     * The FTS3 module is being built as an extension
133399**       (in which case SQLITE_CORE is not defined), or
133400**
133401**     * The FTS3 module is being built into the core of
133402**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
133403*/
133404#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
133405
133406/* #include <assert.h> */
133407/* #include <stdlib.h> */
133408/* #include <string.h> */
133409
133410
133411/*
133412** Malloc and Free functions
133413*/
133414static void *fts3HashMalloc(int n){
133415  void *p = sqlite3_malloc(n);
133416  if( p ){
133417    memset(p, 0, n);
133418  }
133419  return p;
133420}
133421static void fts3HashFree(void *p){
133422  sqlite3_free(p);
133423}
133424
133425/* Turn bulk memory into a hash table object by initializing the
133426** fields of the Hash structure.
133427**
133428** "pNew" is a pointer to the hash table that is to be initialized.
133429** keyClass is one of the constants
133430** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass
133431** determines what kind of key the hash table will use.  "copyKey" is
133432** true if the hash table should make its own private copy of keys and
133433** false if it should just use the supplied pointer.
133434*/
133435SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
133436  assert( pNew!=0 );
133437  assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
133438  pNew->keyClass = keyClass;
133439  pNew->copyKey = copyKey;
133440  pNew->first = 0;
133441  pNew->count = 0;
133442  pNew->htsize = 0;
133443  pNew->ht = 0;
133444}
133445
133446/* Remove all entries from a hash table.  Reclaim all memory.
133447** Call this routine to delete a hash table or to reset a hash table
133448** to the empty state.
133449*/
133450SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
133451  Fts3HashElem *elem;         /* For looping over all elements of the table */
133452
133453  assert( pH!=0 );
133454  elem = pH->first;
133455  pH->first = 0;
133456  fts3HashFree(pH->ht);
133457  pH->ht = 0;
133458  pH->htsize = 0;
133459  while( elem ){
133460    Fts3HashElem *next_elem = elem->next;
133461    if( pH->copyKey && elem->pKey ){
133462      fts3HashFree(elem->pKey);
133463    }
133464    fts3HashFree(elem);
133465    elem = next_elem;
133466  }
133467  pH->count = 0;
133468}
133469
133470/*
133471** Hash and comparison functions when the mode is FTS3_HASH_STRING
133472*/
133473static int fts3StrHash(const void *pKey, int nKey){
133474  const char *z = (const char *)pKey;
133475  unsigned h = 0;
133476  if( nKey<=0 ) nKey = (int) strlen(z);
133477  while( nKey > 0  ){
133478    h = (h<<3) ^ h ^ *z++;
133479    nKey--;
133480  }
133481  return (int)(h & 0x7fffffff);
133482}
133483static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
133484  if( n1!=n2 ) return 1;
133485  return strncmp((const char*)pKey1,(const char*)pKey2,n1);
133486}
133487
133488/*
133489** Hash and comparison functions when the mode is FTS3_HASH_BINARY
133490*/
133491static int fts3BinHash(const void *pKey, int nKey){
133492  int h = 0;
133493  const char *z = (const char *)pKey;
133494  while( nKey-- > 0 ){
133495    h = (h<<3) ^ h ^ *(z++);
133496  }
133497  return h & 0x7fffffff;
133498}
133499static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
133500  if( n1!=n2 ) return 1;
133501  return memcmp(pKey1,pKey2,n1);
133502}
133503
133504/*
133505** Return a pointer to the appropriate hash function given the key class.
133506**
133507** The C syntax in this function definition may be unfamilar to some
133508** programmers, so we provide the following additional explanation:
133509**
133510** The name of the function is "ftsHashFunction".  The function takes a
133511** single parameter "keyClass".  The return value of ftsHashFunction()
133512** is a pointer to another function.  Specifically, the return value
133513** of ftsHashFunction() is a pointer to a function that takes two parameters
133514** with types "const void*" and "int" and returns an "int".
133515*/
133516static int (*ftsHashFunction(int keyClass))(const void*,int){
133517  if( keyClass==FTS3_HASH_STRING ){
133518    return &fts3StrHash;
133519  }else{
133520    assert( keyClass==FTS3_HASH_BINARY );
133521    return &fts3BinHash;
133522  }
133523}
133524
133525/*
133526** Return a pointer to the appropriate hash function given the key class.
133527**
133528** For help in interpreted the obscure C code in the function definition,
133529** see the header comment on the previous function.
133530*/
133531static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
133532  if( keyClass==FTS3_HASH_STRING ){
133533    return &fts3StrCompare;
133534  }else{
133535    assert( keyClass==FTS3_HASH_BINARY );
133536    return &fts3BinCompare;
133537  }
133538}
133539
133540/* Link an element into the hash table
133541*/
133542static void fts3HashInsertElement(
133543  Fts3Hash *pH,            /* The complete hash table */
133544  struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
133545  Fts3HashElem *pNew       /* The element to be inserted */
133546){
133547  Fts3HashElem *pHead;     /* First element already in pEntry */
133548  pHead = pEntry->chain;
133549  if( pHead ){
133550    pNew->next = pHead;
133551    pNew->prev = pHead->prev;
133552    if( pHead->prev ){ pHead->prev->next = pNew; }
133553    else             { pH->first = pNew; }
133554    pHead->prev = pNew;
133555  }else{
133556    pNew->next = pH->first;
133557    if( pH->first ){ pH->first->prev = pNew; }
133558    pNew->prev = 0;
133559    pH->first = pNew;
133560  }
133561  pEntry->count++;
133562  pEntry->chain = pNew;
133563}
133564
133565
133566/* Resize the hash table so that it cantains "new_size" buckets.
133567** "new_size" must be a power of 2.  The hash table might fail
133568** to resize if sqliteMalloc() fails.
133569**
133570** Return non-zero if a memory allocation error occurs.
133571*/
133572static int fts3Rehash(Fts3Hash *pH, int new_size){
133573  struct _fts3ht *new_ht;          /* The new hash table */
133574  Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
133575  int (*xHash)(const void*,int);   /* The hash function */
133576
133577  assert( (new_size & (new_size-1))==0 );
133578  new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
133579  if( new_ht==0 ) return 1;
133580  fts3HashFree(pH->ht);
133581  pH->ht = new_ht;
133582  pH->htsize = new_size;
133583  xHash = ftsHashFunction(pH->keyClass);
133584  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
133585    int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
133586    next_elem = elem->next;
133587    fts3HashInsertElement(pH, &new_ht[h], elem);
133588  }
133589  return 0;
133590}
133591
133592/* This function (for internal use only) locates an element in an
133593** hash table that matches the given key.  The hash for this key has
133594** already been computed and is passed as the 4th parameter.
133595*/
133596static Fts3HashElem *fts3FindElementByHash(
133597  const Fts3Hash *pH, /* The pH to be searched */
133598  const void *pKey,   /* The key we are searching for */
133599  int nKey,
133600  int h               /* The hash for this key. */
133601){
133602  Fts3HashElem *elem;            /* Used to loop thru the element list */
133603  int count;                     /* Number of elements left to test */
133604  int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
133605
133606  if( pH->ht ){
133607    struct _fts3ht *pEntry = &pH->ht[h];
133608    elem = pEntry->chain;
133609    count = pEntry->count;
133610    xCompare = ftsCompareFunction(pH->keyClass);
133611    while( count-- && elem ){
133612      if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
133613        return elem;
133614      }
133615      elem = elem->next;
133616    }
133617  }
133618  return 0;
133619}
133620
133621/* Remove a single entry from the hash table given a pointer to that
133622** element and a hash on the element's key.
133623*/
133624static void fts3RemoveElementByHash(
133625  Fts3Hash *pH,         /* The pH containing "elem" */
133626  Fts3HashElem* elem,   /* The element to be removed from the pH */
133627  int h                 /* Hash value for the element */
133628){
133629  struct _fts3ht *pEntry;
133630  if( elem->prev ){
133631    elem->prev->next = elem->next;
133632  }else{
133633    pH->first = elem->next;
133634  }
133635  if( elem->next ){
133636    elem->next->prev = elem->prev;
133637  }
133638  pEntry = &pH->ht[h];
133639  if( pEntry->chain==elem ){
133640    pEntry->chain = elem->next;
133641  }
133642  pEntry->count--;
133643  if( pEntry->count<=0 ){
133644    pEntry->chain = 0;
133645  }
133646  if( pH->copyKey && elem->pKey ){
133647    fts3HashFree(elem->pKey);
133648  }
133649  fts3HashFree( elem );
133650  pH->count--;
133651  if( pH->count<=0 ){
133652    assert( pH->first==0 );
133653    assert( pH->count==0 );
133654    fts3HashClear(pH);
133655  }
133656}
133657
133658SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
133659  const Fts3Hash *pH,
133660  const void *pKey,
133661  int nKey
133662){
133663  int h;                          /* A hash on key */
133664  int (*xHash)(const void*,int);  /* The hash function */
133665
133666  if( pH==0 || pH->ht==0 ) return 0;
133667  xHash = ftsHashFunction(pH->keyClass);
133668  assert( xHash!=0 );
133669  h = (*xHash)(pKey,nKey);
133670  assert( (pH->htsize & (pH->htsize-1))==0 );
133671  return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
133672}
133673
133674/*
133675** Attempt to locate an element of the hash table pH with a key
133676** that matches pKey,nKey.  Return the data for this element if it is
133677** found, or NULL if there is no match.
133678*/
133679SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
133680  Fts3HashElem *pElem;            /* The element that matches key (if any) */
133681
133682  pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
133683  return pElem ? pElem->data : 0;
133684}
133685
133686/* Insert an element into the hash table pH.  The key is pKey,nKey
133687** and the data is "data".
133688**
133689** If no element exists with a matching key, then a new
133690** element is created.  A copy of the key is made if the copyKey
133691** flag is set.  NULL is returned.
133692**
133693** If another element already exists with the same key, then the
133694** new data replaces the old data and the old data is returned.
133695** The key is not copied in this instance.  If a malloc fails, then
133696** the new data is returned and the hash table is unchanged.
133697**
133698** If the "data" parameter to this function is NULL, then the
133699** element corresponding to "key" is removed from the hash table.
133700*/
133701SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
133702  Fts3Hash *pH,        /* The hash table to insert into */
133703  const void *pKey,    /* The key */
133704  int nKey,            /* Number of bytes in the key */
133705  void *data           /* The data */
133706){
133707  int hraw;                 /* Raw hash value of the key */
133708  int h;                    /* the hash of the key modulo hash table size */
133709  Fts3HashElem *elem;       /* Used to loop thru the element list */
133710  Fts3HashElem *new_elem;   /* New element added to the pH */
133711  int (*xHash)(const void*,int);  /* The hash function */
133712
133713  assert( pH!=0 );
133714  xHash = ftsHashFunction(pH->keyClass);
133715  assert( xHash!=0 );
133716  hraw = (*xHash)(pKey, nKey);
133717  assert( (pH->htsize & (pH->htsize-1))==0 );
133718  h = hraw & (pH->htsize-1);
133719  elem = fts3FindElementByHash(pH,pKey,nKey,h);
133720  if( elem ){
133721    void *old_data = elem->data;
133722    if( data==0 ){
133723      fts3RemoveElementByHash(pH,elem,h);
133724    }else{
133725      elem->data = data;
133726    }
133727    return old_data;
133728  }
133729  if( data==0 ) return 0;
133730  if( (pH->htsize==0 && fts3Rehash(pH,8))
133731   || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
133732  ){
133733    pH->count = 0;
133734    return data;
133735  }
133736  assert( pH->htsize>0 );
133737  new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
133738  if( new_elem==0 ) return data;
133739  if( pH->copyKey && pKey!=0 ){
133740    new_elem->pKey = fts3HashMalloc( nKey );
133741    if( new_elem->pKey==0 ){
133742      fts3HashFree(new_elem);
133743      return data;
133744    }
133745    memcpy((void*)new_elem->pKey, pKey, nKey);
133746  }else{
133747    new_elem->pKey = (void*)pKey;
133748  }
133749  new_elem->nKey = nKey;
133750  pH->count++;
133751  assert( pH->htsize>0 );
133752  assert( (pH->htsize & (pH->htsize-1))==0 );
133753  h = hraw & (pH->htsize-1);
133754  fts3HashInsertElement(pH, &pH->ht[h], new_elem);
133755  new_elem->data = data;
133756  return 0;
133757}
133758
133759#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
133760
133761/************** End of fts3_hash.c *******************************************/
133762/************** Begin file fts3_porter.c *************************************/
133763/*
133764** 2006 September 30
133765**
133766** The author disclaims copyright to this source code.  In place of
133767** a legal notice, here is a blessing:
133768**
133769**    May you do good and not evil.
133770**    May you find forgiveness for yourself and forgive others.
133771**    May you share freely, never taking more than you give.
133772**
133773*************************************************************************
133774** Implementation of the full-text-search tokenizer that implements
133775** a Porter stemmer.
133776*/
133777
133778/*
133779** The code in this file is only compiled if:
133780**
133781**     * The FTS3 module is being built as an extension
133782**       (in which case SQLITE_CORE is not defined), or
133783**
133784**     * The FTS3 module is being built into the core of
133785**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
133786*/
133787#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
133788
133789/* #include <assert.h> */
133790/* #include <stdlib.h> */
133791/* #include <stdio.h> */
133792/* #include <string.h> */
133793
133794
133795/*
133796** Class derived from sqlite3_tokenizer
133797*/
133798typedef struct porter_tokenizer {
133799  sqlite3_tokenizer base;      /* Base class */
133800} porter_tokenizer;
133801
133802/*
133803** Class derived from sqlite3_tokenizer_cursor
133804*/
133805typedef struct porter_tokenizer_cursor {
133806  sqlite3_tokenizer_cursor base;
133807  const char *zInput;          /* input we are tokenizing */
133808  int nInput;                  /* size of the input */
133809  int iOffset;                 /* current position in zInput */
133810  int iToken;                  /* index of next token to be returned */
133811  char *zToken;                /* storage for current token */
133812  int nAllocated;              /* space allocated to zToken buffer */
133813} porter_tokenizer_cursor;
133814
133815
133816/*
133817** Create a new tokenizer instance.
133818*/
133819static int porterCreate(
133820  int argc, const char * const *argv,
133821  sqlite3_tokenizer **ppTokenizer
133822){
133823  porter_tokenizer *t;
133824
133825  UNUSED_PARAMETER(argc);
133826  UNUSED_PARAMETER(argv);
133827
133828  t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
133829  if( t==NULL ) return SQLITE_NOMEM;
133830  memset(t, 0, sizeof(*t));
133831  *ppTokenizer = &t->base;
133832  return SQLITE_OK;
133833}
133834
133835/*
133836** Destroy a tokenizer
133837*/
133838static int porterDestroy(sqlite3_tokenizer *pTokenizer){
133839  sqlite3_free(pTokenizer);
133840  return SQLITE_OK;
133841}
133842
133843/*
133844** Prepare to begin tokenizing a particular string.  The input
133845** string to be tokenized is zInput[0..nInput-1].  A cursor
133846** used to incrementally tokenize this string is returned in
133847** *ppCursor.
133848*/
133849static int porterOpen(
133850  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
133851  const char *zInput, int nInput,        /* String to be tokenized */
133852  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
133853){
133854  porter_tokenizer_cursor *c;
133855
133856  UNUSED_PARAMETER(pTokenizer);
133857
133858  c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
133859  if( c==NULL ) return SQLITE_NOMEM;
133860
133861  c->zInput = zInput;
133862  if( zInput==0 ){
133863    c->nInput = 0;
133864  }else if( nInput<0 ){
133865    c->nInput = (int)strlen(zInput);
133866  }else{
133867    c->nInput = nInput;
133868  }
133869  c->iOffset = 0;                 /* start tokenizing at the beginning */
133870  c->iToken = 0;
133871  c->zToken = NULL;               /* no space allocated, yet. */
133872  c->nAllocated = 0;
133873
133874  *ppCursor = &c->base;
133875  return SQLITE_OK;
133876}
133877
133878/*
133879** Close a tokenization cursor previously opened by a call to
133880** porterOpen() above.
133881*/
133882static int porterClose(sqlite3_tokenizer_cursor *pCursor){
133883  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
133884  sqlite3_free(c->zToken);
133885  sqlite3_free(c);
133886  return SQLITE_OK;
133887}
133888/*
133889** Vowel or consonant
133890*/
133891static const char cType[] = {
133892   0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
133893   1, 1, 1, 2, 1
133894};
133895
133896/*
133897** isConsonant() and isVowel() determine if their first character in
133898** the string they point to is a consonant or a vowel, according
133899** to Porter ruls.
133900**
133901** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
133902** 'Y' is a consonant unless it follows another consonant,
133903** in which case it is a vowel.
133904**
133905** In these routine, the letters are in reverse order.  So the 'y' rule
133906** is that 'y' is a consonant unless it is followed by another
133907** consonent.
133908*/
133909static int isVowel(const char*);
133910static int isConsonant(const char *z){
133911  int j;
133912  char x = *z;
133913  if( x==0 ) return 0;
133914  assert( x>='a' && x<='z' );
133915  j = cType[x-'a'];
133916  if( j<2 ) return j;
133917  return z[1]==0 || isVowel(z + 1);
133918}
133919static int isVowel(const char *z){
133920  int j;
133921  char x = *z;
133922  if( x==0 ) return 0;
133923  assert( x>='a' && x<='z' );
133924  j = cType[x-'a'];
133925  if( j<2 ) return 1-j;
133926  return isConsonant(z + 1);
133927}
133928
133929/*
133930** Let any sequence of one or more vowels be represented by V and let
133931** C be sequence of one or more consonants.  Then every word can be
133932** represented as:
133933**
133934**           [C] (VC){m} [V]
133935**
133936** In prose:  A word is an optional consonant followed by zero or
133937** vowel-consonant pairs followed by an optional vowel.  "m" is the
133938** number of vowel consonant pairs.  This routine computes the value
133939** of m for the first i bytes of a word.
133940**
133941** Return true if the m-value for z is 1 or more.  In other words,
133942** return true if z contains at least one vowel that is followed
133943** by a consonant.
133944**
133945** In this routine z[] is in reverse order.  So we are really looking
133946** for an instance of of a consonant followed by a vowel.
133947*/
133948static int m_gt_0(const char *z){
133949  while( isVowel(z) ){ z++; }
133950  if( *z==0 ) return 0;
133951  while( isConsonant(z) ){ z++; }
133952  return *z!=0;
133953}
133954
133955/* Like mgt0 above except we are looking for a value of m which is
133956** exactly 1
133957*/
133958static int m_eq_1(const char *z){
133959  while( isVowel(z) ){ z++; }
133960  if( *z==0 ) return 0;
133961  while( isConsonant(z) ){ z++; }
133962  if( *z==0 ) return 0;
133963  while( isVowel(z) ){ z++; }
133964  if( *z==0 ) return 1;
133965  while( isConsonant(z) ){ z++; }
133966  return *z==0;
133967}
133968
133969/* Like mgt0 above except we are looking for a value of m>1 instead
133970** or m>0
133971*/
133972static int m_gt_1(const char *z){
133973  while( isVowel(z) ){ z++; }
133974  if( *z==0 ) return 0;
133975  while( isConsonant(z) ){ z++; }
133976  if( *z==0 ) return 0;
133977  while( isVowel(z) ){ z++; }
133978  if( *z==0 ) return 0;
133979  while( isConsonant(z) ){ z++; }
133980  return *z!=0;
133981}
133982
133983/*
133984** Return TRUE if there is a vowel anywhere within z[0..n-1]
133985*/
133986static int hasVowel(const char *z){
133987  while( isConsonant(z) ){ z++; }
133988  return *z!=0;
133989}
133990
133991/*
133992** Return TRUE if the word ends in a double consonant.
133993**
133994** The text is reversed here. So we are really looking at
133995** the first two characters of z[].
133996*/
133997static int doubleConsonant(const char *z){
133998  return isConsonant(z) && z[0]==z[1];
133999}
134000
134001/*
134002** Return TRUE if the word ends with three letters which
134003** are consonant-vowel-consonent and where the final consonant
134004** is not 'w', 'x', or 'y'.
134005**
134006** The word is reversed here.  So we are really checking the
134007** first three letters and the first one cannot be in [wxy].
134008*/
134009static int star_oh(const char *z){
134010  return
134011    isConsonant(z) &&
134012    z[0]!='w' && z[0]!='x' && z[0]!='y' &&
134013    isVowel(z+1) &&
134014    isConsonant(z+2);
134015}
134016
134017/*
134018** If the word ends with zFrom and xCond() is true for the stem
134019** of the word that preceeds the zFrom ending, then change the
134020** ending to zTo.
134021**
134022** The input word *pz and zFrom are both in reverse order.  zTo
134023** is in normal order.
134024**
134025** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
134026** match.  Not that TRUE is returned even if xCond() fails and
134027** no substitution occurs.
134028*/
134029static int stem(
134030  char **pz,             /* The word being stemmed (Reversed) */
134031  const char *zFrom,     /* If the ending matches this... (Reversed) */
134032  const char *zTo,       /* ... change the ending to this (not reversed) */
134033  int (*xCond)(const char*)   /* Condition that must be true */
134034){
134035  char *z = *pz;
134036  while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
134037  if( *zFrom!=0 ) return 0;
134038  if( xCond && !xCond(z) ) return 1;
134039  while( *zTo ){
134040    *(--z) = *(zTo++);
134041  }
134042  *pz = z;
134043  return 1;
134044}
134045
134046/*
134047** This is the fallback stemmer used when the porter stemmer is
134048** inappropriate.  The input word is copied into the output with
134049** US-ASCII case folding.  If the input word is too long (more
134050** than 20 bytes if it contains no digits or more than 6 bytes if
134051** it contains digits) then word is truncated to 20 or 6 bytes
134052** by taking 10 or 3 bytes from the beginning and end.
134053*/
134054static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
134055  int i, mx, j;
134056  int hasDigit = 0;
134057  for(i=0; i<nIn; i++){
134058    char c = zIn[i];
134059    if( c>='A' && c<='Z' ){
134060      zOut[i] = c - 'A' + 'a';
134061    }else{
134062      if( c>='0' && c<='9' ) hasDigit = 1;
134063      zOut[i] = c;
134064    }
134065  }
134066  mx = hasDigit ? 3 : 10;
134067  if( nIn>mx*2 ){
134068    for(j=mx, i=nIn-mx; i<nIn; i++, j++){
134069      zOut[j] = zOut[i];
134070    }
134071    i = j;
134072  }
134073  zOut[i] = 0;
134074  *pnOut = i;
134075}
134076
134077
134078/*
134079** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
134080** zOut is at least big enough to hold nIn bytes.  Write the actual
134081** size of the output word (exclusive of the '\0' terminator) into *pnOut.
134082**
134083** Any upper-case characters in the US-ASCII character set ([A-Z])
134084** are converted to lower case.  Upper-case UTF characters are
134085** unchanged.
134086**
134087** Words that are longer than about 20 bytes are stemmed by retaining
134088** a few bytes from the beginning and the end of the word.  If the
134089** word contains digits, 3 bytes are taken from the beginning and
134090** 3 bytes from the end.  For long words without digits, 10 bytes
134091** are taken from each end.  US-ASCII case folding still applies.
134092**
134093** If the input word contains not digits but does characters not
134094** in [a-zA-Z] then no stemming is attempted and this routine just
134095** copies the input into the input into the output with US-ASCII
134096** case folding.
134097**
134098** Stemming never increases the length of the word.  So there is
134099** no chance of overflowing the zOut buffer.
134100*/
134101static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
134102  int i, j;
134103  char zReverse[28];
134104  char *z, *z2;
134105  if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
134106    /* The word is too big or too small for the porter stemmer.
134107    ** Fallback to the copy stemmer */
134108    copy_stemmer(zIn, nIn, zOut, pnOut);
134109    return;
134110  }
134111  for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
134112    char c = zIn[i];
134113    if( c>='A' && c<='Z' ){
134114      zReverse[j] = c + 'a' - 'A';
134115    }else if( c>='a' && c<='z' ){
134116      zReverse[j] = c;
134117    }else{
134118      /* The use of a character not in [a-zA-Z] means that we fallback
134119      ** to the copy stemmer */
134120      copy_stemmer(zIn, nIn, zOut, pnOut);
134121      return;
134122    }
134123  }
134124  memset(&zReverse[sizeof(zReverse)-5], 0, 5);
134125  z = &zReverse[j+1];
134126
134127
134128  /* Step 1a */
134129  if( z[0]=='s' ){
134130    if(
134131     !stem(&z, "sess", "ss", 0) &&
134132     !stem(&z, "sei", "i", 0)  &&
134133     !stem(&z, "ss", "ss", 0)
134134    ){
134135      z++;
134136    }
134137  }
134138
134139  /* Step 1b */
134140  z2 = z;
134141  if( stem(&z, "dee", "ee", m_gt_0) ){
134142    /* Do nothing.  The work was all in the test */
134143  }else if(
134144     (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
134145      && z!=z2
134146  ){
134147     if( stem(&z, "ta", "ate", 0) ||
134148         stem(&z, "lb", "ble", 0) ||
134149         stem(&z, "zi", "ize", 0) ){
134150       /* Do nothing.  The work was all in the test */
134151     }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
134152       z++;
134153     }else if( m_eq_1(z) && star_oh(z) ){
134154       *(--z) = 'e';
134155     }
134156  }
134157
134158  /* Step 1c */
134159  if( z[0]=='y' && hasVowel(z+1) ){
134160    z[0] = 'i';
134161  }
134162
134163  /* Step 2 */
134164  switch( z[1] ){
134165   case 'a':
134166     if( !stem(&z, "lanoita", "ate", m_gt_0) ){
134167       stem(&z, "lanoit", "tion", m_gt_0);
134168     }
134169     break;
134170   case 'c':
134171     if( !stem(&z, "icne", "ence", m_gt_0) ){
134172       stem(&z, "icna", "ance", m_gt_0);
134173     }
134174     break;
134175   case 'e':
134176     stem(&z, "rezi", "ize", m_gt_0);
134177     break;
134178   case 'g':
134179     stem(&z, "igol", "log", m_gt_0);
134180     break;
134181   case 'l':
134182     if( !stem(&z, "ilb", "ble", m_gt_0)
134183      && !stem(&z, "illa", "al", m_gt_0)
134184      && !stem(&z, "iltne", "ent", m_gt_0)
134185      && !stem(&z, "ile", "e", m_gt_0)
134186     ){
134187       stem(&z, "ilsuo", "ous", m_gt_0);
134188     }
134189     break;
134190   case 'o':
134191     if( !stem(&z, "noitazi", "ize", m_gt_0)
134192      && !stem(&z, "noita", "ate", m_gt_0)
134193     ){
134194       stem(&z, "rota", "ate", m_gt_0);
134195     }
134196     break;
134197   case 's':
134198     if( !stem(&z, "msila", "al", m_gt_0)
134199      && !stem(&z, "ssenevi", "ive", m_gt_0)
134200      && !stem(&z, "ssenluf", "ful", m_gt_0)
134201     ){
134202       stem(&z, "ssensuo", "ous", m_gt_0);
134203     }
134204     break;
134205   case 't':
134206     if( !stem(&z, "itila", "al", m_gt_0)
134207      && !stem(&z, "itivi", "ive", m_gt_0)
134208     ){
134209       stem(&z, "itilib", "ble", m_gt_0);
134210     }
134211     break;
134212  }
134213
134214  /* Step 3 */
134215  switch( z[0] ){
134216   case 'e':
134217     if( !stem(&z, "etaci", "ic", m_gt_0)
134218      && !stem(&z, "evita", "", m_gt_0)
134219     ){
134220       stem(&z, "ezila", "al", m_gt_0);
134221     }
134222     break;
134223   case 'i':
134224     stem(&z, "itici", "ic", m_gt_0);
134225     break;
134226   case 'l':
134227     if( !stem(&z, "laci", "ic", m_gt_0) ){
134228       stem(&z, "luf", "", m_gt_0);
134229     }
134230     break;
134231   case 's':
134232     stem(&z, "ssen", "", m_gt_0);
134233     break;
134234  }
134235
134236  /* Step 4 */
134237  switch( z[1] ){
134238   case 'a':
134239     if( z[0]=='l' && m_gt_1(z+2) ){
134240       z += 2;
134241     }
134242     break;
134243   case 'c':
134244     if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
134245       z += 4;
134246     }
134247     break;
134248   case 'e':
134249     if( z[0]=='r' && m_gt_1(z+2) ){
134250       z += 2;
134251     }
134252     break;
134253   case 'i':
134254     if( z[0]=='c' && m_gt_1(z+2) ){
134255       z += 2;
134256     }
134257     break;
134258   case 'l':
134259     if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
134260       z += 4;
134261     }
134262     break;
134263   case 'n':
134264     if( z[0]=='t' ){
134265       if( z[2]=='a' ){
134266         if( m_gt_1(z+3) ){
134267           z += 3;
134268         }
134269       }else if( z[2]=='e' ){
134270         if( !stem(&z, "tneme", "", m_gt_1)
134271          && !stem(&z, "tnem", "", m_gt_1)
134272         ){
134273           stem(&z, "tne", "", m_gt_1);
134274         }
134275       }
134276     }
134277     break;
134278   case 'o':
134279     if( z[0]=='u' ){
134280       if( m_gt_1(z+2) ){
134281         z += 2;
134282       }
134283     }else if( z[3]=='s' || z[3]=='t' ){
134284       stem(&z, "noi", "", m_gt_1);
134285     }
134286     break;
134287   case 's':
134288     if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
134289       z += 3;
134290     }
134291     break;
134292   case 't':
134293     if( !stem(&z, "eta", "", m_gt_1) ){
134294       stem(&z, "iti", "", m_gt_1);
134295     }
134296     break;
134297   case 'u':
134298     if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
134299       z += 3;
134300     }
134301     break;
134302   case 'v':
134303   case 'z':
134304     if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
134305       z += 3;
134306     }
134307     break;
134308  }
134309
134310  /* Step 5a */
134311  if( z[0]=='e' ){
134312    if( m_gt_1(z+1) ){
134313      z++;
134314    }else if( m_eq_1(z+1) && !star_oh(z+1) ){
134315      z++;
134316    }
134317  }
134318
134319  /* Step 5b */
134320  if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
134321    z++;
134322  }
134323
134324  /* z[] is now the stemmed word in reverse order.  Flip it back
134325  ** around into forward order and return.
134326  */
134327  *pnOut = i = (int)strlen(z);
134328  zOut[i] = 0;
134329  while( *z ){
134330    zOut[--i] = *(z++);
134331  }
134332}
134333
134334/*
134335** Characters that can be part of a token.  We assume any character
134336** whose value is greater than 0x80 (any UTF character) can be
134337** part of a token.  In other words, delimiters all must have
134338** values of 0x7f or lower.
134339*/
134340static const char porterIdChar[] = {
134341/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
134342    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
134343    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
134344    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
134345    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
134346    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
134347};
134348#define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
134349
134350/*
134351** Extract the next token from a tokenization cursor.  The cursor must
134352** have been opened by a prior call to porterOpen().
134353*/
134354static int porterNext(
134355  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
134356  const char **pzToken,               /* OUT: *pzToken is the token text */
134357  int *pnBytes,                       /* OUT: Number of bytes in token */
134358  int *piStartOffset,                 /* OUT: Starting offset of token */
134359  int *piEndOffset,                   /* OUT: Ending offset of token */
134360  int *piPosition                     /* OUT: Position integer of token */
134361){
134362  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
134363  const char *z = c->zInput;
134364
134365  while( c->iOffset<c->nInput ){
134366    int iStartOffset, ch;
134367
134368    /* Scan past delimiter characters */
134369    while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
134370      c->iOffset++;
134371    }
134372
134373    /* Count non-delimiter characters. */
134374    iStartOffset = c->iOffset;
134375    while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
134376      c->iOffset++;
134377    }
134378
134379    if( c->iOffset>iStartOffset ){
134380      int n = c->iOffset-iStartOffset;
134381      if( n>c->nAllocated ){
134382        char *pNew;
134383        c->nAllocated = n+20;
134384        pNew = sqlite3_realloc(c->zToken, c->nAllocated);
134385        if( !pNew ) return SQLITE_NOMEM;
134386        c->zToken = pNew;
134387      }
134388      porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
134389      *pzToken = c->zToken;
134390      *piStartOffset = iStartOffset;
134391      *piEndOffset = c->iOffset;
134392      *piPosition = c->iToken++;
134393      return SQLITE_OK;
134394    }
134395  }
134396  return SQLITE_DONE;
134397}
134398
134399/*
134400** The set of routines that implement the porter-stemmer tokenizer
134401*/
134402static const sqlite3_tokenizer_module porterTokenizerModule = {
134403  0,
134404  porterCreate,
134405  porterDestroy,
134406  porterOpen,
134407  porterClose,
134408  porterNext,
134409  0
134410};
134411
134412/*
134413** Allocate a new porter tokenizer.  Return a pointer to the new
134414** tokenizer in *ppModule
134415*/
134416SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
134417  sqlite3_tokenizer_module const**ppModule
134418){
134419  *ppModule = &porterTokenizerModule;
134420}
134421
134422#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
134423
134424/************** End of fts3_porter.c *****************************************/
134425/************** Begin file fts3_tokenizer.c **********************************/
134426/*
134427** 2007 June 22
134428**
134429** The author disclaims copyright to this source code.  In place of
134430** a legal notice, here is a blessing:
134431**
134432**    May you do good and not evil.
134433**    May you find forgiveness for yourself and forgive others.
134434**    May you share freely, never taking more than you give.
134435**
134436******************************************************************************
134437**
134438** This is part of an SQLite module implementing full-text search.
134439** This particular file implements the generic tokenizer interface.
134440*/
134441
134442/*
134443** The code in this file is only compiled if:
134444**
134445**     * The FTS3 module is being built as an extension
134446**       (in which case SQLITE_CORE is not defined), or
134447**
134448**     * The FTS3 module is being built into the core of
134449**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
134450*/
134451#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
134452
134453/* #include <assert.h> */
134454/* #include <string.h> */
134455
134456/*
134457** Implementation of the SQL scalar function for accessing the underlying
134458** hash table. This function may be called as follows:
134459**
134460**   SELECT <function-name>(<key-name>);
134461**   SELECT <function-name>(<key-name>, <pointer>);
134462**
134463** where <function-name> is the name passed as the second argument
134464** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
134465**
134466** If the <pointer> argument is specified, it must be a blob value
134467** containing a pointer to be stored as the hash data corresponding
134468** to the string <key-name>. If <pointer> is not specified, then
134469** the string <key-name> must already exist in the has table. Otherwise,
134470** an error is returned.
134471**
134472** Whether or not the <pointer> argument is specified, the value returned
134473** is a blob containing the pointer stored as the hash data corresponding
134474** to string <key-name> (after the hash-table is updated, if applicable).
134475*/
134476static void scalarFunc(
134477  sqlite3_context *context,
134478  int argc,
134479  sqlite3_value **argv
134480){
134481  Fts3Hash *pHash;
134482  void *pPtr = 0;
134483  const unsigned char *zName;
134484  int nName;
134485
134486  assert( argc==1 || argc==2 );
134487
134488  pHash = (Fts3Hash *)sqlite3_user_data(context);
134489
134490  zName = sqlite3_value_text(argv[0]);
134491  nName = sqlite3_value_bytes(argv[0])+1;
134492
134493  if( argc==2 ){
134494    void *pOld;
134495    int n = sqlite3_value_bytes(argv[1]);
134496    if( n!=sizeof(pPtr) ){
134497      sqlite3_result_error(context, "argument type mismatch", -1);
134498      return;
134499    }
134500    pPtr = *(void **)sqlite3_value_blob(argv[1]);
134501    pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
134502    if( pOld==pPtr ){
134503      sqlite3_result_error(context, "out of memory", -1);
134504      return;
134505    }
134506  }else{
134507    pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
134508    if( !pPtr ){
134509      char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
134510      sqlite3_result_error(context, zErr, -1);
134511      sqlite3_free(zErr);
134512      return;
134513    }
134514  }
134515
134516  sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
134517}
134518
134519SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
134520  static const char isFtsIdChar[] = {
134521      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
134522      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
134523      0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
134524      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
134525      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
134526      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
134527      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
134528      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
134529  };
134530  return (c&0x80 || isFtsIdChar[(int)(c)]);
134531}
134532
134533SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
134534  const char *z1;
134535  const char *z2 = 0;
134536
134537  /* Find the start of the next token. */
134538  z1 = zStr;
134539  while( z2==0 ){
134540    char c = *z1;
134541    switch( c ){
134542      case '\0': return 0;        /* No more tokens here */
134543      case '\'':
134544      case '"':
134545      case '`': {
134546        z2 = z1;
134547        while( *++z2 && (*z2!=c || *++z2==c) );
134548        break;
134549      }
134550      case '[':
134551        z2 = &z1[1];
134552        while( *z2 && z2[0]!=']' ) z2++;
134553        if( *z2 ) z2++;
134554        break;
134555
134556      default:
134557        if( sqlite3Fts3IsIdChar(*z1) ){
134558          z2 = &z1[1];
134559          while( sqlite3Fts3IsIdChar(*z2) ) z2++;
134560        }else{
134561          z1++;
134562        }
134563    }
134564  }
134565
134566  *pn = (int)(z2-z1);
134567  return z1;
134568}
134569
134570SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
134571  Fts3Hash *pHash,                /* Tokenizer hash table */
134572  const char *zArg,               /* Tokenizer name */
134573  sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
134574  char **pzErr                    /* OUT: Set to malloced error message */
134575){
134576  int rc;
134577  char *z = (char *)zArg;
134578  int n = 0;
134579  char *zCopy;
134580  char *zEnd;                     /* Pointer to nul-term of zCopy */
134581  sqlite3_tokenizer_module *m;
134582
134583  zCopy = sqlite3_mprintf("%s", zArg);
134584  if( !zCopy ) return SQLITE_NOMEM;
134585  zEnd = &zCopy[strlen(zCopy)];
134586
134587  z = (char *)sqlite3Fts3NextToken(zCopy, &n);
134588  z[n] = '\0';
134589  sqlite3Fts3Dequote(z);
134590
134591  m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
134592  if( !m ){
134593    *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
134594    rc = SQLITE_ERROR;
134595  }else{
134596    char const **aArg = 0;
134597    int iArg = 0;
134598    z = &z[n+1];
134599    while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
134600      int nNew = sizeof(char *)*(iArg+1);
134601      char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
134602      if( !aNew ){
134603        sqlite3_free(zCopy);
134604        sqlite3_free((void *)aArg);
134605        return SQLITE_NOMEM;
134606      }
134607      aArg = aNew;
134608      aArg[iArg++] = z;
134609      z[n] = '\0';
134610      sqlite3Fts3Dequote(z);
134611      z = &z[n+1];
134612    }
134613    rc = m->xCreate(iArg, aArg, ppTok);
134614    assert( rc!=SQLITE_OK || *ppTok );
134615    if( rc!=SQLITE_OK ){
134616      *pzErr = sqlite3_mprintf("unknown tokenizer");
134617    }else{
134618      (*ppTok)->pModule = m;
134619    }
134620    sqlite3_free((void *)aArg);
134621  }
134622
134623  sqlite3_free(zCopy);
134624  return rc;
134625}
134626
134627
134628#ifdef SQLITE_TEST
134629
134630#include <tcl.h>
134631/* #include <string.h> */
134632
134633/*
134634** Implementation of a special SQL scalar function for testing tokenizers
134635** designed to be used in concert with the Tcl testing framework. This
134636** function must be called with two or more arguments:
134637**
134638**   SELECT <function-name>(<key-name>, ..., <input-string>);
134639**
134640** where <function-name> is the name passed as the second argument
134641** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
134642** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
134643**
134644** The return value is a string that may be interpreted as a Tcl
134645** list. For each token in the <input-string>, three elements are
134646** added to the returned list. The first is the token position, the
134647** second is the token text (folded, stemmed, etc.) and the third is the
134648** substring of <input-string> associated with the token. For example,
134649** using the built-in "simple" tokenizer:
134650**
134651**   SELECT fts_tokenizer_test('simple', 'I don't see how');
134652**
134653** will return the string:
134654**
134655**   "{0 i I 1 dont don't 2 see see 3 how how}"
134656**
134657*/
134658static void testFunc(
134659  sqlite3_context *context,
134660  int argc,
134661  sqlite3_value **argv
134662){
134663  Fts3Hash *pHash;
134664  sqlite3_tokenizer_module *p;
134665  sqlite3_tokenizer *pTokenizer = 0;
134666  sqlite3_tokenizer_cursor *pCsr = 0;
134667
134668  const char *zErr = 0;
134669
134670  const char *zName;
134671  int nName;
134672  const char *zInput;
134673  int nInput;
134674
134675  const char *azArg[64];
134676
134677  const char *zToken;
134678  int nToken = 0;
134679  int iStart = 0;
134680  int iEnd = 0;
134681  int iPos = 0;
134682  int i;
134683
134684  Tcl_Obj *pRet;
134685
134686  if( argc<2 ){
134687    sqlite3_result_error(context, "insufficient arguments", -1);
134688    return;
134689  }
134690
134691  nName = sqlite3_value_bytes(argv[0]);
134692  zName = (const char *)sqlite3_value_text(argv[0]);
134693  nInput = sqlite3_value_bytes(argv[argc-1]);
134694  zInput = (const char *)sqlite3_value_text(argv[argc-1]);
134695
134696  pHash = (Fts3Hash *)sqlite3_user_data(context);
134697  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
134698
134699  if( !p ){
134700    char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
134701    sqlite3_result_error(context, zErr, -1);
134702    sqlite3_free(zErr);
134703    return;
134704  }
134705
134706  pRet = Tcl_NewObj();
134707  Tcl_IncrRefCount(pRet);
134708
134709  for(i=1; i<argc-1; i++){
134710    azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
134711  }
134712
134713  if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
134714    zErr = "error in xCreate()";
134715    goto finish;
134716  }
134717  pTokenizer->pModule = p;
134718  if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
134719    zErr = "error in xOpen()";
134720    goto finish;
134721  }
134722
134723  while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
134724    Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
134725    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
134726    zToken = &zInput[iStart];
134727    nToken = iEnd-iStart;
134728    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
134729  }
134730
134731  if( SQLITE_OK!=p->xClose(pCsr) ){
134732    zErr = "error in xClose()";
134733    goto finish;
134734  }
134735  if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
134736    zErr = "error in xDestroy()";
134737    goto finish;
134738  }
134739
134740finish:
134741  if( zErr ){
134742    sqlite3_result_error(context, zErr, -1);
134743  }else{
134744    sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
134745  }
134746  Tcl_DecrRefCount(pRet);
134747}
134748
134749static
134750int registerTokenizer(
134751  sqlite3 *db,
134752  char *zName,
134753  const sqlite3_tokenizer_module *p
134754){
134755  int rc;
134756  sqlite3_stmt *pStmt;
134757  const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
134758
134759  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
134760  if( rc!=SQLITE_OK ){
134761    return rc;
134762  }
134763
134764  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
134765  sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
134766  sqlite3_step(pStmt);
134767
134768  return sqlite3_finalize(pStmt);
134769}
134770
134771static
134772int queryTokenizer(
134773  sqlite3 *db,
134774  char *zName,
134775  const sqlite3_tokenizer_module **pp
134776){
134777  int rc;
134778  sqlite3_stmt *pStmt;
134779  const char zSql[] = "SELECT fts3_tokenizer(?)";
134780
134781  *pp = 0;
134782  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
134783  if( rc!=SQLITE_OK ){
134784    return rc;
134785  }
134786
134787  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
134788  if( SQLITE_ROW==sqlite3_step(pStmt) ){
134789    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
134790      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
134791    }
134792  }
134793
134794  return sqlite3_finalize(pStmt);
134795}
134796
134797SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
134798
134799/*
134800** Implementation of the scalar function fts3_tokenizer_internal_test().
134801** This function is used for testing only, it is not included in the
134802** build unless SQLITE_TEST is defined.
134803**
134804** The purpose of this is to test that the fts3_tokenizer() function
134805** can be used as designed by the C-code in the queryTokenizer and
134806** registerTokenizer() functions above. These two functions are repeated
134807** in the README.tokenizer file as an example, so it is important to
134808** test them.
134809**
134810** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
134811** function with no arguments. An assert() will fail if a problem is
134812** detected. i.e.:
134813**
134814**     SELECT fts3_tokenizer_internal_test();
134815**
134816*/
134817static void intTestFunc(
134818  sqlite3_context *context,
134819  int argc,
134820  sqlite3_value **argv
134821){
134822  int rc;
134823  const sqlite3_tokenizer_module *p1;
134824  const sqlite3_tokenizer_module *p2;
134825  sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
134826
134827  UNUSED_PARAMETER(argc);
134828  UNUSED_PARAMETER(argv);
134829
134830  /* Test the query function */
134831  sqlite3Fts3SimpleTokenizerModule(&p1);
134832  rc = queryTokenizer(db, "simple", &p2);
134833  assert( rc==SQLITE_OK );
134834  assert( p1==p2 );
134835  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
134836  assert( rc==SQLITE_ERROR );
134837  assert( p2==0 );
134838  assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
134839
134840  /* Test the storage function */
134841  rc = registerTokenizer(db, "nosuchtokenizer", p1);
134842  assert( rc==SQLITE_OK );
134843  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
134844  assert( rc==SQLITE_OK );
134845  assert( p2==p1 );
134846
134847  sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
134848}
134849
134850#endif
134851
134852/*
134853** Set up SQL objects in database db used to access the contents of
134854** the hash table pointed to by argument pHash. The hash table must
134855** been initialized to use string keys, and to take a private copy
134856** of the key when a value is inserted. i.e. by a call similar to:
134857**
134858**    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
134859**
134860** This function adds a scalar function (see header comment above
134861** scalarFunc() in this file for details) and, if ENABLE_TABLE is
134862** defined at compilation time, a temporary virtual table (see header
134863** comment above struct HashTableVtab) to the database schema. Both
134864** provide read/write access to the contents of *pHash.
134865**
134866** The third argument to this function, zName, is used as the name
134867** of both the scalar and, if created, the virtual table.
134868*/
134869SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
134870  sqlite3 *db,
134871  Fts3Hash *pHash,
134872  const char *zName
134873){
134874  int rc = SQLITE_OK;
134875  void *p = (void *)pHash;
134876  const int any = SQLITE_ANY;
134877
134878#ifdef SQLITE_TEST
134879  char *zTest = 0;
134880  char *zTest2 = 0;
134881  void *pdb = (void *)db;
134882  zTest = sqlite3_mprintf("%s_test", zName);
134883  zTest2 = sqlite3_mprintf("%s_internal_test", zName);
134884  if( !zTest || !zTest2 ){
134885    rc = SQLITE_NOMEM;
134886  }
134887#endif
134888
134889  if( SQLITE_OK==rc ){
134890    rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
134891  }
134892  if( SQLITE_OK==rc ){
134893    rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
134894  }
134895#ifdef SQLITE_TEST
134896  if( SQLITE_OK==rc ){
134897    rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
134898  }
134899  if( SQLITE_OK==rc ){
134900    rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
134901  }
134902#endif
134903
134904#ifdef SQLITE_TEST
134905  sqlite3_free(zTest);
134906  sqlite3_free(zTest2);
134907#endif
134908
134909  return rc;
134910}
134911
134912#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
134913
134914/************** End of fts3_tokenizer.c **************************************/
134915/************** Begin file fts3_tokenizer1.c *********************************/
134916/*
134917** 2006 Oct 10
134918**
134919** The author disclaims copyright to this source code.  In place of
134920** a legal notice, here is a blessing:
134921**
134922**    May you do good and not evil.
134923**    May you find forgiveness for yourself and forgive others.
134924**    May you share freely, never taking more than you give.
134925**
134926******************************************************************************
134927**
134928** Implementation of the "simple" full-text-search tokenizer.
134929*/
134930
134931/*
134932** The code in this file is only compiled if:
134933**
134934**     * The FTS3 module is being built as an extension
134935**       (in which case SQLITE_CORE is not defined), or
134936**
134937**     * The FTS3 module is being built into the core of
134938**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
134939*/
134940#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
134941
134942/* #include <assert.h> */
134943/* #include <stdlib.h> */
134944/* #include <stdio.h> */
134945/* #include <string.h> */
134946
134947
134948typedef struct simple_tokenizer {
134949  sqlite3_tokenizer base;
134950  char delim[128];             /* flag ASCII delimiters */
134951} simple_tokenizer;
134952
134953typedef struct simple_tokenizer_cursor {
134954  sqlite3_tokenizer_cursor base;
134955  const char *pInput;          /* input we are tokenizing */
134956  int nBytes;                  /* size of the input */
134957  int iOffset;                 /* current position in pInput */
134958  int iToken;                  /* index of next token to be returned */
134959  char *pToken;                /* storage for current token */
134960  int nTokenAllocated;         /* space allocated to zToken buffer */
134961} simple_tokenizer_cursor;
134962
134963
134964static int simpleDelim(simple_tokenizer *t, unsigned char c){
134965  return c<0x80 && t->delim[c];
134966}
134967static int fts3_isalnum(int x){
134968  return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
134969}
134970
134971/*
134972** Create a new tokenizer instance.
134973*/
134974static int simpleCreate(
134975  int argc, const char * const *argv,
134976  sqlite3_tokenizer **ppTokenizer
134977){
134978  simple_tokenizer *t;
134979
134980  t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
134981  if( t==NULL ) return SQLITE_NOMEM;
134982  memset(t, 0, sizeof(*t));
134983
134984  /* TODO(shess) Delimiters need to remain the same from run to run,
134985  ** else we need to reindex.  One solution would be a meta-table to
134986  ** track such information in the database, then we'd only want this
134987  ** information on the initial create.
134988  */
134989  if( argc>1 ){
134990    int i, n = (int)strlen(argv[1]);
134991    for(i=0; i<n; i++){
134992      unsigned char ch = argv[1][i];
134993      /* We explicitly don't support UTF-8 delimiters for now. */
134994      if( ch>=0x80 ){
134995        sqlite3_free(t);
134996        return SQLITE_ERROR;
134997      }
134998      t->delim[ch] = 1;
134999    }
135000  } else {
135001    /* Mark non-alphanumeric ASCII characters as delimiters */
135002    int i;
135003    for(i=1; i<0x80; i++){
135004      t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
135005    }
135006  }
135007
135008  *ppTokenizer = &t->base;
135009  return SQLITE_OK;
135010}
135011
135012/*
135013** Destroy a tokenizer
135014*/
135015static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
135016  sqlite3_free(pTokenizer);
135017  return SQLITE_OK;
135018}
135019
135020/*
135021** Prepare to begin tokenizing a particular string.  The input
135022** string to be tokenized is pInput[0..nBytes-1].  A cursor
135023** used to incrementally tokenize this string is returned in
135024** *ppCursor.
135025*/
135026static int simpleOpen(
135027  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
135028  const char *pInput, int nBytes,        /* String to be tokenized */
135029  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
135030){
135031  simple_tokenizer_cursor *c;
135032
135033  UNUSED_PARAMETER(pTokenizer);
135034
135035  c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
135036  if( c==NULL ) return SQLITE_NOMEM;
135037
135038  c->pInput = pInput;
135039  if( pInput==0 ){
135040    c->nBytes = 0;
135041  }else if( nBytes<0 ){
135042    c->nBytes = (int)strlen(pInput);
135043  }else{
135044    c->nBytes = nBytes;
135045  }
135046  c->iOffset = 0;                 /* start tokenizing at the beginning */
135047  c->iToken = 0;
135048  c->pToken = NULL;               /* no space allocated, yet. */
135049  c->nTokenAllocated = 0;
135050
135051  *ppCursor = &c->base;
135052  return SQLITE_OK;
135053}
135054
135055/*
135056** Close a tokenization cursor previously opened by a call to
135057** simpleOpen() above.
135058*/
135059static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
135060  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
135061  sqlite3_free(c->pToken);
135062  sqlite3_free(c);
135063  return SQLITE_OK;
135064}
135065
135066/*
135067** Extract the next token from a tokenization cursor.  The cursor must
135068** have been opened by a prior call to simpleOpen().
135069*/
135070static int simpleNext(
135071  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
135072  const char **ppToken,               /* OUT: *ppToken is the token text */
135073  int *pnBytes,                       /* OUT: Number of bytes in token */
135074  int *piStartOffset,                 /* OUT: Starting offset of token */
135075  int *piEndOffset,                   /* OUT: Ending offset of token */
135076  int *piPosition                     /* OUT: Position integer of token */
135077){
135078  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
135079  simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
135080  unsigned char *p = (unsigned char *)c->pInput;
135081
135082  while( c->iOffset<c->nBytes ){
135083    int iStartOffset;
135084
135085    /* Scan past delimiter characters */
135086    while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
135087      c->iOffset++;
135088    }
135089
135090    /* Count non-delimiter characters. */
135091    iStartOffset = c->iOffset;
135092    while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
135093      c->iOffset++;
135094    }
135095
135096    if( c->iOffset>iStartOffset ){
135097      int i, n = c->iOffset-iStartOffset;
135098      if( n>c->nTokenAllocated ){
135099        char *pNew;
135100        c->nTokenAllocated = n+20;
135101        pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
135102        if( !pNew ) return SQLITE_NOMEM;
135103        c->pToken = pNew;
135104      }
135105      for(i=0; i<n; i++){
135106        /* TODO(shess) This needs expansion to handle UTF-8
135107        ** case-insensitivity.
135108        */
135109        unsigned char ch = p[iStartOffset+i];
135110        c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
135111      }
135112      *ppToken = c->pToken;
135113      *pnBytes = n;
135114      *piStartOffset = iStartOffset;
135115      *piEndOffset = c->iOffset;
135116      *piPosition = c->iToken++;
135117
135118      return SQLITE_OK;
135119    }
135120  }
135121  return SQLITE_DONE;
135122}
135123
135124/*
135125** The set of routines that implement the simple tokenizer
135126*/
135127static const sqlite3_tokenizer_module simpleTokenizerModule = {
135128  0,
135129  simpleCreate,
135130  simpleDestroy,
135131  simpleOpen,
135132  simpleClose,
135133  simpleNext,
135134  0,
135135};
135136
135137/*
135138** Allocate a new simple tokenizer.  Return a pointer to the new
135139** tokenizer in *ppModule
135140*/
135141SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
135142  sqlite3_tokenizer_module const**ppModule
135143){
135144  *ppModule = &simpleTokenizerModule;
135145}
135146
135147#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
135148
135149/************** End of fts3_tokenizer1.c *************************************/
135150/************** Begin file fts3_tokenize_vtab.c ******************************/
135151/*
135152** 2013 Apr 22
135153**
135154** The author disclaims copyright to this source code.  In place of
135155** a legal notice, here is a blessing:
135156**
135157**    May you do good and not evil.
135158**    May you find forgiveness for yourself and forgive others.
135159**    May you share freely, never taking more than you give.
135160**
135161******************************************************************************
135162**
135163** This file contains code for the "fts3tokenize" virtual table module.
135164** An fts3tokenize virtual table is created as follows:
135165**
135166**   CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
135167**       <tokenizer-name>, <arg-1>, ...
135168**   );
135169**
135170** The table created has the following schema:
135171**
135172**   CREATE TABLE <tbl>(input, token, start, end, position)
135173**
135174** When queried, the query must include a WHERE clause of type:
135175**
135176**   input = <string>
135177**
135178** The virtual table module tokenizes this <string>, using the FTS3
135179** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
135180** statement and returns one row for each token in the result. With
135181** fields set as follows:
135182**
135183**   input:   Always set to a copy of <string>
135184**   token:   A token from the input.
135185**   start:   Byte offset of the token within the input <string>.
135186**   end:     Byte offset of the byte immediately following the end of the
135187**            token within the input string.
135188**   pos:     Token offset of token within input.
135189**
135190*/
135191#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
135192
135193/* #include <string.h> */
135194/* #include <assert.h> */
135195
135196typedef struct Fts3tokTable Fts3tokTable;
135197typedef struct Fts3tokCursor Fts3tokCursor;
135198
135199/*
135200** Virtual table structure.
135201*/
135202struct Fts3tokTable {
135203  sqlite3_vtab base;              /* Base class used by SQLite core */
135204  const sqlite3_tokenizer_module *pMod;
135205  sqlite3_tokenizer *pTok;
135206};
135207
135208/*
135209** Virtual table cursor structure.
135210*/
135211struct Fts3tokCursor {
135212  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
135213  char *zInput;                   /* Input string */
135214  sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
135215  int iRowid;                     /* Current 'rowid' value */
135216  const char *zToken;             /* Current 'token' value */
135217  int nToken;                     /* Size of zToken in bytes */
135218  int iStart;                     /* Current 'start' value */
135219  int iEnd;                       /* Current 'end' value */
135220  int iPos;                       /* Current 'pos' value */
135221};
135222
135223/*
135224** Query FTS for the tokenizer implementation named zName.
135225*/
135226static int fts3tokQueryTokenizer(
135227  Fts3Hash *pHash,
135228  const char *zName,
135229  const sqlite3_tokenizer_module **pp,
135230  char **pzErr
135231){
135232  sqlite3_tokenizer_module *p;
135233  int nName = (int)strlen(zName);
135234
135235  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
135236  if( !p ){
135237    *pzErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
135238    return SQLITE_ERROR;
135239  }
135240
135241  *pp = p;
135242  return SQLITE_OK;
135243}
135244
135245/*
135246** The second argument, argv[], is an array of pointers to nul-terminated
135247** strings. This function makes a copy of the array and strings into a
135248** single block of memory. It then dequotes any of the strings that appear
135249** to be quoted.
135250**
135251** If successful, output parameter *pazDequote is set to point at the
135252** array of dequoted strings and SQLITE_OK is returned. The caller is
135253** responsible for eventually calling sqlite3_free() to free the array
135254** in this case. Or, if an error occurs, an SQLite error code is returned.
135255** The final value of *pazDequote is undefined in this case.
135256*/
135257static int fts3tokDequoteArray(
135258  int argc,                       /* Number of elements in argv[] */
135259  const char * const *argv,       /* Input array */
135260  char ***pazDequote              /* Output array */
135261){
135262  int rc = SQLITE_OK;             /* Return code */
135263  if( argc==0 ){
135264    *pazDequote = 0;
135265  }else{
135266    int i;
135267    int nByte = 0;
135268    char **azDequote;
135269
135270    for(i=0; i<argc; i++){
135271      nByte += (int)(strlen(argv[i]) + 1);
135272    }
135273
135274    *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
135275    if( azDequote==0 ){
135276      rc = SQLITE_NOMEM;
135277    }else{
135278      char *pSpace = (char *)&azDequote[argc];
135279      for(i=0; i<argc; i++){
135280        int n = (int)strlen(argv[i]);
135281        azDequote[i] = pSpace;
135282        memcpy(pSpace, argv[i], n+1);
135283        sqlite3Fts3Dequote(pSpace);
135284        pSpace += (n+1);
135285      }
135286    }
135287  }
135288
135289  return rc;
135290}
135291
135292/*
135293** Schema of the tokenizer table.
135294*/
135295#define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
135296
135297/*
135298** This function does all the work for both the xConnect and xCreate methods.
135299** These tables have no persistent representation of their own, so xConnect
135300** and xCreate are identical operations.
135301**
135302**   argv[0]: module name
135303**   argv[1]: database name
135304**   argv[2]: table name
135305**   argv[3]: first argument (tokenizer name)
135306*/
135307static int fts3tokConnectMethod(
135308  sqlite3 *db,                    /* Database connection */
135309  void *pHash,                    /* Hash table of tokenizers */
135310  int argc,                       /* Number of elements in argv array */
135311  const char * const *argv,       /* xCreate/xConnect argument array */
135312  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
135313  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
135314){
135315  Fts3tokTable *pTab;
135316  const sqlite3_tokenizer_module *pMod = 0;
135317  sqlite3_tokenizer *pTok = 0;
135318  int rc;
135319  char **azDequote = 0;
135320  int nDequote;
135321
135322  rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
135323  if( rc!=SQLITE_OK ) return rc;
135324
135325  nDequote = argc-3;
135326  rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
135327
135328  if( rc==SQLITE_OK ){
135329    const char *zModule;
135330    if( nDequote<1 ){
135331      zModule = "simple";
135332    }else{
135333      zModule = azDequote[0];
135334    }
135335    rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
135336  }
135337
135338  assert( (rc==SQLITE_OK)==(pMod!=0) );
135339  if( rc==SQLITE_OK ){
135340    const char * const *azArg = (const char * const *)&azDequote[1];
135341    rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
135342  }
135343
135344  if( rc==SQLITE_OK ){
135345    pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
135346    if( pTab==0 ){
135347      rc = SQLITE_NOMEM;
135348    }
135349  }
135350
135351  if( rc==SQLITE_OK ){
135352    memset(pTab, 0, sizeof(Fts3tokTable));
135353    pTab->pMod = pMod;
135354    pTab->pTok = pTok;
135355    *ppVtab = &pTab->base;
135356  }else{
135357    if( pTok ){
135358      pMod->xDestroy(pTok);
135359    }
135360  }
135361
135362  sqlite3_free(azDequote);
135363  return rc;
135364}
135365
135366/*
135367** This function does the work for both the xDisconnect and xDestroy methods.
135368** These tables have no persistent representation of their own, so xDisconnect
135369** and xDestroy are identical operations.
135370*/
135371static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
135372  Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
135373
135374  pTab->pMod->xDestroy(pTab->pTok);
135375  sqlite3_free(pTab);
135376  return SQLITE_OK;
135377}
135378
135379/*
135380** xBestIndex - Analyze a WHERE and ORDER BY clause.
135381*/
135382static int fts3tokBestIndexMethod(
135383  sqlite3_vtab *pVTab,
135384  sqlite3_index_info *pInfo
135385){
135386  int i;
135387  UNUSED_PARAMETER(pVTab);
135388
135389  for(i=0; i<pInfo->nConstraint; i++){
135390    if( pInfo->aConstraint[i].usable
135391     && pInfo->aConstraint[i].iColumn==0
135392     && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
135393    ){
135394      pInfo->idxNum = 1;
135395      pInfo->aConstraintUsage[i].argvIndex = 1;
135396      pInfo->aConstraintUsage[i].omit = 1;
135397      pInfo->estimatedCost = 1;
135398      return SQLITE_OK;
135399    }
135400  }
135401
135402  pInfo->idxNum = 0;
135403  assert( pInfo->estimatedCost>1000000.0 );
135404
135405  return SQLITE_OK;
135406}
135407
135408/*
135409** xOpen - Open a cursor.
135410*/
135411static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
135412  Fts3tokCursor *pCsr;
135413  UNUSED_PARAMETER(pVTab);
135414
135415  pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
135416  if( pCsr==0 ){
135417    return SQLITE_NOMEM;
135418  }
135419  memset(pCsr, 0, sizeof(Fts3tokCursor));
135420
135421  *ppCsr = (sqlite3_vtab_cursor *)pCsr;
135422  return SQLITE_OK;
135423}
135424
135425/*
135426** Reset the tokenizer cursor passed as the only argument. As if it had
135427** just been returned by fts3tokOpenMethod().
135428*/
135429static void fts3tokResetCursor(Fts3tokCursor *pCsr){
135430  if( pCsr->pCsr ){
135431    Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
135432    pTab->pMod->xClose(pCsr->pCsr);
135433    pCsr->pCsr = 0;
135434  }
135435  sqlite3_free(pCsr->zInput);
135436  pCsr->zInput = 0;
135437  pCsr->zToken = 0;
135438  pCsr->nToken = 0;
135439  pCsr->iStart = 0;
135440  pCsr->iEnd = 0;
135441  pCsr->iPos = 0;
135442  pCsr->iRowid = 0;
135443}
135444
135445/*
135446** xClose - Close a cursor.
135447*/
135448static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
135449  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
135450
135451  fts3tokResetCursor(pCsr);
135452  sqlite3_free(pCsr);
135453  return SQLITE_OK;
135454}
135455
135456/*
135457** xNext - Advance the cursor to the next row, if any.
135458*/
135459static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
135460  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
135461  Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
135462  int rc;                         /* Return code */
135463
135464  pCsr->iRowid++;
135465  rc = pTab->pMod->xNext(pCsr->pCsr,
135466      &pCsr->zToken, &pCsr->nToken,
135467      &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
135468  );
135469
135470  if( rc!=SQLITE_OK ){
135471    fts3tokResetCursor(pCsr);
135472    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
135473  }
135474
135475  return rc;
135476}
135477
135478/*
135479** xFilter - Initialize a cursor to point at the start of its data.
135480*/
135481static int fts3tokFilterMethod(
135482  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
135483  int idxNum,                     /* Strategy index */
135484  const char *idxStr,             /* Unused */
135485  int nVal,                       /* Number of elements in apVal */
135486  sqlite3_value **apVal           /* Arguments for the indexing scheme */
135487){
135488  int rc = SQLITE_ERROR;
135489  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
135490  Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
135491  UNUSED_PARAMETER(idxStr);
135492  UNUSED_PARAMETER(nVal);
135493
135494  fts3tokResetCursor(pCsr);
135495  if( idxNum==1 ){
135496    const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
135497    int nByte = sqlite3_value_bytes(apVal[0]);
135498    pCsr->zInput = sqlite3_malloc(nByte+1);
135499    if( pCsr->zInput==0 ){
135500      rc = SQLITE_NOMEM;
135501    }else{
135502      memcpy(pCsr->zInput, zByte, nByte);
135503      pCsr->zInput[nByte] = 0;
135504      rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
135505      if( rc==SQLITE_OK ){
135506        pCsr->pCsr->pTokenizer = pTab->pTok;
135507      }
135508    }
135509  }
135510
135511  if( rc!=SQLITE_OK ) return rc;
135512  return fts3tokNextMethod(pCursor);
135513}
135514
135515/*
135516** xEof - Return true if the cursor is at EOF, or false otherwise.
135517*/
135518static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
135519  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
135520  return (pCsr->zToken==0);
135521}
135522
135523/*
135524** xColumn - Return a column value.
135525*/
135526static int fts3tokColumnMethod(
135527  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
135528  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
135529  int iCol                        /* Index of column to read value from */
135530){
135531  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
135532
135533  /* CREATE TABLE x(input, token, start, end, position) */
135534  switch( iCol ){
135535    case 0:
135536      sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
135537      break;
135538    case 1:
135539      sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
135540      break;
135541    case 2:
135542      sqlite3_result_int(pCtx, pCsr->iStart);
135543      break;
135544    case 3:
135545      sqlite3_result_int(pCtx, pCsr->iEnd);
135546      break;
135547    default:
135548      assert( iCol==4 );
135549      sqlite3_result_int(pCtx, pCsr->iPos);
135550      break;
135551  }
135552  return SQLITE_OK;
135553}
135554
135555/*
135556** xRowid - Return the current rowid for the cursor.
135557*/
135558static int fts3tokRowidMethod(
135559  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
135560  sqlite_int64 *pRowid            /* OUT: Rowid value */
135561){
135562  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
135563  *pRowid = (sqlite3_int64)pCsr->iRowid;
135564  return SQLITE_OK;
135565}
135566
135567/*
135568** Register the fts3tok module with database connection db. Return SQLITE_OK
135569** if successful or an error code if sqlite3_create_module() fails.
135570*/
135571SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
135572  static const sqlite3_module fts3tok_module = {
135573     0,                           /* iVersion      */
135574     fts3tokConnectMethod,        /* xCreate       */
135575     fts3tokConnectMethod,        /* xConnect      */
135576     fts3tokBestIndexMethod,      /* xBestIndex    */
135577     fts3tokDisconnectMethod,     /* xDisconnect   */
135578     fts3tokDisconnectMethod,     /* xDestroy      */
135579     fts3tokOpenMethod,           /* xOpen         */
135580     fts3tokCloseMethod,          /* xClose        */
135581     fts3tokFilterMethod,         /* xFilter       */
135582     fts3tokNextMethod,           /* xNext         */
135583     fts3tokEofMethod,            /* xEof          */
135584     fts3tokColumnMethod,         /* xColumn       */
135585     fts3tokRowidMethod,          /* xRowid        */
135586     0,                           /* xUpdate       */
135587     0,                           /* xBegin        */
135588     0,                           /* xSync         */
135589     0,                           /* xCommit       */
135590     0,                           /* xRollback     */
135591     0,                           /* xFindFunction */
135592     0,                           /* xRename       */
135593     0,                           /* xSavepoint    */
135594     0,                           /* xRelease      */
135595     0                            /* xRollbackTo   */
135596  };
135597  int rc;                         /* Return code */
135598
135599  rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
135600  return rc;
135601}
135602
135603#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
135604
135605/************** End of fts3_tokenize_vtab.c **********************************/
135606/************** Begin file fts3_write.c **************************************/
135607/*
135608** 2009 Oct 23
135609**
135610** The author disclaims copyright to this source code.  In place of
135611** a legal notice, here is a blessing:
135612**
135613**    May you do good and not evil.
135614**    May you find forgiveness for yourself and forgive others.
135615**    May you share freely, never taking more than you give.
135616**
135617******************************************************************************
135618**
135619** This file is part of the SQLite FTS3 extension module. Specifically,
135620** this file contains code to insert, update and delete rows from FTS3
135621** tables. It also contains code to merge FTS3 b-tree segments. Some
135622** of the sub-routines used to merge segments are also used by the query
135623** code in fts3.c.
135624*/
135625
135626#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
135627
135628/* #include <string.h> */
135629/* #include <assert.h> */
135630/* #include <stdlib.h> */
135631
135632
135633#define FTS_MAX_APPENDABLE_HEIGHT 16
135634
135635/*
135636** When full-text index nodes are loaded from disk, the buffer that they
135637** are loaded into has the following number of bytes of padding at the end
135638** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
135639** of 920 bytes is allocated for it.
135640**
135641** This means that if we have a pointer into a buffer containing node data,
135642** it is always safe to read up to two varints from it without risking an
135643** overread, even if the node data is corrupted.
135644*/
135645#define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
135646
135647/*
135648** Under certain circumstances, b-tree nodes (doclists) can be loaded into
135649** memory incrementally instead of all at once. This can be a big performance
135650** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
135651** method before retrieving all query results (as may happen, for example,
135652** if a query has a LIMIT clause).
135653**
135654** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
135655** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
135656** The code is written so that the hard lower-limit for each of these values
135657** is 1. Clearly such small values would be inefficient, but can be useful
135658** for testing purposes.
135659**
135660** If this module is built with SQLITE_TEST defined, these constants may
135661** be overridden at runtime for testing purposes. File fts3_test.c contains
135662** a Tcl interface to read and write the values.
135663*/
135664#ifdef SQLITE_TEST
135665int test_fts3_node_chunksize = (4*1024);
135666int test_fts3_node_chunk_threshold = (4*1024)*4;
135667# define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
135668# define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
135669#else
135670# define FTS3_NODE_CHUNKSIZE (4*1024)
135671# define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
135672#endif
135673
135674/*
135675** The two values that may be meaningfully bound to the :1 parameter in
135676** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
135677*/
135678#define FTS_STAT_DOCTOTAL      0
135679#define FTS_STAT_INCRMERGEHINT 1
135680#define FTS_STAT_AUTOINCRMERGE 2
135681
135682/*
135683** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
135684** and incremental merge operation that takes place. This is used for
135685** debugging FTS only, it should not usually be turned on in production
135686** systems.
135687*/
135688#ifdef FTS3_LOG_MERGES
135689static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
135690  sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
135691}
135692#else
135693#define fts3LogMerge(x, y)
135694#endif
135695
135696
135697typedef struct PendingList PendingList;
135698typedef struct SegmentNode SegmentNode;
135699typedef struct SegmentWriter SegmentWriter;
135700
135701/*
135702** An instance of the following data structure is used to build doclists
135703** incrementally. See function fts3PendingListAppend() for details.
135704*/
135705struct PendingList {
135706  int nData;
135707  char *aData;
135708  int nSpace;
135709  sqlite3_int64 iLastDocid;
135710  sqlite3_int64 iLastCol;
135711  sqlite3_int64 iLastPos;
135712};
135713
135714
135715/*
135716** Each cursor has a (possibly empty) linked list of the following objects.
135717*/
135718struct Fts3DeferredToken {
135719  Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
135720  int iCol;                       /* Column token must occur in */
135721  Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
135722  PendingList *pList;             /* Doclist is assembled here */
135723};
135724
135725/*
135726** An instance of this structure is used to iterate through the terms on
135727** a contiguous set of segment b-tree leaf nodes. Although the details of
135728** this structure are only manipulated by code in this file, opaque handles
135729** of type Fts3SegReader* are also used by code in fts3.c to iterate through
135730** terms when querying the full-text index. See functions:
135731**
135732**   sqlite3Fts3SegReaderNew()
135733**   sqlite3Fts3SegReaderFree()
135734**   sqlite3Fts3SegReaderIterate()
135735**
135736** Methods used to manipulate Fts3SegReader structures:
135737**
135738**   fts3SegReaderNext()
135739**   fts3SegReaderFirstDocid()
135740**   fts3SegReaderNextDocid()
135741*/
135742struct Fts3SegReader {
135743  int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
135744  u8 bLookup;                     /* True for a lookup only */
135745  u8 rootOnly;                    /* True for a root-only reader */
135746
135747  sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
135748  sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
135749  sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
135750  sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
135751
135752  char *aNode;                    /* Pointer to node data (or NULL) */
135753  int nNode;                      /* Size of buffer at aNode (or 0) */
135754  int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
135755  sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
135756
135757  Fts3HashElem **ppNextElem;
135758
135759  /* Variables set by fts3SegReaderNext(). These may be read directly
135760  ** by the caller. They are valid from the time SegmentReaderNew() returns
135761  ** until SegmentReaderNext() returns something other than SQLITE_OK
135762  ** (i.e. SQLITE_DONE).
135763  */
135764  int nTerm;                      /* Number of bytes in current term */
135765  char *zTerm;                    /* Pointer to current term */
135766  int nTermAlloc;                 /* Allocated size of zTerm buffer */
135767  char *aDoclist;                 /* Pointer to doclist of current entry */
135768  int nDoclist;                   /* Size of doclist in current entry */
135769
135770  /* The following variables are used by fts3SegReaderNextDocid() to iterate
135771  ** through the current doclist (aDoclist/nDoclist).
135772  */
135773  char *pOffsetList;
135774  int nOffsetList;                /* For descending pending seg-readers only */
135775  sqlite3_int64 iDocid;
135776};
135777
135778#define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
135779#define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
135780
135781/*
135782** An instance of this structure is used to create a segment b-tree in the
135783** database. The internal details of this type are only accessed by the
135784** following functions:
135785**
135786**   fts3SegWriterAdd()
135787**   fts3SegWriterFlush()
135788**   fts3SegWriterFree()
135789*/
135790struct SegmentWriter {
135791  SegmentNode *pTree;             /* Pointer to interior tree structure */
135792  sqlite3_int64 iFirst;           /* First slot in %_segments written */
135793  sqlite3_int64 iFree;            /* Next free slot in %_segments */
135794  char *zTerm;                    /* Pointer to previous term buffer */
135795  int nTerm;                      /* Number of bytes in zTerm */
135796  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
135797  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
135798  int nSize;                      /* Size of allocation at aData */
135799  int nData;                      /* Bytes of data in aData */
135800  char *aData;                    /* Pointer to block from malloc() */
135801  i64 nLeafData;                  /* Number of bytes of leaf data written */
135802};
135803
135804/*
135805** Type SegmentNode is used by the following three functions to create
135806** the interior part of the segment b+-tree structures (everything except
135807** the leaf nodes). These functions and type are only ever used by code
135808** within the fts3SegWriterXXX() family of functions described above.
135809**
135810**   fts3NodeAddTerm()
135811**   fts3NodeWrite()
135812**   fts3NodeFree()
135813**
135814** When a b+tree is written to the database (either as a result of a merge
135815** or the pending-terms table being flushed), leaves are written into the
135816** database file as soon as they are completely populated. The interior of
135817** the tree is assembled in memory and written out only once all leaves have
135818** been populated and stored. This is Ok, as the b+-tree fanout is usually
135819** very large, meaning that the interior of the tree consumes relatively
135820** little memory.
135821*/
135822struct SegmentNode {
135823  SegmentNode *pParent;           /* Parent node (or NULL for root node) */
135824  SegmentNode *pRight;            /* Pointer to right-sibling */
135825  SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
135826  int nEntry;                     /* Number of terms written to node so far */
135827  char *zTerm;                    /* Pointer to previous term buffer */
135828  int nTerm;                      /* Number of bytes in zTerm */
135829  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
135830  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
135831  int nData;                      /* Bytes of valid data so far */
135832  char *aData;                    /* Node data */
135833};
135834
135835/*
135836** Valid values for the second argument to fts3SqlStmt().
135837*/
135838#define SQL_DELETE_CONTENT             0
135839#define SQL_IS_EMPTY                   1
135840#define SQL_DELETE_ALL_CONTENT         2
135841#define SQL_DELETE_ALL_SEGMENTS        3
135842#define SQL_DELETE_ALL_SEGDIR          4
135843#define SQL_DELETE_ALL_DOCSIZE         5
135844#define SQL_DELETE_ALL_STAT            6
135845#define SQL_SELECT_CONTENT_BY_ROWID    7
135846#define SQL_NEXT_SEGMENT_INDEX         8
135847#define SQL_INSERT_SEGMENTS            9
135848#define SQL_NEXT_SEGMENTS_ID          10
135849#define SQL_INSERT_SEGDIR             11
135850#define SQL_SELECT_LEVEL              12
135851#define SQL_SELECT_LEVEL_RANGE        13
135852#define SQL_SELECT_LEVEL_COUNT        14
135853#define SQL_SELECT_SEGDIR_MAX_LEVEL   15
135854#define SQL_DELETE_SEGDIR_LEVEL       16
135855#define SQL_DELETE_SEGMENTS_RANGE     17
135856#define SQL_CONTENT_INSERT            18
135857#define SQL_DELETE_DOCSIZE            19
135858#define SQL_REPLACE_DOCSIZE           20
135859#define SQL_SELECT_DOCSIZE            21
135860#define SQL_SELECT_STAT               22
135861#define SQL_REPLACE_STAT              23
135862
135863#define SQL_SELECT_ALL_PREFIX_LEVEL   24
135864#define SQL_DELETE_ALL_TERMS_SEGDIR   25
135865#define SQL_DELETE_SEGDIR_RANGE       26
135866#define SQL_SELECT_ALL_LANGID         27
135867#define SQL_FIND_MERGE_LEVEL          28
135868#define SQL_MAX_LEAF_NODE_ESTIMATE    29
135869#define SQL_DELETE_SEGDIR_ENTRY       30
135870#define SQL_SHIFT_SEGDIR_ENTRY        31
135871#define SQL_SELECT_SEGDIR             32
135872#define SQL_CHOMP_SEGDIR              33
135873#define SQL_SEGMENT_IS_APPENDABLE     34
135874#define SQL_SELECT_INDEXES            35
135875#define SQL_SELECT_MXLEVEL            36
135876
135877#define SQL_SELECT_LEVEL_RANGE2       37
135878#define SQL_UPDATE_LEVEL_IDX          38
135879#define SQL_UPDATE_LEVEL              39
135880
135881/*
135882** This function is used to obtain an SQLite prepared statement handle
135883** for the statement identified by the second argument. If successful,
135884** *pp is set to the requested statement handle and SQLITE_OK returned.
135885** Otherwise, an SQLite error code is returned and *pp is set to 0.
135886**
135887** If argument apVal is not NULL, then it must point to an array with
135888** at least as many entries as the requested statement has bound
135889** parameters. The values are bound to the statements parameters before
135890** returning.
135891*/
135892static int fts3SqlStmt(
135893  Fts3Table *p,                   /* Virtual table handle */
135894  int eStmt,                      /* One of the SQL_XXX constants above */
135895  sqlite3_stmt **pp,              /* OUT: Statement handle */
135896  sqlite3_value **apVal           /* Values to bind to statement */
135897){
135898  const char *azSql[] = {
135899/* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
135900/* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
135901/* 2  */  "DELETE FROM %Q.'%q_content'",
135902/* 3  */  "DELETE FROM %Q.'%q_segments'",
135903/* 4  */  "DELETE FROM %Q.'%q_segdir'",
135904/* 5  */  "DELETE FROM %Q.'%q_docsize'",
135905/* 6  */  "DELETE FROM %Q.'%q_stat'",
135906/* 7  */  "SELECT %s WHERE rowid=?",
135907/* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
135908/* 9  */  "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
135909/* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
135910/* 11 */  "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
135911
135912          /* Return segments in order from oldest to newest.*/
135913/* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
135914            "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
135915/* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
135916            "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
135917            "ORDER BY level DESC, idx ASC",
135918
135919/* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
135920/* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
135921
135922/* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
135923/* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
135924/* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
135925/* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
135926/* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
135927/* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
135928/* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=?",
135929/* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
135930/* 24 */  "",
135931/* 25 */  "",
135932
135933/* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
135934/* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
135935
135936/* This statement is used to determine which level to read the input from
135937** when performing an incremental merge. It returns the absolute level number
135938** of the oldest level in the db that contains at least ? segments. Or,
135939** if no level in the FTS index contains more than ? segments, the statement
135940** returns zero rows.  */
135941/* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
135942         "  ORDER BY (level %% 1024) ASC LIMIT 1",
135943
135944/* Estimate the upper limit on the number of leaf nodes in a new segment
135945** created by merging the oldest :2 segments from absolute level :1. See
135946** function sqlite3Fts3Incrmerge() for details.  */
135947/* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
135948         "  FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
135949
135950/* SQL_DELETE_SEGDIR_ENTRY
135951**   Delete the %_segdir entry on absolute level :1 with index :2.  */
135952/* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
135953
135954/* SQL_SHIFT_SEGDIR_ENTRY
135955**   Modify the idx value for the segment with idx=:3 on absolute level :2
135956**   to :1.  */
135957/* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
135958
135959/* SQL_SELECT_SEGDIR
135960**   Read a single entry from the %_segdir table. The entry from absolute
135961**   level :1 with index value :2.  */
135962/* 32 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
135963            "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
135964
135965/* SQL_CHOMP_SEGDIR
135966**   Update the start_block (:1) and root (:2) fields of the %_segdir
135967**   entry located on absolute level :3 with index :4.  */
135968/* 33 */  "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
135969            "WHERE level = ? AND idx = ?",
135970
135971/* SQL_SEGMENT_IS_APPENDABLE
135972**   Return a single row if the segment with end_block=? is appendable. Or
135973**   no rows otherwise.  */
135974/* 34 */  "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
135975
135976/* SQL_SELECT_INDEXES
135977**   Return the list of valid segment indexes for absolute level ?  */
135978/* 35 */  "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
135979
135980/* SQL_SELECT_MXLEVEL
135981**   Return the largest relative level in the FTS index or indexes.  */
135982/* 36 */  "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
135983
135984          /* Return segments in order from oldest to newest.*/
135985/* 37 */  "SELECT level, idx, end_block "
135986            "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
135987            "ORDER BY level DESC, idx ASC",
135988
135989          /* Update statements used while promoting segments */
135990/* 38 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
135991            "WHERE level=? AND idx=?",
135992/* 39 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
135993
135994  };
135995  int rc = SQLITE_OK;
135996  sqlite3_stmt *pStmt;
135997
135998  assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
135999  assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
136000
136001  pStmt = p->aStmt[eStmt];
136002  if( !pStmt ){
136003    char *zSql;
136004    if( eStmt==SQL_CONTENT_INSERT ){
136005      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
136006    }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
136007      zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
136008    }else{
136009      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
136010    }
136011    if( !zSql ){
136012      rc = SQLITE_NOMEM;
136013    }else{
136014      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
136015      sqlite3_free(zSql);
136016      assert( rc==SQLITE_OK || pStmt==0 );
136017      p->aStmt[eStmt] = pStmt;
136018    }
136019  }
136020  if( apVal ){
136021    int i;
136022    int nParam = sqlite3_bind_parameter_count(pStmt);
136023    for(i=0; rc==SQLITE_OK && i<nParam; i++){
136024      rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
136025    }
136026  }
136027  *pp = pStmt;
136028  return rc;
136029}
136030
136031
136032static int fts3SelectDocsize(
136033  Fts3Table *pTab,                /* FTS3 table handle */
136034  sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
136035  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
136036){
136037  sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
136038  int rc;                         /* Return code */
136039
136040  rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
136041  if( rc==SQLITE_OK ){
136042    sqlite3_bind_int64(pStmt, 1, iDocid);
136043    rc = sqlite3_step(pStmt);
136044    if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
136045      rc = sqlite3_reset(pStmt);
136046      if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
136047      pStmt = 0;
136048    }else{
136049      rc = SQLITE_OK;
136050    }
136051  }
136052
136053  *ppStmt = pStmt;
136054  return rc;
136055}
136056
136057SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
136058  Fts3Table *pTab,                /* Fts3 table handle */
136059  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
136060){
136061  sqlite3_stmt *pStmt = 0;
136062  int rc;
136063  rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
136064  if( rc==SQLITE_OK ){
136065    sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
136066    if( sqlite3_step(pStmt)!=SQLITE_ROW
136067     || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
136068    ){
136069      rc = sqlite3_reset(pStmt);
136070      if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
136071      pStmt = 0;
136072    }
136073  }
136074  *ppStmt = pStmt;
136075  return rc;
136076}
136077
136078SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
136079  Fts3Table *pTab,                /* Fts3 table handle */
136080  sqlite3_int64 iDocid,           /* Docid to read size data for */
136081  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
136082){
136083  return fts3SelectDocsize(pTab, iDocid, ppStmt);
136084}
136085
136086/*
136087** Similar to fts3SqlStmt(). Except, after binding the parameters in
136088** array apVal[] to the SQL statement identified by eStmt, the statement
136089** is executed.
136090**
136091** Returns SQLITE_OK if the statement is successfully executed, or an
136092** SQLite error code otherwise.
136093*/
136094static void fts3SqlExec(
136095  int *pRC,                /* Result code */
136096  Fts3Table *p,            /* The FTS3 table */
136097  int eStmt,               /* Index of statement to evaluate */
136098  sqlite3_value **apVal    /* Parameters to bind */
136099){
136100  sqlite3_stmt *pStmt;
136101  int rc;
136102  if( *pRC ) return;
136103  rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
136104  if( rc==SQLITE_OK ){
136105    sqlite3_step(pStmt);
136106    rc = sqlite3_reset(pStmt);
136107  }
136108  *pRC = rc;
136109}
136110
136111
136112/*
136113** This function ensures that the caller has obtained an exclusive
136114** shared-cache table-lock on the %_segdir table. This is required before
136115** writing data to the fts3 table. If this lock is not acquired first, then
136116** the caller may end up attempting to take this lock as part of committing
136117** a transaction, causing SQLite to return SQLITE_LOCKED or
136118** LOCKED_SHAREDCACHEto a COMMIT command.
136119**
136120** It is best to avoid this because if FTS3 returns any error when
136121** committing a transaction, the whole transaction will be rolled back.
136122** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
136123** It can still happen if the user locks the underlying tables directly
136124** instead of accessing them via FTS.
136125*/
136126static int fts3Writelock(Fts3Table *p){
136127  int rc = SQLITE_OK;
136128
136129  if( p->nPendingData==0 ){
136130    sqlite3_stmt *pStmt;
136131    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
136132    if( rc==SQLITE_OK ){
136133      sqlite3_bind_null(pStmt, 1);
136134      sqlite3_step(pStmt);
136135      rc = sqlite3_reset(pStmt);
136136    }
136137  }
136138
136139  return rc;
136140}
136141
136142/*
136143** FTS maintains a separate indexes for each language-id (a 32-bit integer).
136144** Within each language id, a separate index is maintained to store the
136145** document terms, and each configured prefix size (configured the FTS
136146** "prefix=" option). And each index consists of multiple levels ("relative
136147** levels").
136148**
136149** All three of these values (the language id, the specific index and the
136150** level within the index) are encoded in 64-bit integer values stored
136151** in the %_segdir table on disk. This function is used to convert three
136152** separate component values into the single 64-bit integer value that
136153** can be used to query the %_segdir table.
136154**
136155** Specifically, each language-id/index combination is allocated 1024
136156** 64-bit integer level values ("absolute levels"). The main terms index
136157** for language-id 0 is allocate values 0-1023. The first prefix index
136158** (if any) for language-id 0 is allocated values 1024-2047. And so on.
136159** Language 1 indexes are allocated immediately following language 0.
136160**
136161** So, for a system with nPrefix prefix indexes configured, the block of
136162** absolute levels that corresponds to language-id iLangid and index
136163** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
136164*/
136165static sqlite3_int64 getAbsoluteLevel(
136166  Fts3Table *p,                   /* FTS3 table handle */
136167  int iLangid,                    /* Language id */
136168  int iIndex,                     /* Index in p->aIndex[] */
136169  int iLevel                      /* Level of segments */
136170){
136171  sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */
136172  assert( iLangid>=0 );
136173  assert( p->nIndex>0 );
136174  assert( iIndex>=0 && iIndex<p->nIndex );
136175
136176  iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
136177  return iBase + iLevel;
136178}
136179
136180/*
136181** Set *ppStmt to a statement handle that may be used to iterate through
136182** all rows in the %_segdir table, from oldest to newest. If successful,
136183** return SQLITE_OK. If an error occurs while preparing the statement,
136184** return an SQLite error code.
136185**
136186** There is only ever one instance of this SQL statement compiled for
136187** each FTS3 table.
136188**
136189** The statement returns the following columns from the %_segdir table:
136190**
136191**   0: idx
136192**   1: start_block
136193**   2: leaves_end_block
136194**   3: end_block
136195**   4: root
136196*/
136197SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
136198  Fts3Table *p,                   /* FTS3 table */
136199  int iLangid,                    /* Language being queried */
136200  int iIndex,                     /* Index for p->aIndex[] */
136201  int iLevel,                     /* Level to select (relative level) */
136202  sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
136203){
136204  int rc;
136205  sqlite3_stmt *pStmt = 0;
136206
136207  assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
136208  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
136209  assert( iIndex>=0 && iIndex<p->nIndex );
136210
136211  if( iLevel<0 ){
136212    /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
136213    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
136214    if( rc==SQLITE_OK ){
136215      sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
136216      sqlite3_bind_int64(pStmt, 2,
136217          getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
136218      );
136219    }
136220  }else{
136221    /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
136222    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
136223    if( rc==SQLITE_OK ){
136224      sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
136225    }
136226  }
136227  *ppStmt = pStmt;
136228  return rc;
136229}
136230
136231
136232/*
136233** Append a single varint to a PendingList buffer. SQLITE_OK is returned
136234** if successful, or an SQLite error code otherwise.
136235**
136236** This function also serves to allocate the PendingList structure itself.
136237** For example, to create a new PendingList structure containing two
136238** varints:
136239**
136240**   PendingList *p = 0;
136241**   fts3PendingListAppendVarint(&p, 1);
136242**   fts3PendingListAppendVarint(&p, 2);
136243*/
136244static int fts3PendingListAppendVarint(
136245  PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
136246  sqlite3_int64 i                 /* Value to append to data */
136247){
136248  PendingList *p = *pp;
136249
136250  /* Allocate or grow the PendingList as required. */
136251  if( !p ){
136252    p = sqlite3_malloc(sizeof(*p) + 100);
136253    if( !p ){
136254      return SQLITE_NOMEM;
136255    }
136256    p->nSpace = 100;
136257    p->aData = (char *)&p[1];
136258    p->nData = 0;
136259  }
136260  else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
136261    int nNew = p->nSpace * 2;
136262    p = sqlite3_realloc(p, sizeof(*p) + nNew);
136263    if( !p ){
136264      sqlite3_free(*pp);
136265      *pp = 0;
136266      return SQLITE_NOMEM;
136267    }
136268    p->nSpace = nNew;
136269    p->aData = (char *)&p[1];
136270  }
136271
136272  /* Append the new serialized varint to the end of the list. */
136273  p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
136274  p->aData[p->nData] = '\0';
136275  *pp = p;
136276  return SQLITE_OK;
136277}
136278
136279/*
136280** Add a docid/column/position entry to a PendingList structure. Non-zero
136281** is returned if the structure is sqlite3_realloced as part of adding
136282** the entry. Otherwise, zero.
136283**
136284** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
136285** Zero is always returned in this case. Otherwise, if no OOM error occurs,
136286** it is set to SQLITE_OK.
136287*/
136288static int fts3PendingListAppend(
136289  PendingList **pp,               /* IN/OUT: PendingList structure */
136290  sqlite3_int64 iDocid,           /* Docid for entry to add */
136291  sqlite3_int64 iCol,             /* Column for entry to add */
136292  sqlite3_int64 iPos,             /* Position of term for entry to add */
136293  int *pRc                        /* OUT: Return code */
136294){
136295  PendingList *p = *pp;
136296  int rc = SQLITE_OK;
136297
136298  assert( !p || p->iLastDocid<=iDocid );
136299
136300  if( !p || p->iLastDocid!=iDocid ){
136301    sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
136302    if( p ){
136303      assert( p->nData<p->nSpace );
136304      assert( p->aData[p->nData]==0 );
136305      p->nData++;
136306    }
136307    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
136308      goto pendinglistappend_out;
136309    }
136310    p->iLastCol = -1;
136311    p->iLastPos = 0;
136312    p->iLastDocid = iDocid;
136313  }
136314  if( iCol>0 && p->iLastCol!=iCol ){
136315    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
136316     || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
136317    ){
136318      goto pendinglistappend_out;
136319    }
136320    p->iLastCol = iCol;
136321    p->iLastPos = 0;
136322  }
136323  if( iCol>=0 ){
136324    assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
136325    rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
136326    if( rc==SQLITE_OK ){
136327      p->iLastPos = iPos;
136328    }
136329  }
136330
136331 pendinglistappend_out:
136332  *pRc = rc;
136333  if( p!=*pp ){
136334    *pp = p;
136335    return 1;
136336  }
136337  return 0;
136338}
136339
136340/*
136341** Free a PendingList object allocated by fts3PendingListAppend().
136342*/
136343static void fts3PendingListDelete(PendingList *pList){
136344  sqlite3_free(pList);
136345}
136346
136347/*
136348** Add an entry to one of the pending-terms hash tables.
136349*/
136350static int fts3PendingTermsAddOne(
136351  Fts3Table *p,
136352  int iCol,
136353  int iPos,
136354  Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
136355  const char *zToken,
136356  int nToken
136357){
136358  PendingList *pList;
136359  int rc = SQLITE_OK;
136360
136361  pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
136362  if( pList ){
136363    p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
136364  }
136365  if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
136366    if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
136367      /* Malloc failed while inserting the new entry. This can only
136368      ** happen if there was no previous entry for this token.
136369      */
136370      assert( 0==fts3HashFind(pHash, zToken, nToken) );
136371      sqlite3_free(pList);
136372      rc = SQLITE_NOMEM;
136373    }
136374  }
136375  if( rc==SQLITE_OK ){
136376    p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
136377  }
136378  return rc;
136379}
136380
136381/*
136382** Tokenize the nul-terminated string zText and add all tokens to the
136383** pending-terms hash-table. The docid used is that currently stored in
136384** p->iPrevDocid, and the column is specified by argument iCol.
136385**
136386** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
136387*/
136388static int fts3PendingTermsAdd(
136389  Fts3Table *p,                   /* Table into which text will be inserted */
136390  int iLangid,                    /* Language id to use */
136391  const char *zText,              /* Text of document to be inserted */
136392  int iCol,                       /* Column into which text is being inserted */
136393  u32 *pnWord                     /* IN/OUT: Incr. by number tokens inserted */
136394){
136395  int rc;
136396  int iStart = 0;
136397  int iEnd = 0;
136398  int iPos = 0;
136399  int nWord = 0;
136400
136401  char const *zToken;
136402  int nToken = 0;
136403
136404  sqlite3_tokenizer *pTokenizer = p->pTokenizer;
136405  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
136406  sqlite3_tokenizer_cursor *pCsr;
136407  int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
136408      const char**,int*,int*,int*,int*);
136409
136410  assert( pTokenizer && pModule );
136411
136412  /* If the user has inserted a NULL value, this function may be called with
136413  ** zText==0. In this case, add zero token entries to the hash table and
136414  ** return early. */
136415  if( zText==0 ){
136416    *pnWord = 0;
136417    return SQLITE_OK;
136418  }
136419
136420  rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
136421  if( rc!=SQLITE_OK ){
136422    return rc;
136423  }
136424
136425  xNext = pModule->xNext;
136426  while( SQLITE_OK==rc
136427      && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
136428  ){
136429    int i;
136430    if( iPos>=nWord ) nWord = iPos+1;
136431
136432    /* Positions cannot be negative; we use -1 as a terminator internally.
136433    ** Tokens must have a non-zero length.
136434    */
136435    if( iPos<0 || !zToken || nToken<=0 ){
136436      rc = SQLITE_ERROR;
136437      break;
136438    }
136439
136440    /* Add the term to the terms index */
136441    rc = fts3PendingTermsAddOne(
136442        p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
136443    );
136444
136445    /* Add the term to each of the prefix indexes that it is not too
136446    ** short for. */
136447    for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
136448      struct Fts3Index *pIndex = &p->aIndex[i];
136449      if( nToken<pIndex->nPrefix ) continue;
136450      rc = fts3PendingTermsAddOne(
136451          p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
136452      );
136453    }
136454  }
136455
136456  pModule->xClose(pCsr);
136457  *pnWord += nWord;
136458  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
136459}
136460
136461/*
136462** Calling this function indicates that subsequent calls to
136463** fts3PendingTermsAdd() are to add term/position-list pairs for the
136464** contents of the document with docid iDocid.
136465*/
136466static int fts3PendingTermsDocid(
136467  Fts3Table *p,                   /* Full-text table handle */
136468  int iLangid,                    /* Language id of row being written */
136469  sqlite_int64 iDocid             /* Docid of row being written */
136470){
136471  assert( iLangid>=0 );
136472
136473  /* TODO(shess) Explore whether partially flushing the buffer on
136474  ** forced-flush would provide better performance.  I suspect that if
136475  ** we ordered the doclists by size and flushed the largest until the
136476  ** buffer was half empty, that would let the less frequent terms
136477  ** generate longer doclists.
136478  */
136479  if( iDocid<=p->iPrevDocid
136480   || p->iPrevLangid!=iLangid
136481   || p->nPendingData>p->nMaxPendingData
136482  ){
136483    int rc = sqlite3Fts3PendingTermsFlush(p);
136484    if( rc!=SQLITE_OK ) return rc;
136485  }
136486  p->iPrevDocid = iDocid;
136487  p->iPrevLangid = iLangid;
136488  return SQLITE_OK;
136489}
136490
136491/*
136492** Discard the contents of the pending-terms hash tables.
136493*/
136494SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
136495  int i;
136496  for(i=0; i<p->nIndex; i++){
136497    Fts3HashElem *pElem;
136498    Fts3Hash *pHash = &p->aIndex[i].hPending;
136499    for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
136500      PendingList *pList = (PendingList *)fts3HashData(pElem);
136501      fts3PendingListDelete(pList);
136502    }
136503    fts3HashClear(pHash);
136504  }
136505  p->nPendingData = 0;
136506}
136507
136508/*
136509** This function is called by the xUpdate() method as part of an INSERT
136510** operation. It adds entries for each term in the new record to the
136511** pendingTerms hash table.
136512**
136513** Argument apVal is the same as the similarly named argument passed to
136514** fts3InsertData(). Parameter iDocid is the docid of the new row.
136515*/
136516static int fts3InsertTerms(
136517  Fts3Table *p,
136518  int iLangid,
136519  sqlite3_value **apVal,
136520  u32 *aSz
136521){
136522  int i;                          /* Iterator variable */
136523  for(i=2; i<p->nColumn+2; i++){
136524    int iCol = i-2;
136525    if( p->abNotindexed[iCol]==0 ){
136526      const char *zText = (const char *)sqlite3_value_text(apVal[i]);
136527      int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
136528      if( rc!=SQLITE_OK ){
136529        return rc;
136530      }
136531      aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
136532    }
136533  }
136534  return SQLITE_OK;
136535}
136536
136537/*
136538** This function is called by the xUpdate() method for an INSERT operation.
136539** The apVal parameter is passed a copy of the apVal argument passed by
136540** SQLite to the xUpdate() method. i.e:
136541**
136542**   apVal[0]                Not used for INSERT.
136543**   apVal[1]                rowid
136544**   apVal[2]                Left-most user-defined column
136545**   ...
136546**   apVal[p->nColumn+1]     Right-most user-defined column
136547**   apVal[p->nColumn+2]     Hidden column with same name as table
136548**   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
136549**   apVal[p->nColumn+4]     Hidden languageid column
136550*/
136551static int fts3InsertData(
136552  Fts3Table *p,                   /* Full-text table */
136553  sqlite3_value **apVal,          /* Array of values to insert */
136554  sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
136555){
136556  int rc;                         /* Return code */
136557  sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
136558
136559  if( p->zContentTbl ){
136560    sqlite3_value *pRowid = apVal[p->nColumn+3];
136561    if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
136562      pRowid = apVal[1];
136563    }
136564    if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
136565      return SQLITE_CONSTRAINT;
136566    }
136567    *piDocid = sqlite3_value_int64(pRowid);
136568    return SQLITE_OK;
136569  }
136570
136571  /* Locate the statement handle used to insert data into the %_content
136572  ** table. The SQL for this statement is:
136573  **
136574  **   INSERT INTO %_content VALUES(?, ?, ?, ...)
136575  **
136576  ** The statement features N '?' variables, where N is the number of user
136577  ** defined columns in the FTS3 table, plus one for the docid field.
136578  */
136579  rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
136580  if( rc==SQLITE_OK && p->zLanguageid ){
136581    rc = sqlite3_bind_int(
136582        pContentInsert, p->nColumn+2,
136583        sqlite3_value_int(apVal[p->nColumn+4])
136584    );
136585  }
136586  if( rc!=SQLITE_OK ) return rc;
136587
136588  /* There is a quirk here. The users INSERT statement may have specified
136589  ** a value for the "rowid" field, for the "docid" field, or for both.
136590  ** Which is a problem, since "rowid" and "docid" are aliases for the
136591  ** same value. For example:
136592  **
136593  **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
136594  **
136595  ** In FTS3, this is an error. It is an error to specify non-NULL values
136596  ** for both docid and some other rowid alias.
136597  */
136598  if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
136599    if( SQLITE_NULL==sqlite3_value_type(apVal[0])
136600     && SQLITE_NULL!=sqlite3_value_type(apVal[1])
136601    ){
136602      /* A rowid/docid conflict. */
136603      return SQLITE_ERROR;
136604    }
136605    rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
136606    if( rc!=SQLITE_OK ) return rc;
136607  }
136608
136609  /* Execute the statement to insert the record. Set *piDocid to the
136610  ** new docid value.
136611  */
136612  sqlite3_step(pContentInsert);
136613  rc = sqlite3_reset(pContentInsert);
136614
136615  *piDocid = sqlite3_last_insert_rowid(p->db);
136616  return rc;
136617}
136618
136619
136620
136621/*
136622** Remove all data from the FTS3 table. Clear the hash table containing
136623** pending terms.
136624*/
136625static int fts3DeleteAll(Fts3Table *p, int bContent){
136626  int rc = SQLITE_OK;             /* Return code */
136627
136628  /* Discard the contents of the pending-terms hash table. */
136629  sqlite3Fts3PendingTermsClear(p);
136630
136631  /* Delete everything from the shadow tables. Except, leave %_content as
136632  ** is if bContent is false.  */
136633  assert( p->zContentTbl==0 || bContent==0 );
136634  if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
136635  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
136636  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
136637  if( p->bHasDocsize ){
136638    fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
136639  }
136640  if( p->bHasStat ){
136641    fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
136642  }
136643  return rc;
136644}
136645
136646/*
136647**
136648*/
136649static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
136650  int iLangid = 0;
136651  if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
136652  return iLangid;
136653}
136654
136655/*
136656** The first element in the apVal[] array is assumed to contain the docid
136657** (an integer) of a row about to be deleted. Remove all terms from the
136658** full-text index.
136659*/
136660static void fts3DeleteTerms(
136661  int *pRC,               /* Result code */
136662  Fts3Table *p,           /* The FTS table to delete from */
136663  sqlite3_value *pRowid,  /* The docid to be deleted */
136664  u32 *aSz,               /* Sizes of deleted document written here */
136665  int *pbFound            /* OUT: Set to true if row really does exist */
136666){
136667  int rc;
136668  sqlite3_stmt *pSelect;
136669
136670  assert( *pbFound==0 );
136671  if( *pRC ) return;
136672  rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
136673  if( rc==SQLITE_OK ){
136674    if( SQLITE_ROW==sqlite3_step(pSelect) ){
136675      int i;
136676      int iLangid = langidFromSelect(p, pSelect);
136677      rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
136678      for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
136679        int iCol = i-1;
136680        if( p->abNotindexed[iCol]==0 ){
136681          const char *zText = (const char *)sqlite3_column_text(pSelect, i);
136682          rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
136683          aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
136684        }
136685      }
136686      if( rc!=SQLITE_OK ){
136687        sqlite3_reset(pSelect);
136688        *pRC = rc;
136689        return;
136690      }
136691      *pbFound = 1;
136692    }
136693    rc = sqlite3_reset(pSelect);
136694  }else{
136695    sqlite3_reset(pSelect);
136696  }
136697  *pRC = rc;
136698}
136699
136700/*
136701** Forward declaration to account for the circular dependency between
136702** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
136703*/
136704static int fts3SegmentMerge(Fts3Table *, int, int, int);
136705
136706/*
136707** This function allocates a new level iLevel index in the segdir table.
136708** Usually, indexes are allocated within a level sequentially starting
136709** with 0, so the allocated index is one greater than the value returned
136710** by:
136711**
136712**   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
136713**
136714** However, if there are already FTS3_MERGE_COUNT indexes at the requested
136715** level, they are merged into a single level (iLevel+1) segment and the
136716** allocated index is 0.
136717**
136718** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
136719** returned. Otherwise, an SQLite error code is returned.
136720*/
136721static int fts3AllocateSegdirIdx(
136722  Fts3Table *p,
136723  int iLangid,                    /* Language id */
136724  int iIndex,                     /* Index for p->aIndex */
136725  int iLevel,
136726  int *piIdx
136727){
136728  int rc;                         /* Return Code */
136729  sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
136730  int iNext = 0;                  /* Result of query pNextIdx */
136731
136732  assert( iLangid>=0 );
136733  assert( p->nIndex>=1 );
136734
136735  /* Set variable iNext to the next available segdir index at level iLevel. */
136736  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
136737  if( rc==SQLITE_OK ){
136738    sqlite3_bind_int64(
136739        pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
136740    );
136741    if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
136742      iNext = sqlite3_column_int(pNextIdx, 0);
136743    }
136744    rc = sqlite3_reset(pNextIdx);
136745  }
136746
136747  if( rc==SQLITE_OK ){
136748    /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
136749    ** full, merge all segments in level iLevel into a single iLevel+1
136750    ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
136751    ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
136752    */
136753    if( iNext>=FTS3_MERGE_COUNT ){
136754      fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
136755      rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
136756      *piIdx = 0;
136757    }else{
136758      *piIdx = iNext;
136759    }
136760  }
136761
136762  return rc;
136763}
136764
136765/*
136766** The %_segments table is declared as follows:
136767**
136768**   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
136769**
136770** This function reads data from a single row of the %_segments table. The
136771** specific row is identified by the iBlockid parameter. If paBlob is not
136772** NULL, then a buffer is allocated using sqlite3_malloc() and populated
136773** with the contents of the blob stored in the "block" column of the
136774** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
136775** to the size of the blob in bytes before returning.
136776**
136777** If an error occurs, or the table does not contain the specified row,
136778** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
136779** paBlob is non-NULL, then it is the responsibility of the caller to
136780** eventually free the returned buffer.
136781**
136782** This function may leave an open sqlite3_blob* handle in the
136783** Fts3Table.pSegments variable. This handle is reused by subsequent calls
136784** to this function. The handle may be closed by calling the
136785** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
136786** performance improvement, but the blob handle should always be closed
136787** before control is returned to the user (to prevent a lock being held
136788** on the database file for longer than necessary). Thus, any virtual table
136789** method (xFilter etc.) that may directly or indirectly call this function
136790** must call sqlite3Fts3SegmentsClose() before returning.
136791*/
136792SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
136793  Fts3Table *p,                   /* FTS3 table handle */
136794  sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
136795  char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
136796  int *pnBlob,                    /* OUT: Size of blob data */
136797  int *pnLoad                     /* OUT: Bytes actually loaded */
136798){
136799  int rc;                         /* Return code */
136800
136801  /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
136802  assert( pnBlob );
136803
136804  if( p->pSegments ){
136805    rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
136806  }else{
136807    if( 0==p->zSegmentsTbl ){
136808      p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
136809      if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
136810    }
136811    rc = sqlite3_blob_open(
136812       p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
136813    );
136814  }
136815
136816  if( rc==SQLITE_OK ){
136817    int nByte = sqlite3_blob_bytes(p->pSegments);
136818    *pnBlob = nByte;
136819    if( paBlob ){
136820      char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
136821      if( !aByte ){
136822        rc = SQLITE_NOMEM;
136823      }else{
136824        if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
136825          nByte = FTS3_NODE_CHUNKSIZE;
136826          *pnLoad = nByte;
136827        }
136828        rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
136829        memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
136830        if( rc!=SQLITE_OK ){
136831          sqlite3_free(aByte);
136832          aByte = 0;
136833        }
136834      }
136835      *paBlob = aByte;
136836    }
136837  }
136838
136839  return rc;
136840}
136841
136842/*
136843** Close the blob handle at p->pSegments, if it is open. See comments above
136844** the sqlite3Fts3ReadBlock() function for details.
136845*/
136846SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
136847  sqlite3_blob_close(p->pSegments);
136848  p->pSegments = 0;
136849}
136850
136851static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
136852  int nRead;                      /* Number of bytes to read */
136853  int rc;                         /* Return code */
136854
136855  nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
136856  rc = sqlite3_blob_read(
136857      pReader->pBlob,
136858      &pReader->aNode[pReader->nPopulate],
136859      nRead,
136860      pReader->nPopulate
136861  );
136862
136863  if( rc==SQLITE_OK ){
136864    pReader->nPopulate += nRead;
136865    memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
136866    if( pReader->nPopulate==pReader->nNode ){
136867      sqlite3_blob_close(pReader->pBlob);
136868      pReader->pBlob = 0;
136869      pReader->nPopulate = 0;
136870    }
136871  }
136872  return rc;
136873}
136874
136875static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
136876  int rc = SQLITE_OK;
136877  assert( !pReader->pBlob
136878       || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
136879  );
136880  while( pReader->pBlob && rc==SQLITE_OK
136881     &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
136882  ){
136883    rc = fts3SegReaderIncrRead(pReader);
136884  }
136885  return rc;
136886}
136887
136888/*
136889** Set an Fts3SegReader cursor to point at EOF.
136890*/
136891static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
136892  if( !fts3SegReaderIsRootOnly(pSeg) ){
136893    sqlite3_free(pSeg->aNode);
136894    sqlite3_blob_close(pSeg->pBlob);
136895    pSeg->pBlob = 0;
136896  }
136897  pSeg->aNode = 0;
136898}
136899
136900/*
136901** Move the iterator passed as the first argument to the next term in the
136902** segment. If successful, SQLITE_OK is returned. If there is no next term,
136903** SQLITE_DONE. Otherwise, an SQLite error code.
136904*/
136905static int fts3SegReaderNext(
136906  Fts3Table *p,
136907  Fts3SegReader *pReader,
136908  int bIncr
136909){
136910  int rc;                         /* Return code of various sub-routines */
136911  char *pNext;                    /* Cursor variable */
136912  int nPrefix;                    /* Number of bytes in term prefix */
136913  int nSuffix;                    /* Number of bytes in term suffix */
136914
136915  if( !pReader->aDoclist ){
136916    pNext = pReader->aNode;
136917  }else{
136918    pNext = &pReader->aDoclist[pReader->nDoclist];
136919  }
136920
136921  if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
136922
136923    if( fts3SegReaderIsPending(pReader) ){
136924      Fts3HashElem *pElem = *(pReader->ppNextElem);
136925      if( pElem==0 ){
136926        pReader->aNode = 0;
136927      }else{
136928        PendingList *pList = (PendingList *)fts3HashData(pElem);
136929        pReader->zTerm = (char *)fts3HashKey(pElem);
136930        pReader->nTerm = fts3HashKeysize(pElem);
136931        pReader->nNode = pReader->nDoclist = pList->nData + 1;
136932        pReader->aNode = pReader->aDoclist = pList->aData;
136933        pReader->ppNextElem++;
136934        assert( pReader->aNode );
136935      }
136936      return SQLITE_OK;
136937    }
136938
136939    fts3SegReaderSetEof(pReader);
136940
136941    /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
136942    ** blocks have already been traversed.  */
136943    assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
136944    if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
136945      return SQLITE_OK;
136946    }
136947
136948    rc = sqlite3Fts3ReadBlock(
136949        p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
136950        (bIncr ? &pReader->nPopulate : 0)
136951    );
136952    if( rc!=SQLITE_OK ) return rc;
136953    assert( pReader->pBlob==0 );
136954    if( bIncr && pReader->nPopulate<pReader->nNode ){
136955      pReader->pBlob = p->pSegments;
136956      p->pSegments = 0;
136957    }
136958    pNext = pReader->aNode;
136959  }
136960
136961  assert( !fts3SegReaderIsPending(pReader) );
136962
136963  rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
136964  if( rc!=SQLITE_OK ) return rc;
136965
136966  /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
136967  ** safe (no risk of overread) even if the node data is corrupted. */
136968  pNext += fts3GetVarint32(pNext, &nPrefix);
136969  pNext += fts3GetVarint32(pNext, &nSuffix);
136970  if( nPrefix<0 || nSuffix<=0
136971   || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
136972  ){
136973    return FTS_CORRUPT_VTAB;
136974  }
136975
136976  if( nPrefix+nSuffix>pReader->nTermAlloc ){
136977    int nNew = (nPrefix+nSuffix)*2;
136978    char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
136979    if( !zNew ){
136980      return SQLITE_NOMEM;
136981    }
136982    pReader->zTerm = zNew;
136983    pReader->nTermAlloc = nNew;
136984  }
136985
136986  rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
136987  if( rc!=SQLITE_OK ) return rc;
136988
136989  memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
136990  pReader->nTerm = nPrefix+nSuffix;
136991  pNext += nSuffix;
136992  pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
136993  pReader->aDoclist = pNext;
136994  pReader->pOffsetList = 0;
136995
136996  /* Check that the doclist does not appear to extend past the end of the
136997  ** b-tree node. And that the final byte of the doclist is 0x00. If either
136998  ** of these statements is untrue, then the data structure is corrupt.
136999  */
137000  if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
137001   || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
137002  ){
137003    return FTS_CORRUPT_VTAB;
137004  }
137005  return SQLITE_OK;
137006}
137007
137008/*
137009** Set the SegReader to point to the first docid in the doclist associated
137010** with the current term.
137011*/
137012static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
137013  int rc = SQLITE_OK;
137014  assert( pReader->aDoclist );
137015  assert( !pReader->pOffsetList );
137016  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
137017    u8 bEof = 0;
137018    pReader->iDocid = 0;
137019    pReader->nOffsetList = 0;
137020    sqlite3Fts3DoclistPrev(0,
137021        pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
137022        &pReader->iDocid, &pReader->nOffsetList, &bEof
137023    );
137024  }else{
137025    rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
137026    if( rc==SQLITE_OK ){
137027      int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
137028      pReader->pOffsetList = &pReader->aDoclist[n];
137029    }
137030  }
137031  return rc;
137032}
137033
137034/*
137035** Advance the SegReader to point to the next docid in the doclist
137036** associated with the current term.
137037**
137038** If arguments ppOffsetList and pnOffsetList are not NULL, then
137039** *ppOffsetList is set to point to the first column-offset list
137040** in the doclist entry (i.e. immediately past the docid varint).
137041** *pnOffsetList is set to the length of the set of column-offset
137042** lists, not including the nul-terminator byte. For example:
137043*/
137044static int fts3SegReaderNextDocid(
137045  Fts3Table *pTab,
137046  Fts3SegReader *pReader,         /* Reader to advance to next docid */
137047  char **ppOffsetList,            /* OUT: Pointer to current position-list */
137048  int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
137049){
137050  int rc = SQLITE_OK;
137051  char *p = pReader->pOffsetList;
137052  char c = 0;
137053
137054  assert( p );
137055
137056  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
137057    /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
137058    ** Pending-terms doclists are always built up in ascending order, so
137059    ** we have to iterate through them backwards here. */
137060    u8 bEof = 0;
137061    if( ppOffsetList ){
137062      *ppOffsetList = pReader->pOffsetList;
137063      *pnOffsetList = pReader->nOffsetList - 1;
137064    }
137065    sqlite3Fts3DoclistPrev(0,
137066        pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
137067        &pReader->nOffsetList, &bEof
137068    );
137069    if( bEof ){
137070      pReader->pOffsetList = 0;
137071    }else{
137072      pReader->pOffsetList = p;
137073    }
137074  }else{
137075    char *pEnd = &pReader->aDoclist[pReader->nDoclist];
137076
137077    /* Pointer p currently points at the first byte of an offset list. The
137078    ** following block advances it to point one byte past the end of
137079    ** the same offset list. */
137080    while( 1 ){
137081
137082      /* The following line of code (and the "p++" below the while() loop) is
137083      ** normally all that is required to move pointer p to the desired
137084      ** position. The exception is if this node is being loaded from disk
137085      ** incrementally and pointer "p" now points to the first byte past
137086      ** the populated part of pReader->aNode[].
137087      */
137088      while( *p | c ) c = *p++ & 0x80;
137089      assert( *p==0 );
137090
137091      if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
137092      rc = fts3SegReaderIncrRead(pReader);
137093      if( rc!=SQLITE_OK ) return rc;
137094    }
137095    p++;
137096
137097    /* If required, populate the output variables with a pointer to and the
137098    ** size of the previous offset-list.
137099    */
137100    if( ppOffsetList ){
137101      *ppOffsetList = pReader->pOffsetList;
137102      *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
137103    }
137104
137105    /* List may have been edited in place by fts3EvalNearTrim() */
137106    while( p<pEnd && *p==0 ) p++;
137107
137108    /* If there are no more entries in the doclist, set pOffsetList to
137109    ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
137110    ** Fts3SegReader.pOffsetList to point to the next offset list before
137111    ** returning.
137112    */
137113    if( p>=pEnd ){
137114      pReader->pOffsetList = 0;
137115    }else{
137116      rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
137117      if( rc==SQLITE_OK ){
137118        sqlite3_int64 iDelta;
137119        pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
137120        if( pTab->bDescIdx ){
137121          pReader->iDocid -= iDelta;
137122        }else{
137123          pReader->iDocid += iDelta;
137124        }
137125      }
137126    }
137127  }
137128
137129  return SQLITE_OK;
137130}
137131
137132
137133SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
137134  Fts3Cursor *pCsr,
137135  Fts3MultiSegReader *pMsr,
137136  int *pnOvfl
137137){
137138  Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
137139  int nOvfl = 0;
137140  int ii;
137141  int rc = SQLITE_OK;
137142  int pgsz = p->nPgsz;
137143
137144  assert( p->bFts4 );
137145  assert( pgsz>0 );
137146
137147  for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
137148    Fts3SegReader *pReader = pMsr->apSegment[ii];
137149    if( !fts3SegReaderIsPending(pReader)
137150     && !fts3SegReaderIsRootOnly(pReader)
137151    ){
137152      sqlite3_int64 jj;
137153      for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
137154        int nBlob;
137155        rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
137156        if( rc!=SQLITE_OK ) break;
137157        if( (nBlob+35)>pgsz ){
137158          nOvfl += (nBlob + 34)/pgsz;
137159        }
137160      }
137161    }
137162  }
137163  *pnOvfl = nOvfl;
137164  return rc;
137165}
137166
137167/*
137168** Free all allocations associated with the iterator passed as the
137169** second argument.
137170*/
137171SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
137172  if( pReader && !fts3SegReaderIsPending(pReader) ){
137173    sqlite3_free(pReader->zTerm);
137174    if( !fts3SegReaderIsRootOnly(pReader) ){
137175      sqlite3_free(pReader->aNode);
137176      sqlite3_blob_close(pReader->pBlob);
137177    }
137178  }
137179  sqlite3_free(pReader);
137180}
137181
137182/*
137183** Allocate a new SegReader object.
137184*/
137185SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
137186  int iAge,                       /* Segment "age". */
137187  int bLookup,                    /* True for a lookup only */
137188  sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
137189  sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
137190  sqlite3_int64 iEndBlock,        /* Final block of segment */
137191  const char *zRoot,              /* Buffer containing root node */
137192  int nRoot,                      /* Size of buffer containing root node */
137193  Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
137194){
137195  Fts3SegReader *pReader;         /* Newly allocated SegReader object */
137196  int nExtra = 0;                 /* Bytes to allocate segment root node */
137197
137198  assert( iStartLeaf<=iEndLeaf );
137199  if( iStartLeaf==0 ){
137200    nExtra = nRoot + FTS3_NODE_PADDING;
137201  }
137202
137203  pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
137204  if( !pReader ){
137205    return SQLITE_NOMEM;
137206  }
137207  memset(pReader, 0, sizeof(Fts3SegReader));
137208  pReader->iIdx = iAge;
137209  pReader->bLookup = bLookup!=0;
137210  pReader->iStartBlock = iStartLeaf;
137211  pReader->iLeafEndBlock = iEndLeaf;
137212  pReader->iEndBlock = iEndBlock;
137213
137214  if( nExtra ){
137215    /* The entire segment is stored in the root node. */
137216    pReader->aNode = (char *)&pReader[1];
137217    pReader->rootOnly = 1;
137218    pReader->nNode = nRoot;
137219    memcpy(pReader->aNode, zRoot, nRoot);
137220    memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
137221  }else{
137222    pReader->iCurrentBlock = iStartLeaf-1;
137223  }
137224  *ppReader = pReader;
137225  return SQLITE_OK;
137226}
137227
137228/*
137229** This is a comparison function used as a qsort() callback when sorting
137230** an array of pending terms by term. This occurs as part of flushing
137231** the contents of the pending-terms hash table to the database.
137232*/
137233static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
137234  char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
137235  char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
137236  int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
137237  int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
137238
137239  int n = (n1<n2 ? n1 : n2);
137240  int c = memcmp(z1, z2, n);
137241  if( c==0 ){
137242    c = n1 - n2;
137243  }
137244  return c;
137245}
137246
137247/*
137248** This function is used to allocate an Fts3SegReader that iterates through
137249** a subset of the terms stored in the Fts3Table.pendingTerms array.
137250**
137251** If the isPrefixIter parameter is zero, then the returned SegReader iterates
137252** through each term in the pending-terms table. Or, if isPrefixIter is
137253** non-zero, it iterates through each term and its prefixes. For example, if
137254** the pending terms hash table contains the terms "sqlite", "mysql" and
137255** "firebird", then the iterator visits the following 'terms' (in the order
137256** shown):
137257**
137258**   f fi fir fire fireb firebi firebir firebird
137259**   m my mys mysq mysql
137260**   s sq sql sqli sqlit sqlite
137261**
137262** Whereas if isPrefixIter is zero, the terms visited are:
137263**
137264**   firebird mysql sqlite
137265*/
137266SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
137267  Fts3Table *p,                   /* Virtual table handle */
137268  int iIndex,                     /* Index for p->aIndex */
137269  const char *zTerm,              /* Term to search for */
137270  int nTerm,                      /* Size of buffer zTerm */
137271  int bPrefix,                    /* True for a prefix iterator */
137272  Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
137273){
137274  Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
137275  Fts3HashElem *pE;               /* Iterator variable */
137276  Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
137277  int nElem = 0;                  /* Size of array at aElem */
137278  int rc = SQLITE_OK;             /* Return Code */
137279  Fts3Hash *pHash;
137280
137281  pHash = &p->aIndex[iIndex].hPending;
137282  if( bPrefix ){
137283    int nAlloc = 0;               /* Size of allocated array at aElem */
137284
137285    for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
137286      char *zKey = (char *)fts3HashKey(pE);
137287      int nKey = fts3HashKeysize(pE);
137288      if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
137289        if( nElem==nAlloc ){
137290          Fts3HashElem **aElem2;
137291          nAlloc += 16;
137292          aElem2 = (Fts3HashElem **)sqlite3_realloc(
137293              aElem, nAlloc*sizeof(Fts3HashElem *)
137294          );
137295          if( !aElem2 ){
137296            rc = SQLITE_NOMEM;
137297            nElem = 0;
137298            break;
137299          }
137300          aElem = aElem2;
137301        }
137302
137303        aElem[nElem++] = pE;
137304      }
137305    }
137306
137307    /* If more than one term matches the prefix, sort the Fts3HashElem
137308    ** objects in term order using qsort(). This uses the same comparison
137309    ** callback as is used when flushing terms to disk.
137310    */
137311    if( nElem>1 ){
137312      qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
137313    }
137314
137315  }else{
137316    /* The query is a simple term lookup that matches at most one term in
137317    ** the index. All that is required is a straight hash-lookup.
137318    **
137319    ** Because the stack address of pE may be accessed via the aElem pointer
137320    ** below, the "Fts3HashElem *pE" must be declared so that it is valid
137321    ** within this entire function, not just this "else{...}" block.
137322    */
137323    pE = fts3HashFindElem(pHash, zTerm, nTerm);
137324    if( pE ){
137325      aElem = &pE;
137326      nElem = 1;
137327    }
137328  }
137329
137330  if( nElem>0 ){
137331    int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
137332    pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
137333    if( !pReader ){
137334      rc = SQLITE_NOMEM;
137335    }else{
137336      memset(pReader, 0, nByte);
137337      pReader->iIdx = 0x7FFFFFFF;
137338      pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
137339      memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
137340    }
137341  }
137342
137343  if( bPrefix ){
137344    sqlite3_free(aElem);
137345  }
137346  *ppReader = pReader;
137347  return rc;
137348}
137349
137350/*
137351** Compare the entries pointed to by two Fts3SegReader structures.
137352** Comparison is as follows:
137353**
137354**   1) EOF is greater than not EOF.
137355**
137356**   2) The current terms (if any) are compared using memcmp(). If one
137357**      term is a prefix of another, the longer term is considered the
137358**      larger.
137359**
137360**   3) By segment age. An older segment is considered larger.
137361*/
137362static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
137363  int rc;
137364  if( pLhs->aNode && pRhs->aNode ){
137365    int rc2 = pLhs->nTerm - pRhs->nTerm;
137366    if( rc2<0 ){
137367      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
137368    }else{
137369      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
137370    }
137371    if( rc==0 ){
137372      rc = rc2;
137373    }
137374  }else{
137375    rc = (pLhs->aNode==0) - (pRhs->aNode==0);
137376  }
137377  if( rc==0 ){
137378    rc = pRhs->iIdx - pLhs->iIdx;
137379  }
137380  assert( rc!=0 );
137381  return rc;
137382}
137383
137384/*
137385** A different comparison function for SegReader structures. In this
137386** version, it is assumed that each SegReader points to an entry in
137387** a doclist for identical terms. Comparison is made as follows:
137388**
137389**   1) EOF (end of doclist in this case) is greater than not EOF.
137390**
137391**   2) By current docid.
137392**
137393**   3) By segment age. An older segment is considered larger.
137394*/
137395static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
137396  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
137397  if( rc==0 ){
137398    if( pLhs->iDocid==pRhs->iDocid ){
137399      rc = pRhs->iIdx - pLhs->iIdx;
137400    }else{
137401      rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
137402    }
137403  }
137404  assert( pLhs->aNode && pRhs->aNode );
137405  return rc;
137406}
137407static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
137408  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
137409  if( rc==0 ){
137410    if( pLhs->iDocid==pRhs->iDocid ){
137411      rc = pRhs->iIdx - pLhs->iIdx;
137412    }else{
137413      rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
137414    }
137415  }
137416  assert( pLhs->aNode && pRhs->aNode );
137417  return rc;
137418}
137419
137420/*
137421** Compare the term that the Fts3SegReader object passed as the first argument
137422** points to with the term specified by arguments zTerm and nTerm.
137423**
137424** If the pSeg iterator is already at EOF, return 0. Otherwise, return
137425** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
137426** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
137427*/
137428static int fts3SegReaderTermCmp(
137429  Fts3SegReader *pSeg,            /* Segment reader object */
137430  const char *zTerm,              /* Term to compare to */
137431  int nTerm                       /* Size of term zTerm in bytes */
137432){
137433  int res = 0;
137434  if( pSeg->aNode ){
137435    if( pSeg->nTerm>nTerm ){
137436      res = memcmp(pSeg->zTerm, zTerm, nTerm);
137437    }else{
137438      res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
137439    }
137440    if( res==0 ){
137441      res = pSeg->nTerm-nTerm;
137442    }
137443  }
137444  return res;
137445}
137446
137447/*
137448** Argument apSegment is an array of nSegment elements. It is known that
137449** the final (nSegment-nSuspect) members are already in sorted order
137450** (according to the comparison function provided). This function shuffles
137451** the array around until all entries are in sorted order.
137452*/
137453static void fts3SegReaderSort(
137454  Fts3SegReader **apSegment,                     /* Array to sort entries of */
137455  int nSegment,                                  /* Size of apSegment array */
137456  int nSuspect,                                  /* Unsorted entry count */
137457  int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
137458){
137459  int i;                          /* Iterator variable */
137460
137461  assert( nSuspect<=nSegment );
137462
137463  if( nSuspect==nSegment ) nSuspect--;
137464  for(i=nSuspect-1; i>=0; i--){
137465    int j;
137466    for(j=i; j<(nSegment-1); j++){
137467      Fts3SegReader *pTmp;
137468      if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
137469      pTmp = apSegment[j+1];
137470      apSegment[j+1] = apSegment[j];
137471      apSegment[j] = pTmp;
137472    }
137473  }
137474
137475#ifndef NDEBUG
137476  /* Check that the list really is sorted now. */
137477  for(i=0; i<(nSuspect-1); i++){
137478    assert( xCmp(apSegment[i], apSegment[i+1])<0 );
137479  }
137480#endif
137481}
137482
137483/*
137484** Insert a record into the %_segments table.
137485*/
137486static int fts3WriteSegment(
137487  Fts3Table *p,                   /* Virtual table handle */
137488  sqlite3_int64 iBlock,           /* Block id for new block */
137489  char *z,                        /* Pointer to buffer containing block data */
137490  int n                           /* Size of buffer z in bytes */
137491){
137492  sqlite3_stmt *pStmt;
137493  int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
137494  if( rc==SQLITE_OK ){
137495    sqlite3_bind_int64(pStmt, 1, iBlock);
137496    sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
137497    sqlite3_step(pStmt);
137498    rc = sqlite3_reset(pStmt);
137499  }
137500  return rc;
137501}
137502
137503/*
137504** Find the largest relative level number in the table. If successful, set
137505** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
137506** set *pnMax to zero and return an SQLite error code.
137507*/
137508SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
137509  int rc;
137510  int mxLevel = 0;
137511  sqlite3_stmt *pStmt = 0;
137512
137513  rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
137514  if( rc==SQLITE_OK ){
137515    if( SQLITE_ROW==sqlite3_step(pStmt) ){
137516      mxLevel = sqlite3_column_int(pStmt, 0);
137517    }
137518    rc = sqlite3_reset(pStmt);
137519  }
137520  *pnMax = mxLevel;
137521  return rc;
137522}
137523
137524/*
137525** Insert a record into the %_segdir table.
137526*/
137527static int fts3WriteSegdir(
137528  Fts3Table *p,                   /* Virtual table handle */
137529  sqlite3_int64 iLevel,           /* Value for "level" field (absolute level) */
137530  int iIdx,                       /* Value for "idx" field */
137531  sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
137532  sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
137533  sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
137534  sqlite3_int64 nLeafData,        /* Bytes of leaf data in segment */
137535  char *zRoot,                    /* Blob value for "root" field */
137536  int nRoot                       /* Number of bytes in buffer zRoot */
137537){
137538  sqlite3_stmt *pStmt;
137539  int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
137540  if( rc==SQLITE_OK ){
137541    sqlite3_bind_int64(pStmt, 1, iLevel);
137542    sqlite3_bind_int(pStmt, 2, iIdx);
137543    sqlite3_bind_int64(pStmt, 3, iStartBlock);
137544    sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
137545    if( nLeafData==0 ){
137546      sqlite3_bind_int64(pStmt, 5, iEndBlock);
137547    }else{
137548      char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
137549      if( !zEnd ) return SQLITE_NOMEM;
137550      sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
137551    }
137552    sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
137553    sqlite3_step(pStmt);
137554    rc = sqlite3_reset(pStmt);
137555  }
137556  return rc;
137557}
137558
137559/*
137560** Return the size of the common prefix (if any) shared by zPrev and
137561** zNext, in bytes. For example,
137562**
137563**   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
137564**   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
137565**   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
137566*/
137567static int fts3PrefixCompress(
137568  const char *zPrev,              /* Buffer containing previous term */
137569  int nPrev,                      /* Size of buffer zPrev in bytes */
137570  const char *zNext,              /* Buffer containing next term */
137571  int nNext                       /* Size of buffer zNext in bytes */
137572){
137573  int n;
137574  UNUSED_PARAMETER(nNext);
137575  for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
137576  return n;
137577}
137578
137579/*
137580** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
137581** (according to memcmp) than the previous term.
137582*/
137583static int fts3NodeAddTerm(
137584  Fts3Table *p,                   /* Virtual table handle */
137585  SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
137586  int isCopyTerm,                 /* True if zTerm/nTerm is transient */
137587  const char *zTerm,              /* Pointer to buffer containing term */
137588  int nTerm                       /* Size of term in bytes */
137589){
137590  SegmentNode *pTree = *ppTree;
137591  int rc;
137592  SegmentNode *pNew;
137593
137594  /* First try to append the term to the current node. Return early if
137595  ** this is possible.
137596  */
137597  if( pTree ){
137598    int nData = pTree->nData;     /* Current size of node in bytes */
137599    int nReq = nData;             /* Required space after adding zTerm */
137600    int nPrefix;                  /* Number of bytes of prefix compression */
137601    int nSuffix;                  /* Suffix length */
137602
137603    nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
137604    nSuffix = nTerm-nPrefix;
137605
137606    nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
137607    if( nReq<=p->nNodeSize || !pTree->zTerm ){
137608
137609      if( nReq>p->nNodeSize ){
137610        /* An unusual case: this is the first term to be added to the node
137611        ** and the static node buffer (p->nNodeSize bytes) is not large
137612        ** enough. Use a separately malloced buffer instead This wastes
137613        ** p->nNodeSize bytes, but since this scenario only comes about when
137614        ** the database contain two terms that share a prefix of almost 2KB,
137615        ** this is not expected to be a serious problem.
137616        */
137617        assert( pTree->aData==(char *)&pTree[1] );
137618        pTree->aData = (char *)sqlite3_malloc(nReq);
137619        if( !pTree->aData ){
137620          return SQLITE_NOMEM;
137621        }
137622      }
137623
137624      if( pTree->zTerm ){
137625        /* There is no prefix-length field for first term in a node */
137626        nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
137627      }
137628
137629      nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
137630      memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
137631      pTree->nData = nData + nSuffix;
137632      pTree->nEntry++;
137633
137634      if( isCopyTerm ){
137635        if( pTree->nMalloc<nTerm ){
137636          char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
137637          if( !zNew ){
137638            return SQLITE_NOMEM;
137639          }
137640          pTree->nMalloc = nTerm*2;
137641          pTree->zMalloc = zNew;
137642        }
137643        pTree->zTerm = pTree->zMalloc;
137644        memcpy(pTree->zTerm, zTerm, nTerm);
137645        pTree->nTerm = nTerm;
137646      }else{
137647        pTree->zTerm = (char *)zTerm;
137648        pTree->nTerm = nTerm;
137649      }
137650      return SQLITE_OK;
137651    }
137652  }
137653
137654  /* If control flows to here, it was not possible to append zTerm to the
137655  ** current node. Create a new node (a right-sibling of the current node).
137656  ** If this is the first node in the tree, the term is added to it.
137657  **
137658  ** Otherwise, the term is not added to the new node, it is left empty for
137659  ** now. Instead, the term is inserted into the parent of pTree. If pTree
137660  ** has no parent, one is created here.
137661  */
137662  pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
137663  if( !pNew ){
137664    return SQLITE_NOMEM;
137665  }
137666  memset(pNew, 0, sizeof(SegmentNode));
137667  pNew->nData = 1 + FTS3_VARINT_MAX;
137668  pNew->aData = (char *)&pNew[1];
137669
137670  if( pTree ){
137671    SegmentNode *pParent = pTree->pParent;
137672    rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
137673    if( pTree->pParent==0 ){
137674      pTree->pParent = pParent;
137675    }
137676    pTree->pRight = pNew;
137677    pNew->pLeftmost = pTree->pLeftmost;
137678    pNew->pParent = pParent;
137679    pNew->zMalloc = pTree->zMalloc;
137680    pNew->nMalloc = pTree->nMalloc;
137681    pTree->zMalloc = 0;
137682  }else{
137683    pNew->pLeftmost = pNew;
137684    rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
137685  }
137686
137687  *ppTree = pNew;
137688  return rc;
137689}
137690
137691/*
137692** Helper function for fts3NodeWrite().
137693*/
137694static int fts3TreeFinishNode(
137695  SegmentNode *pTree,
137696  int iHeight,
137697  sqlite3_int64 iLeftChild
137698){
137699  int nStart;
137700  assert( iHeight>=1 && iHeight<128 );
137701  nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
137702  pTree->aData[nStart] = (char)iHeight;
137703  sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
137704  return nStart;
137705}
137706
137707/*
137708** Write the buffer for the segment node pTree and all of its peers to the
137709** database. Then call this function recursively to write the parent of
137710** pTree and its peers to the database.
137711**
137712** Except, if pTree is a root node, do not write it to the database. Instead,
137713** set output variables *paRoot and *pnRoot to contain the root node.
137714**
137715** If successful, SQLITE_OK is returned and output variable *piLast is
137716** set to the largest blockid written to the database (or zero if no
137717** blocks were written to the db). Otherwise, an SQLite error code is
137718** returned.
137719*/
137720static int fts3NodeWrite(
137721  Fts3Table *p,                   /* Virtual table handle */
137722  SegmentNode *pTree,             /* SegmentNode handle */
137723  int iHeight,                    /* Height of this node in tree */
137724  sqlite3_int64 iLeaf,            /* Block id of first leaf node */
137725  sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
137726  sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
137727  char **paRoot,                  /* OUT: Data for root node */
137728  int *pnRoot                     /* OUT: Size of root node in bytes */
137729){
137730  int rc = SQLITE_OK;
137731
137732  if( !pTree->pParent ){
137733    /* Root node of the tree. */
137734    int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
137735    *piLast = iFree-1;
137736    *pnRoot = pTree->nData - nStart;
137737    *paRoot = &pTree->aData[nStart];
137738  }else{
137739    SegmentNode *pIter;
137740    sqlite3_int64 iNextFree = iFree;
137741    sqlite3_int64 iNextLeaf = iLeaf;
137742    for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
137743      int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
137744      int nWrite = pIter->nData - nStart;
137745
137746      rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
137747      iNextFree++;
137748      iNextLeaf += (pIter->nEntry+1);
137749    }
137750    if( rc==SQLITE_OK ){
137751      assert( iNextLeaf==iFree );
137752      rc = fts3NodeWrite(
137753          p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
137754      );
137755    }
137756  }
137757
137758  return rc;
137759}
137760
137761/*
137762** Free all memory allocations associated with the tree pTree.
137763*/
137764static void fts3NodeFree(SegmentNode *pTree){
137765  if( pTree ){
137766    SegmentNode *p = pTree->pLeftmost;
137767    fts3NodeFree(p->pParent);
137768    while( p ){
137769      SegmentNode *pRight = p->pRight;
137770      if( p->aData!=(char *)&p[1] ){
137771        sqlite3_free(p->aData);
137772      }
137773      assert( pRight==0 || p->zMalloc==0 );
137774      sqlite3_free(p->zMalloc);
137775      sqlite3_free(p);
137776      p = pRight;
137777    }
137778  }
137779}
137780
137781/*
137782** Add a term to the segment being constructed by the SegmentWriter object
137783** *ppWriter. When adding the first term to a segment, *ppWriter should
137784** be passed NULL. This function will allocate a new SegmentWriter object
137785** and return it via the input/output variable *ppWriter in this case.
137786**
137787** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
137788*/
137789static int fts3SegWriterAdd(
137790  Fts3Table *p,                   /* Virtual table handle */
137791  SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
137792  int isCopyTerm,                 /* True if buffer zTerm must be copied */
137793  const char *zTerm,              /* Pointer to buffer containing term */
137794  int nTerm,                      /* Size of term in bytes */
137795  const char *aDoclist,           /* Pointer to buffer containing doclist */
137796  int nDoclist                    /* Size of doclist in bytes */
137797){
137798  int nPrefix;                    /* Size of term prefix in bytes */
137799  int nSuffix;                    /* Size of term suffix in bytes */
137800  int nReq;                       /* Number of bytes required on leaf page */
137801  int nData;
137802  SegmentWriter *pWriter = *ppWriter;
137803
137804  if( !pWriter ){
137805    int rc;
137806    sqlite3_stmt *pStmt;
137807
137808    /* Allocate the SegmentWriter structure */
137809    pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
137810    if( !pWriter ) return SQLITE_NOMEM;
137811    memset(pWriter, 0, sizeof(SegmentWriter));
137812    *ppWriter = pWriter;
137813
137814    /* Allocate a buffer in which to accumulate data */
137815    pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
137816    if( !pWriter->aData ) return SQLITE_NOMEM;
137817    pWriter->nSize = p->nNodeSize;
137818
137819    /* Find the next free blockid in the %_segments table */
137820    rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
137821    if( rc!=SQLITE_OK ) return rc;
137822    if( SQLITE_ROW==sqlite3_step(pStmt) ){
137823      pWriter->iFree = sqlite3_column_int64(pStmt, 0);
137824      pWriter->iFirst = pWriter->iFree;
137825    }
137826    rc = sqlite3_reset(pStmt);
137827    if( rc!=SQLITE_OK ) return rc;
137828  }
137829  nData = pWriter->nData;
137830
137831  nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
137832  nSuffix = nTerm-nPrefix;
137833
137834  /* Figure out how many bytes are required by this new entry */
137835  nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
137836    sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
137837    nSuffix +                               /* Term suffix */
137838    sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
137839    nDoclist;                               /* Doclist data */
137840
137841  if( nData>0 && nData+nReq>p->nNodeSize ){
137842    int rc;
137843
137844    /* The current leaf node is full. Write it out to the database. */
137845    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
137846    if( rc!=SQLITE_OK ) return rc;
137847    p->nLeafAdd++;
137848
137849    /* Add the current term to the interior node tree. The term added to
137850    ** the interior tree must:
137851    **
137852    **   a) be greater than the largest term on the leaf node just written
137853    **      to the database (still available in pWriter->zTerm), and
137854    **
137855    **   b) be less than or equal to the term about to be added to the new
137856    **      leaf node (zTerm/nTerm).
137857    **
137858    ** In other words, it must be the prefix of zTerm 1 byte longer than
137859    ** the common prefix (if any) of zTerm and pWriter->zTerm.
137860    */
137861    assert( nPrefix<nTerm );
137862    rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
137863    if( rc!=SQLITE_OK ) return rc;
137864
137865    nData = 0;
137866    pWriter->nTerm = 0;
137867
137868    nPrefix = 0;
137869    nSuffix = nTerm;
137870    nReq = 1 +                              /* varint containing prefix size */
137871      sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
137872      nTerm +                               /* Term suffix */
137873      sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
137874      nDoclist;                             /* Doclist data */
137875  }
137876
137877  /* Increase the total number of bytes written to account for the new entry. */
137878  pWriter->nLeafData += nReq;
137879
137880  /* If the buffer currently allocated is too small for this entry, realloc
137881  ** the buffer to make it large enough.
137882  */
137883  if( nReq>pWriter->nSize ){
137884    char *aNew = sqlite3_realloc(pWriter->aData, nReq);
137885    if( !aNew ) return SQLITE_NOMEM;
137886    pWriter->aData = aNew;
137887    pWriter->nSize = nReq;
137888  }
137889  assert( nData+nReq<=pWriter->nSize );
137890
137891  /* Append the prefix-compressed term and doclist to the buffer. */
137892  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
137893  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
137894  memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
137895  nData += nSuffix;
137896  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
137897  memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
137898  pWriter->nData = nData + nDoclist;
137899
137900  /* Save the current term so that it can be used to prefix-compress the next.
137901  ** If the isCopyTerm parameter is true, then the buffer pointed to by
137902  ** zTerm is transient, so take a copy of the term data. Otherwise, just
137903  ** store a copy of the pointer.
137904  */
137905  if( isCopyTerm ){
137906    if( nTerm>pWriter->nMalloc ){
137907      char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
137908      if( !zNew ){
137909        return SQLITE_NOMEM;
137910      }
137911      pWriter->nMalloc = nTerm*2;
137912      pWriter->zMalloc = zNew;
137913      pWriter->zTerm = zNew;
137914    }
137915    assert( pWriter->zTerm==pWriter->zMalloc );
137916    memcpy(pWriter->zTerm, zTerm, nTerm);
137917  }else{
137918    pWriter->zTerm = (char *)zTerm;
137919  }
137920  pWriter->nTerm = nTerm;
137921
137922  return SQLITE_OK;
137923}
137924
137925/*
137926** Flush all data associated with the SegmentWriter object pWriter to the
137927** database. This function must be called after all terms have been added
137928** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
137929** returned. Otherwise, an SQLite error code.
137930*/
137931static int fts3SegWriterFlush(
137932  Fts3Table *p,                   /* Virtual table handle */
137933  SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
137934  sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
137935  int iIdx                        /* Value for 'idx' column of %_segdir */
137936){
137937  int rc;                         /* Return code */
137938  if( pWriter->pTree ){
137939    sqlite3_int64 iLast = 0;      /* Largest block id written to database */
137940    sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
137941    char *zRoot = NULL;           /* Pointer to buffer containing root node */
137942    int nRoot = 0;                /* Size of buffer zRoot */
137943
137944    iLastLeaf = pWriter->iFree;
137945    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
137946    if( rc==SQLITE_OK ){
137947      rc = fts3NodeWrite(p, pWriter->pTree, 1,
137948          pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
137949    }
137950    if( rc==SQLITE_OK ){
137951      rc = fts3WriteSegdir(p, iLevel, iIdx,
137952          pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
137953    }
137954  }else{
137955    /* The entire tree fits on the root node. Write it to the segdir table. */
137956    rc = fts3WriteSegdir(p, iLevel, iIdx,
137957        0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
137958  }
137959  p->nLeafAdd++;
137960  return rc;
137961}
137962
137963/*
137964** Release all memory held by the SegmentWriter object passed as the
137965** first argument.
137966*/
137967static void fts3SegWriterFree(SegmentWriter *pWriter){
137968  if( pWriter ){
137969    sqlite3_free(pWriter->aData);
137970    sqlite3_free(pWriter->zMalloc);
137971    fts3NodeFree(pWriter->pTree);
137972    sqlite3_free(pWriter);
137973  }
137974}
137975
137976/*
137977** The first value in the apVal[] array is assumed to contain an integer.
137978** This function tests if there exist any documents with docid values that
137979** are different from that integer. i.e. if deleting the document with docid
137980** pRowid would mean the FTS3 table were empty.
137981**
137982** If successful, *pisEmpty is set to true if the table is empty except for
137983** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
137984** error occurs, an SQLite error code is returned.
137985*/
137986static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
137987  sqlite3_stmt *pStmt;
137988  int rc;
137989  if( p->zContentTbl ){
137990    /* If using the content=xxx option, assume the table is never empty */
137991    *pisEmpty = 0;
137992    rc = SQLITE_OK;
137993  }else{
137994    rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
137995    if( rc==SQLITE_OK ){
137996      if( SQLITE_ROW==sqlite3_step(pStmt) ){
137997        *pisEmpty = sqlite3_column_int(pStmt, 0);
137998      }
137999      rc = sqlite3_reset(pStmt);
138000    }
138001  }
138002  return rc;
138003}
138004
138005/*
138006** Set *pnMax to the largest segment level in the database for the index
138007** iIndex.
138008**
138009** Segment levels are stored in the 'level' column of the %_segdir table.
138010**
138011** Return SQLITE_OK if successful, or an SQLite error code if not.
138012*/
138013static int fts3SegmentMaxLevel(
138014  Fts3Table *p,
138015  int iLangid,
138016  int iIndex,
138017  sqlite3_int64 *pnMax
138018){
138019  sqlite3_stmt *pStmt;
138020  int rc;
138021  assert( iIndex>=0 && iIndex<p->nIndex );
138022
138023  /* Set pStmt to the compiled version of:
138024  **
138025  **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
138026  **
138027  ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
138028  */
138029  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
138030  if( rc!=SQLITE_OK ) return rc;
138031  sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
138032  sqlite3_bind_int64(pStmt, 2,
138033      getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
138034  );
138035  if( SQLITE_ROW==sqlite3_step(pStmt) ){
138036    *pnMax = sqlite3_column_int64(pStmt, 0);
138037  }
138038  return sqlite3_reset(pStmt);
138039}
138040
138041/*
138042** iAbsLevel is an absolute level that may be assumed to exist within
138043** the database. This function checks if it is the largest level number
138044** within its index. Assuming no error occurs, *pbMax is set to 1 if
138045** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
138046** is returned. If an error occurs, an error code is returned and the
138047** final value of *pbMax is undefined.
138048*/
138049static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
138050
138051  /* Set pStmt to the compiled version of:
138052  **
138053  **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
138054  **
138055  ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
138056  */
138057  sqlite3_stmt *pStmt;
138058  int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
138059  if( rc!=SQLITE_OK ) return rc;
138060  sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
138061  sqlite3_bind_int64(pStmt, 2,
138062      ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
138063  );
138064
138065  *pbMax = 0;
138066  if( SQLITE_ROW==sqlite3_step(pStmt) ){
138067    *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
138068  }
138069  return sqlite3_reset(pStmt);
138070}
138071
138072/*
138073** Delete all entries in the %_segments table associated with the segment
138074** opened with seg-reader pSeg. This function does not affect the contents
138075** of the %_segdir table.
138076*/
138077static int fts3DeleteSegment(
138078  Fts3Table *p,                   /* FTS table handle */
138079  Fts3SegReader *pSeg             /* Segment to delete */
138080){
138081  int rc = SQLITE_OK;             /* Return code */
138082  if( pSeg->iStartBlock ){
138083    sqlite3_stmt *pDelete;        /* SQL statement to delete rows */
138084    rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
138085    if( rc==SQLITE_OK ){
138086      sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
138087      sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
138088      sqlite3_step(pDelete);
138089      rc = sqlite3_reset(pDelete);
138090    }
138091  }
138092  return rc;
138093}
138094
138095/*
138096** This function is used after merging multiple segments into a single large
138097** segment to delete the old, now redundant, segment b-trees. Specifically,
138098** it:
138099**
138100**   1) Deletes all %_segments entries for the segments associated with
138101**      each of the SegReader objects in the array passed as the third
138102**      argument, and
138103**
138104**   2) deletes all %_segdir entries with level iLevel, or all %_segdir
138105**      entries regardless of level if (iLevel<0).
138106**
138107** SQLITE_OK is returned if successful, otherwise an SQLite error code.
138108*/
138109static int fts3DeleteSegdir(
138110  Fts3Table *p,                   /* Virtual table handle */
138111  int iLangid,                    /* Language id */
138112  int iIndex,                     /* Index for p->aIndex */
138113  int iLevel,                     /* Level of %_segdir entries to delete */
138114  Fts3SegReader **apSegment,      /* Array of SegReader objects */
138115  int nReader                     /* Size of array apSegment */
138116){
138117  int rc = SQLITE_OK;             /* Return Code */
138118  int i;                          /* Iterator variable */
138119  sqlite3_stmt *pDelete = 0;      /* SQL statement to delete rows */
138120
138121  for(i=0; rc==SQLITE_OK && i<nReader; i++){
138122    rc = fts3DeleteSegment(p, apSegment[i]);
138123  }
138124  if( rc!=SQLITE_OK ){
138125    return rc;
138126  }
138127
138128  assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
138129  if( iLevel==FTS3_SEGCURSOR_ALL ){
138130    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
138131    if( rc==SQLITE_OK ){
138132      sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
138133      sqlite3_bind_int64(pDelete, 2,
138134          getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
138135      );
138136    }
138137  }else{
138138    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
138139    if( rc==SQLITE_OK ){
138140      sqlite3_bind_int64(
138141          pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
138142      );
138143    }
138144  }
138145
138146  if( rc==SQLITE_OK ){
138147    sqlite3_step(pDelete);
138148    rc = sqlite3_reset(pDelete);
138149  }
138150
138151  return rc;
138152}
138153
138154/*
138155** When this function is called, buffer *ppList (size *pnList bytes) contains
138156** a position list that may (or may not) feature multiple columns. This
138157** function adjusts the pointer *ppList and the length *pnList so that they
138158** identify the subset of the position list that corresponds to column iCol.
138159**
138160** If there are no entries in the input position list for column iCol, then
138161** *pnList is set to zero before returning.
138162**
138163** If parameter bZero is non-zero, then any part of the input list following
138164** the end of the output list is zeroed before returning.
138165*/
138166static void fts3ColumnFilter(
138167  int iCol,                       /* Column to filter on */
138168  int bZero,                      /* Zero out anything following *ppList */
138169  char **ppList,                  /* IN/OUT: Pointer to position list */
138170  int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
138171){
138172  char *pList = *ppList;
138173  int nList = *pnList;
138174  char *pEnd = &pList[nList];
138175  int iCurrent = 0;
138176  char *p = pList;
138177
138178  assert( iCol>=0 );
138179  while( 1 ){
138180    char c = 0;
138181    while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
138182
138183    if( iCol==iCurrent ){
138184      nList = (int)(p - pList);
138185      break;
138186    }
138187
138188    nList -= (int)(p - pList);
138189    pList = p;
138190    if( nList==0 ){
138191      break;
138192    }
138193    p = &pList[1];
138194    p += fts3GetVarint32(p, &iCurrent);
138195  }
138196
138197  if( bZero && &pList[nList]!=pEnd ){
138198    memset(&pList[nList], 0, pEnd - &pList[nList]);
138199  }
138200  *ppList = pList;
138201  *pnList = nList;
138202}
138203
138204/*
138205** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
138206** existing data). Grow the buffer if required.
138207**
138208** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
138209** trying to resize the buffer, return SQLITE_NOMEM.
138210*/
138211static int fts3MsrBufferData(
138212  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
138213  char *pList,
138214  int nList
138215){
138216  if( nList>pMsr->nBuffer ){
138217    char *pNew;
138218    pMsr->nBuffer = nList*2;
138219    pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
138220    if( !pNew ) return SQLITE_NOMEM;
138221    pMsr->aBuffer = pNew;
138222  }
138223
138224  memcpy(pMsr->aBuffer, pList, nList);
138225  return SQLITE_OK;
138226}
138227
138228SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
138229  Fts3Table *p,                   /* Virtual table handle */
138230  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
138231  sqlite3_int64 *piDocid,         /* OUT: Docid value */
138232  char **paPoslist,               /* OUT: Pointer to position list */
138233  int *pnPoslist                  /* OUT: Size of position list in bytes */
138234){
138235  int nMerge = pMsr->nAdvance;
138236  Fts3SegReader **apSegment = pMsr->apSegment;
138237  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
138238    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
138239  );
138240
138241  if( nMerge==0 ){
138242    *paPoslist = 0;
138243    return SQLITE_OK;
138244  }
138245
138246  while( 1 ){
138247    Fts3SegReader *pSeg;
138248    pSeg = pMsr->apSegment[0];
138249
138250    if( pSeg->pOffsetList==0 ){
138251      *paPoslist = 0;
138252      break;
138253    }else{
138254      int rc;
138255      char *pList;
138256      int nList;
138257      int j;
138258      sqlite3_int64 iDocid = apSegment[0]->iDocid;
138259
138260      rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
138261      j = 1;
138262      while( rc==SQLITE_OK
138263        && j<nMerge
138264        && apSegment[j]->pOffsetList
138265        && apSegment[j]->iDocid==iDocid
138266      ){
138267        rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
138268        j++;
138269      }
138270      if( rc!=SQLITE_OK ) return rc;
138271      fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
138272
138273      if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
138274        rc = fts3MsrBufferData(pMsr, pList, nList+1);
138275        if( rc!=SQLITE_OK ) return rc;
138276        assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
138277        pList = pMsr->aBuffer;
138278      }
138279
138280      if( pMsr->iColFilter>=0 ){
138281        fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
138282      }
138283
138284      if( nList>0 ){
138285        *paPoslist = pList;
138286        *piDocid = iDocid;
138287        *pnPoslist = nList;
138288        break;
138289      }
138290    }
138291  }
138292
138293  return SQLITE_OK;
138294}
138295
138296static int fts3SegReaderStart(
138297  Fts3Table *p,                   /* Virtual table handle */
138298  Fts3MultiSegReader *pCsr,       /* Cursor object */
138299  const char *zTerm,              /* Term searched for (or NULL) */
138300  int nTerm                       /* Length of zTerm in bytes */
138301){
138302  int i;
138303  int nSeg = pCsr->nSegment;
138304
138305  /* If the Fts3SegFilter defines a specific term (or term prefix) to search
138306  ** for, then advance each segment iterator until it points to a term of
138307  ** equal or greater value than the specified term. This prevents many
138308  ** unnecessary merge/sort operations for the case where single segment
138309  ** b-tree leaf nodes contain more than one term.
138310  */
138311  for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
138312    int res = 0;
138313    Fts3SegReader *pSeg = pCsr->apSegment[i];
138314    do {
138315      int rc = fts3SegReaderNext(p, pSeg, 0);
138316      if( rc!=SQLITE_OK ) return rc;
138317    }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
138318
138319    if( pSeg->bLookup && res!=0 ){
138320      fts3SegReaderSetEof(pSeg);
138321    }
138322  }
138323  fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
138324
138325  return SQLITE_OK;
138326}
138327
138328SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
138329  Fts3Table *p,                   /* Virtual table handle */
138330  Fts3MultiSegReader *pCsr,       /* Cursor object */
138331  Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
138332){
138333  pCsr->pFilter = pFilter;
138334  return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
138335}
138336
138337SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
138338  Fts3Table *p,                   /* Virtual table handle */
138339  Fts3MultiSegReader *pCsr,       /* Cursor object */
138340  int iCol,                       /* Column to match on. */
138341  const char *zTerm,              /* Term to iterate through a doclist for */
138342  int nTerm                       /* Number of bytes in zTerm */
138343){
138344  int i;
138345  int rc;
138346  int nSegment = pCsr->nSegment;
138347  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
138348    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
138349  );
138350
138351  assert( pCsr->pFilter==0 );
138352  assert( zTerm && nTerm>0 );
138353
138354  /* Advance each segment iterator until it points to the term zTerm/nTerm. */
138355  rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
138356  if( rc!=SQLITE_OK ) return rc;
138357
138358  /* Determine how many of the segments actually point to zTerm/nTerm. */
138359  for(i=0; i<nSegment; i++){
138360    Fts3SegReader *pSeg = pCsr->apSegment[i];
138361    if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
138362      break;
138363    }
138364  }
138365  pCsr->nAdvance = i;
138366
138367  /* Advance each of the segments to point to the first docid. */
138368  for(i=0; i<pCsr->nAdvance; i++){
138369    rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
138370    if( rc!=SQLITE_OK ) return rc;
138371  }
138372  fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
138373
138374  assert( iCol<0 || iCol<p->nColumn );
138375  pCsr->iColFilter = iCol;
138376
138377  return SQLITE_OK;
138378}
138379
138380/*
138381** This function is called on a MultiSegReader that has been started using
138382** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
138383** have been made. Calling this function puts the MultiSegReader in such
138384** a state that if the next two calls are:
138385**
138386**   sqlite3Fts3SegReaderStart()
138387**   sqlite3Fts3SegReaderStep()
138388**
138389** then the entire doclist for the term is available in
138390** MultiSegReader.aDoclist/nDoclist.
138391*/
138392SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
138393  int i;                          /* Used to iterate through segment-readers */
138394
138395  assert( pCsr->zTerm==0 );
138396  assert( pCsr->nTerm==0 );
138397  assert( pCsr->aDoclist==0 );
138398  assert( pCsr->nDoclist==0 );
138399
138400  pCsr->nAdvance = 0;
138401  pCsr->bRestart = 1;
138402  for(i=0; i<pCsr->nSegment; i++){
138403    pCsr->apSegment[i]->pOffsetList = 0;
138404    pCsr->apSegment[i]->nOffsetList = 0;
138405    pCsr->apSegment[i]->iDocid = 0;
138406  }
138407
138408  return SQLITE_OK;
138409}
138410
138411
138412SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
138413  Fts3Table *p,                   /* Virtual table handle */
138414  Fts3MultiSegReader *pCsr        /* Cursor object */
138415){
138416  int rc = SQLITE_OK;
138417
138418  int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
138419  int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
138420  int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
138421  int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
138422  int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
138423  int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
138424
138425  Fts3SegReader **apSegment = pCsr->apSegment;
138426  int nSegment = pCsr->nSegment;
138427  Fts3SegFilter *pFilter = pCsr->pFilter;
138428  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
138429    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
138430  );
138431
138432  if( pCsr->nSegment==0 ) return SQLITE_OK;
138433
138434  do {
138435    int nMerge;
138436    int i;
138437
138438    /* Advance the first pCsr->nAdvance entries in the apSegment[] array
138439    ** forward. Then sort the list in order of current term again.
138440    */
138441    for(i=0; i<pCsr->nAdvance; i++){
138442      Fts3SegReader *pSeg = apSegment[i];
138443      if( pSeg->bLookup ){
138444        fts3SegReaderSetEof(pSeg);
138445      }else{
138446        rc = fts3SegReaderNext(p, pSeg, 0);
138447      }
138448      if( rc!=SQLITE_OK ) return rc;
138449    }
138450    fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
138451    pCsr->nAdvance = 0;
138452
138453    /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
138454    assert( rc==SQLITE_OK );
138455    if( apSegment[0]->aNode==0 ) break;
138456
138457    pCsr->nTerm = apSegment[0]->nTerm;
138458    pCsr->zTerm = apSegment[0]->zTerm;
138459
138460    /* If this is a prefix-search, and if the term that apSegment[0] points
138461    ** to does not share a suffix with pFilter->zTerm/nTerm, then all
138462    ** required callbacks have been made. In this case exit early.
138463    **
138464    ** Similarly, if this is a search for an exact match, and the first term
138465    ** of segment apSegment[0] is not a match, exit early.
138466    */
138467    if( pFilter->zTerm && !isScan ){
138468      if( pCsr->nTerm<pFilter->nTerm
138469       || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
138470       || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
138471      ){
138472        break;
138473      }
138474    }
138475
138476    nMerge = 1;
138477    while( nMerge<nSegment
138478        && apSegment[nMerge]->aNode
138479        && apSegment[nMerge]->nTerm==pCsr->nTerm
138480        && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
138481    ){
138482      nMerge++;
138483    }
138484
138485    assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
138486    if( nMerge==1
138487     && !isIgnoreEmpty
138488     && !isFirst
138489     && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
138490    ){
138491      pCsr->nDoclist = apSegment[0]->nDoclist;
138492      if( fts3SegReaderIsPending(apSegment[0]) ){
138493        rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
138494        pCsr->aDoclist = pCsr->aBuffer;
138495      }else{
138496        pCsr->aDoclist = apSegment[0]->aDoclist;
138497      }
138498      if( rc==SQLITE_OK ) rc = SQLITE_ROW;
138499    }else{
138500      int nDoclist = 0;           /* Size of doclist */
138501      sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
138502
138503      /* The current term of the first nMerge entries in the array
138504      ** of Fts3SegReader objects is the same. The doclists must be merged
138505      ** and a single term returned with the merged doclist.
138506      */
138507      for(i=0; i<nMerge; i++){
138508        fts3SegReaderFirstDocid(p, apSegment[i]);
138509      }
138510      fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
138511      while( apSegment[0]->pOffsetList ){
138512        int j;                    /* Number of segments that share a docid */
138513        char *pList = 0;
138514        int nList = 0;
138515        int nByte;
138516        sqlite3_int64 iDocid = apSegment[0]->iDocid;
138517        fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
138518        j = 1;
138519        while( j<nMerge
138520            && apSegment[j]->pOffsetList
138521            && apSegment[j]->iDocid==iDocid
138522        ){
138523          fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
138524          j++;
138525        }
138526
138527        if( isColFilter ){
138528          fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
138529        }
138530
138531        if( !isIgnoreEmpty || nList>0 ){
138532
138533          /* Calculate the 'docid' delta value to write into the merged
138534          ** doclist. */
138535          sqlite3_int64 iDelta;
138536          if( p->bDescIdx && nDoclist>0 ){
138537            iDelta = iPrev - iDocid;
138538          }else{
138539            iDelta = iDocid - iPrev;
138540          }
138541          assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
138542          assert( nDoclist>0 || iDelta==iDocid );
138543
138544          nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
138545          if( nDoclist+nByte>pCsr->nBuffer ){
138546            char *aNew;
138547            pCsr->nBuffer = (nDoclist+nByte)*2;
138548            aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
138549            if( !aNew ){
138550              return SQLITE_NOMEM;
138551            }
138552            pCsr->aBuffer = aNew;
138553          }
138554
138555          if( isFirst ){
138556            char *a = &pCsr->aBuffer[nDoclist];
138557            int nWrite;
138558
138559            nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
138560            if( nWrite ){
138561              iPrev = iDocid;
138562              nDoclist += nWrite;
138563            }
138564          }else{
138565            nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
138566            iPrev = iDocid;
138567            if( isRequirePos ){
138568              memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
138569              nDoclist += nList;
138570              pCsr->aBuffer[nDoclist++] = '\0';
138571            }
138572          }
138573        }
138574
138575        fts3SegReaderSort(apSegment, nMerge, j, xCmp);
138576      }
138577      if( nDoclist>0 ){
138578        pCsr->aDoclist = pCsr->aBuffer;
138579        pCsr->nDoclist = nDoclist;
138580        rc = SQLITE_ROW;
138581      }
138582    }
138583    pCsr->nAdvance = nMerge;
138584  }while( rc==SQLITE_OK );
138585
138586  return rc;
138587}
138588
138589
138590SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
138591  Fts3MultiSegReader *pCsr       /* Cursor object */
138592){
138593  if( pCsr ){
138594    int i;
138595    for(i=0; i<pCsr->nSegment; i++){
138596      sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
138597    }
138598    sqlite3_free(pCsr->apSegment);
138599    sqlite3_free(pCsr->aBuffer);
138600
138601    pCsr->nSegment = 0;
138602    pCsr->apSegment = 0;
138603    pCsr->aBuffer = 0;
138604  }
138605}
138606
138607/*
138608** Decode the "end_block" field, selected by column iCol of the SELECT
138609** statement passed as the first argument.
138610**
138611** The "end_block" field may contain either an integer, or a text field
138612** containing the text representation of two non-negative integers separated
138613** by one or more space (0x20) characters. In the first case, set *piEndBlock
138614** to the integer value and *pnByte to zero before returning. In the second,
138615** set *piEndBlock to the first value and *pnByte to the second.
138616*/
138617static void fts3ReadEndBlockField(
138618  sqlite3_stmt *pStmt,
138619  int iCol,
138620  i64 *piEndBlock,
138621  i64 *pnByte
138622){
138623  const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
138624  if( zText ){
138625    int i;
138626    int iMul = 1;
138627    i64 iVal = 0;
138628    for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
138629      iVal = iVal*10 + (zText[i] - '0');
138630    }
138631    *piEndBlock = iVal;
138632    while( zText[i]==' ' ) i++;
138633    iVal = 0;
138634    if( zText[i]=='-' ){
138635      i++;
138636      iMul = -1;
138637    }
138638    for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
138639      iVal = iVal*10 + (zText[i] - '0');
138640    }
138641    *pnByte = (iVal * (i64)iMul);
138642  }
138643}
138644
138645
138646/*
138647** A segment of size nByte bytes has just been written to absolute level
138648** iAbsLevel. Promote any segments that should be promoted as a result.
138649*/
138650static int fts3PromoteSegments(
138651  Fts3Table *p,                   /* FTS table handle */
138652  sqlite3_int64 iAbsLevel,        /* Absolute level just updated */
138653  sqlite3_int64 nByte             /* Size of new segment at iAbsLevel */
138654){
138655  int rc = SQLITE_OK;
138656  sqlite3_stmt *pRange;
138657
138658  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
138659
138660  if( rc==SQLITE_OK ){
138661    int bOk = 0;
138662    i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
138663    i64 nLimit = (nByte*3)/2;
138664
138665    /* Loop through all entries in the %_segdir table corresponding to
138666    ** segments in this index on levels greater than iAbsLevel. If there is
138667    ** at least one such segment, and it is possible to determine that all
138668    ** such segments are smaller than nLimit bytes in size, they will be
138669    ** promoted to level iAbsLevel.  */
138670    sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
138671    sqlite3_bind_int64(pRange, 2, iLast);
138672    while( SQLITE_ROW==sqlite3_step(pRange) ){
138673      i64 nSize = 0, dummy;
138674      fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
138675      if( nSize<=0 || nSize>nLimit ){
138676        /* If nSize==0, then the %_segdir.end_block field does not not
138677        ** contain a size value. This happens if it was written by an
138678        ** old version of FTS. In this case it is not possible to determine
138679        ** the size of the segment, and so segment promotion does not
138680        ** take place.  */
138681        bOk = 0;
138682        break;
138683      }
138684      bOk = 1;
138685    }
138686    rc = sqlite3_reset(pRange);
138687
138688    if( bOk ){
138689      int iIdx = 0;
138690      sqlite3_stmt *pUpdate1;
138691      sqlite3_stmt *pUpdate2;
138692
138693      if( rc==SQLITE_OK ){
138694        rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
138695      }
138696      if( rc==SQLITE_OK ){
138697        rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
138698      }
138699
138700      if( rc==SQLITE_OK ){
138701
138702        /* Loop through all %_segdir entries for segments in this index with
138703        ** levels equal to or greater than iAbsLevel. As each entry is visited,
138704        ** updated it to set (level = -1) and (idx = N), where N is 0 for the
138705        ** oldest segment in the range, 1 for the next oldest, and so on.
138706        **
138707        ** In other words, move all segments being promoted to level -1,
138708        ** setting the "idx" fields as appropriate to keep them in the same
138709        ** order. The contents of level -1 (which is never used, except
138710        ** transiently here), will be moved back to level iAbsLevel below.  */
138711        sqlite3_bind_int64(pRange, 1, iAbsLevel);
138712        while( SQLITE_ROW==sqlite3_step(pRange) ){
138713          sqlite3_bind_int(pUpdate1, 1, iIdx++);
138714          sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
138715          sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
138716          sqlite3_step(pUpdate1);
138717          rc = sqlite3_reset(pUpdate1);
138718          if( rc!=SQLITE_OK ){
138719            sqlite3_reset(pRange);
138720            break;
138721          }
138722        }
138723      }
138724      if( rc==SQLITE_OK ){
138725        rc = sqlite3_reset(pRange);
138726      }
138727
138728      /* Move level -1 to level iAbsLevel */
138729      if( rc==SQLITE_OK ){
138730        sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
138731        sqlite3_step(pUpdate2);
138732        rc = sqlite3_reset(pUpdate2);
138733      }
138734    }
138735  }
138736
138737
138738  return rc;
138739}
138740
138741/*
138742** Merge all level iLevel segments in the database into a single
138743** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
138744** single segment with a level equal to the numerically largest level
138745** currently present in the database.
138746**
138747** If this function is called with iLevel<0, but there is only one
138748** segment in the database, SQLITE_DONE is returned immediately.
138749** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
138750** an SQLite error code is returned.
138751*/
138752static int fts3SegmentMerge(
138753  Fts3Table *p,
138754  int iLangid,                    /* Language id to merge */
138755  int iIndex,                     /* Index in p->aIndex[] to merge */
138756  int iLevel                      /* Level to merge */
138757){
138758  int rc;                         /* Return code */
138759  int iIdx = 0;                   /* Index of new segment */
138760  sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
138761  SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
138762  Fts3SegFilter filter;           /* Segment term filter condition */
138763  Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
138764  int bIgnoreEmpty = 0;           /* True to ignore empty segments */
138765  i64 iMaxLevel = 0;              /* Max level number for this index/langid */
138766
138767  assert( iLevel==FTS3_SEGCURSOR_ALL
138768       || iLevel==FTS3_SEGCURSOR_PENDING
138769       || iLevel>=0
138770  );
138771  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
138772  assert( iIndex>=0 && iIndex<p->nIndex );
138773
138774  rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
138775  if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
138776
138777  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
138778    rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
138779    if( rc!=SQLITE_OK ) goto finished;
138780  }
138781
138782  if( iLevel==FTS3_SEGCURSOR_ALL ){
138783    /* This call is to merge all segments in the database to a single
138784    ** segment. The level of the new segment is equal to the numerically
138785    ** greatest segment level currently present in the database for this
138786    ** index. The idx of the new segment is always 0.  */
138787    if( csr.nSegment==1 ){
138788      rc = SQLITE_DONE;
138789      goto finished;
138790    }
138791    iNewLevel = iMaxLevel;
138792    bIgnoreEmpty = 1;
138793
138794  }else{
138795    /* This call is to merge all segments at level iLevel. find the next
138796    ** available segment index at level iLevel+1. The call to
138797    ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
138798    ** a single iLevel+2 segment if necessary.  */
138799    assert( FTS3_SEGCURSOR_PENDING==-1 );
138800    iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
138801    rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
138802    bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
138803  }
138804  if( rc!=SQLITE_OK ) goto finished;
138805
138806  assert( csr.nSegment>0 );
138807  assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
138808  assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
138809
138810  memset(&filter, 0, sizeof(Fts3SegFilter));
138811  filter.flags = FTS3_SEGMENT_REQUIRE_POS;
138812  filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
138813
138814  rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
138815  while( SQLITE_OK==rc ){
138816    rc = sqlite3Fts3SegReaderStep(p, &csr);
138817    if( rc!=SQLITE_ROW ) break;
138818    rc = fts3SegWriterAdd(p, &pWriter, 1,
138819        csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
138820  }
138821  if( rc!=SQLITE_OK ) goto finished;
138822  assert( pWriter || bIgnoreEmpty );
138823
138824  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
138825    rc = fts3DeleteSegdir(
138826        p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
138827    );
138828    if( rc!=SQLITE_OK ) goto finished;
138829  }
138830  if( pWriter ){
138831    rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
138832    if( rc==SQLITE_OK ){
138833      if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
138834        rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
138835      }
138836    }
138837  }
138838
138839 finished:
138840  fts3SegWriterFree(pWriter);
138841  sqlite3Fts3SegReaderFinish(&csr);
138842  return rc;
138843}
138844
138845
138846/*
138847** Flush the contents of pendingTerms to level 0 segments.
138848*/
138849SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
138850  int rc = SQLITE_OK;
138851  int i;
138852
138853  for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
138854    rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
138855    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
138856  }
138857  sqlite3Fts3PendingTermsClear(p);
138858
138859  /* Determine the auto-incr-merge setting if unknown.  If enabled,
138860  ** estimate the number of leaf blocks of content to be written
138861  */
138862  if( rc==SQLITE_OK && p->bHasStat
138863   && p->nAutoincrmerge==0xff && p->nLeafAdd>0
138864  ){
138865    sqlite3_stmt *pStmt = 0;
138866    rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
138867    if( rc==SQLITE_OK ){
138868      sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
138869      rc = sqlite3_step(pStmt);
138870      if( rc==SQLITE_ROW ){
138871        p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
138872        if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
138873      }else if( rc==SQLITE_DONE ){
138874        p->nAutoincrmerge = 0;
138875      }
138876      rc = sqlite3_reset(pStmt);
138877    }
138878  }
138879  return rc;
138880}
138881
138882/*
138883** Encode N integers as varints into a blob.
138884*/
138885static void fts3EncodeIntArray(
138886  int N,             /* The number of integers to encode */
138887  u32 *a,            /* The integer values */
138888  char *zBuf,        /* Write the BLOB here */
138889  int *pNBuf         /* Write number of bytes if zBuf[] used here */
138890){
138891  int i, j;
138892  for(i=j=0; i<N; i++){
138893    j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
138894  }
138895  *pNBuf = j;
138896}
138897
138898/*
138899** Decode a blob of varints into N integers
138900*/
138901static void fts3DecodeIntArray(
138902  int N,             /* The number of integers to decode */
138903  u32 *a,            /* Write the integer values */
138904  const char *zBuf,  /* The BLOB containing the varints */
138905  int nBuf           /* size of the BLOB */
138906){
138907  int i, j;
138908  UNUSED_PARAMETER(nBuf);
138909  for(i=j=0; i<N; i++){
138910    sqlite3_int64 x;
138911    j += sqlite3Fts3GetVarint(&zBuf[j], &x);
138912    assert(j<=nBuf);
138913    a[i] = (u32)(x & 0xffffffff);
138914  }
138915}
138916
138917/*
138918** Insert the sizes (in tokens) for each column of the document
138919** with docid equal to p->iPrevDocid.  The sizes are encoded as
138920** a blob of varints.
138921*/
138922static void fts3InsertDocsize(
138923  int *pRC,                       /* Result code */
138924  Fts3Table *p,                   /* Table into which to insert */
138925  u32 *aSz                        /* Sizes of each column, in tokens */
138926){
138927  char *pBlob;             /* The BLOB encoding of the document size */
138928  int nBlob;               /* Number of bytes in the BLOB */
138929  sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
138930  int rc;                  /* Result code from subfunctions */
138931
138932  if( *pRC ) return;
138933  pBlob = sqlite3_malloc( 10*p->nColumn );
138934  if( pBlob==0 ){
138935    *pRC = SQLITE_NOMEM;
138936    return;
138937  }
138938  fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
138939  rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
138940  if( rc ){
138941    sqlite3_free(pBlob);
138942    *pRC = rc;
138943    return;
138944  }
138945  sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
138946  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
138947  sqlite3_step(pStmt);
138948  *pRC = sqlite3_reset(pStmt);
138949}
138950
138951/*
138952** Record 0 of the %_stat table contains a blob consisting of N varints,
138953** where N is the number of user defined columns in the fts3 table plus
138954** two. If nCol is the number of user defined columns, then values of the
138955** varints are set as follows:
138956**
138957**   Varint 0:       Total number of rows in the table.
138958**
138959**   Varint 1..nCol: For each column, the total number of tokens stored in
138960**                   the column for all rows of the table.
138961**
138962**   Varint 1+nCol:  The total size, in bytes, of all text values in all
138963**                   columns of all rows of the table.
138964**
138965*/
138966static void fts3UpdateDocTotals(
138967  int *pRC,                       /* The result code */
138968  Fts3Table *p,                   /* Table being updated */
138969  u32 *aSzIns,                    /* Size increases */
138970  u32 *aSzDel,                    /* Size decreases */
138971  int nChng                       /* Change in the number of documents */
138972){
138973  char *pBlob;             /* Storage for BLOB written into %_stat */
138974  int nBlob;               /* Size of BLOB written into %_stat */
138975  u32 *a;                  /* Array of integers that becomes the BLOB */
138976  sqlite3_stmt *pStmt;     /* Statement for reading and writing */
138977  int i;                   /* Loop counter */
138978  int rc;                  /* Result code from subfunctions */
138979
138980  const int nStat = p->nColumn+2;
138981
138982  if( *pRC ) return;
138983  a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
138984  if( a==0 ){
138985    *pRC = SQLITE_NOMEM;
138986    return;
138987  }
138988  pBlob = (char*)&a[nStat];
138989  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
138990  if( rc ){
138991    sqlite3_free(a);
138992    *pRC = rc;
138993    return;
138994  }
138995  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
138996  if( sqlite3_step(pStmt)==SQLITE_ROW ){
138997    fts3DecodeIntArray(nStat, a,
138998         sqlite3_column_blob(pStmt, 0),
138999         sqlite3_column_bytes(pStmt, 0));
139000  }else{
139001    memset(a, 0, sizeof(u32)*(nStat) );
139002  }
139003  rc = sqlite3_reset(pStmt);
139004  if( rc!=SQLITE_OK ){
139005    sqlite3_free(a);
139006    *pRC = rc;
139007    return;
139008  }
139009  if( nChng<0 && a[0]<(u32)(-nChng) ){
139010    a[0] = 0;
139011  }else{
139012    a[0] += nChng;
139013  }
139014  for(i=0; i<p->nColumn+1; i++){
139015    u32 x = a[i+1];
139016    if( x+aSzIns[i] < aSzDel[i] ){
139017      x = 0;
139018    }else{
139019      x = x + aSzIns[i] - aSzDel[i];
139020    }
139021    a[i+1] = x;
139022  }
139023  fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
139024  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
139025  if( rc ){
139026    sqlite3_free(a);
139027    *pRC = rc;
139028    return;
139029  }
139030  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
139031  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
139032  sqlite3_step(pStmt);
139033  *pRC = sqlite3_reset(pStmt);
139034  sqlite3_free(a);
139035}
139036
139037/*
139038** Merge the entire database so that there is one segment for each
139039** iIndex/iLangid combination.
139040*/
139041static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
139042  int bSeenDone = 0;
139043  int rc;
139044  sqlite3_stmt *pAllLangid = 0;
139045
139046  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
139047  if( rc==SQLITE_OK ){
139048    int rc2;
139049    sqlite3_bind_int(pAllLangid, 1, p->nIndex);
139050    while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
139051      int i;
139052      int iLangid = sqlite3_column_int(pAllLangid, 0);
139053      for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
139054        rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
139055        if( rc==SQLITE_DONE ){
139056          bSeenDone = 1;
139057          rc = SQLITE_OK;
139058        }
139059      }
139060    }
139061    rc2 = sqlite3_reset(pAllLangid);
139062    if( rc==SQLITE_OK ) rc = rc2;
139063  }
139064
139065  sqlite3Fts3SegmentsClose(p);
139066  sqlite3Fts3PendingTermsClear(p);
139067
139068  return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
139069}
139070
139071/*
139072** This function is called when the user executes the following statement:
139073**
139074**     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
139075**
139076** The entire FTS index is discarded and rebuilt. If the table is one
139077** created using the content=xxx option, then the new index is based on
139078** the current contents of the xxx table. Otherwise, it is rebuilt based
139079** on the contents of the %_content table.
139080*/
139081static int fts3DoRebuild(Fts3Table *p){
139082  int rc;                         /* Return Code */
139083
139084  rc = fts3DeleteAll(p, 0);
139085  if( rc==SQLITE_OK ){
139086    u32 *aSz = 0;
139087    u32 *aSzIns = 0;
139088    u32 *aSzDel = 0;
139089    sqlite3_stmt *pStmt = 0;
139090    int nEntry = 0;
139091
139092    /* Compose and prepare an SQL statement to loop through the content table */
139093    char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
139094    if( !zSql ){
139095      rc = SQLITE_NOMEM;
139096    }else{
139097      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
139098      sqlite3_free(zSql);
139099    }
139100
139101    if( rc==SQLITE_OK ){
139102      int nByte = sizeof(u32) * (p->nColumn+1)*3;
139103      aSz = (u32 *)sqlite3_malloc(nByte);
139104      if( aSz==0 ){
139105        rc = SQLITE_NOMEM;
139106      }else{
139107        memset(aSz, 0, nByte);
139108        aSzIns = &aSz[p->nColumn+1];
139109        aSzDel = &aSzIns[p->nColumn+1];
139110      }
139111    }
139112
139113    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
139114      int iCol;
139115      int iLangid = langidFromSelect(p, pStmt);
139116      rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
139117      memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
139118      for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
139119        if( p->abNotindexed[iCol]==0 ){
139120          const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
139121          rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
139122          aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
139123        }
139124      }
139125      if( p->bHasDocsize ){
139126        fts3InsertDocsize(&rc, p, aSz);
139127      }
139128      if( rc!=SQLITE_OK ){
139129        sqlite3_finalize(pStmt);
139130        pStmt = 0;
139131      }else{
139132        nEntry++;
139133        for(iCol=0; iCol<=p->nColumn; iCol++){
139134          aSzIns[iCol] += aSz[iCol];
139135        }
139136      }
139137    }
139138    if( p->bFts4 ){
139139      fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
139140    }
139141    sqlite3_free(aSz);
139142
139143    if( pStmt ){
139144      int rc2 = sqlite3_finalize(pStmt);
139145      if( rc==SQLITE_OK ){
139146        rc = rc2;
139147      }
139148    }
139149  }
139150
139151  return rc;
139152}
139153
139154
139155/*
139156** This function opens a cursor used to read the input data for an
139157** incremental merge operation. Specifically, it opens a cursor to scan
139158** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
139159** level iAbsLevel.
139160*/
139161static int fts3IncrmergeCsr(
139162  Fts3Table *p,                   /* FTS3 table handle */
139163  sqlite3_int64 iAbsLevel,        /* Absolute level to open */
139164  int nSeg,                       /* Number of segments to merge */
139165  Fts3MultiSegReader *pCsr        /* Cursor object to populate */
139166){
139167  int rc;                         /* Return Code */
139168  sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */
139169  int nByte;                      /* Bytes allocated at pCsr->apSegment[] */
139170
139171  /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
139172  memset(pCsr, 0, sizeof(*pCsr));
139173  nByte = sizeof(Fts3SegReader *) * nSeg;
139174  pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
139175
139176  if( pCsr->apSegment==0 ){
139177    rc = SQLITE_NOMEM;
139178  }else{
139179    memset(pCsr->apSegment, 0, nByte);
139180    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
139181  }
139182  if( rc==SQLITE_OK ){
139183    int i;
139184    int rc2;
139185    sqlite3_bind_int64(pStmt, 1, iAbsLevel);
139186    assert( pCsr->nSegment==0 );
139187    for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
139188      rc = sqlite3Fts3SegReaderNew(i, 0,
139189          sqlite3_column_int64(pStmt, 1),        /* segdir.start_block */
139190          sqlite3_column_int64(pStmt, 2),        /* segdir.leaves_end_block */
139191          sqlite3_column_int64(pStmt, 3),        /* segdir.end_block */
139192          sqlite3_column_blob(pStmt, 4),         /* segdir.root */
139193          sqlite3_column_bytes(pStmt, 4),        /* segdir.root */
139194          &pCsr->apSegment[i]
139195      );
139196      pCsr->nSegment++;
139197    }
139198    rc2 = sqlite3_reset(pStmt);
139199    if( rc==SQLITE_OK ) rc = rc2;
139200  }
139201
139202  return rc;
139203}
139204
139205typedef struct IncrmergeWriter IncrmergeWriter;
139206typedef struct NodeWriter NodeWriter;
139207typedef struct Blob Blob;
139208typedef struct NodeReader NodeReader;
139209
139210/*
139211** An instance of the following structure is used as a dynamic buffer
139212** to build up nodes or other blobs of data in.
139213**
139214** The function blobGrowBuffer() is used to extend the allocation.
139215*/
139216struct Blob {
139217  char *a;                        /* Pointer to allocation */
139218  int n;                          /* Number of valid bytes of data in a[] */
139219  int nAlloc;                     /* Allocated size of a[] (nAlloc>=n) */
139220};
139221
139222/*
139223** This structure is used to build up buffers containing segment b-tree
139224** nodes (blocks).
139225*/
139226struct NodeWriter {
139227  sqlite3_int64 iBlock;           /* Current block id */
139228  Blob key;                       /* Last key written to the current block */
139229  Blob block;                     /* Current block image */
139230};
139231
139232/*
139233** An object of this type contains the state required to create or append
139234** to an appendable b-tree segment.
139235*/
139236struct IncrmergeWriter {
139237  int nLeafEst;                   /* Space allocated for leaf blocks */
139238  int nWork;                      /* Number of leaf pages flushed */
139239  sqlite3_int64 iAbsLevel;        /* Absolute level of input segments */
139240  int iIdx;                       /* Index of *output* segment in iAbsLevel+1 */
139241  sqlite3_int64 iStart;           /* Block number of first allocated block */
139242  sqlite3_int64 iEnd;             /* Block number of last allocated block */
139243  sqlite3_int64 nLeafData;        /* Bytes of leaf page data so far */
139244  u8 bNoLeafData;                 /* If true, store 0 for segment size */
139245  NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
139246};
139247
139248/*
139249** An object of the following type is used to read data from a single
139250** FTS segment node. See the following functions:
139251**
139252**     nodeReaderInit()
139253**     nodeReaderNext()
139254**     nodeReaderRelease()
139255*/
139256struct NodeReader {
139257  const char *aNode;
139258  int nNode;
139259  int iOff;                       /* Current offset within aNode[] */
139260
139261  /* Output variables. Containing the current node entry. */
139262  sqlite3_int64 iChild;           /* Pointer to child node */
139263  Blob term;                      /* Current term */
139264  const char *aDoclist;           /* Pointer to doclist */
139265  int nDoclist;                   /* Size of doclist in bytes */
139266};
139267
139268/*
139269** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
139270** Otherwise, if the allocation at pBlob->a is not already at least nMin
139271** bytes in size, extend (realloc) it to be so.
139272**
139273** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
139274** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
139275** to reflect the new size of the pBlob->a[] buffer.
139276*/
139277static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
139278  if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
139279    int nAlloc = nMin;
139280    char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
139281    if( a ){
139282      pBlob->nAlloc = nAlloc;
139283      pBlob->a = a;
139284    }else{
139285      *pRc = SQLITE_NOMEM;
139286    }
139287  }
139288}
139289
139290/*
139291** Attempt to advance the node-reader object passed as the first argument to
139292** the next entry on the node.
139293**
139294** Return an error code if an error occurs (SQLITE_NOMEM is possible).
139295** Otherwise return SQLITE_OK. If there is no next entry on the node
139296** (e.g. because the current entry is the last) set NodeReader->aNode to
139297** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
139298** variables for the new entry.
139299*/
139300static int nodeReaderNext(NodeReader *p){
139301  int bFirst = (p->term.n==0);    /* True for first term on the node */
139302  int nPrefix = 0;                /* Bytes to copy from previous term */
139303  int nSuffix = 0;                /* Bytes to append to the prefix */
139304  int rc = SQLITE_OK;             /* Return code */
139305
139306  assert( p->aNode );
139307  if( p->iChild && bFirst==0 ) p->iChild++;
139308  if( p->iOff>=p->nNode ){
139309    /* EOF */
139310    p->aNode = 0;
139311  }else{
139312    if( bFirst==0 ){
139313      p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
139314    }
139315    p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
139316
139317    blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
139318    if( rc==SQLITE_OK ){
139319      memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
139320      p->term.n = nPrefix+nSuffix;
139321      p->iOff += nSuffix;
139322      if( p->iChild==0 ){
139323        p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
139324        p->aDoclist = &p->aNode[p->iOff];
139325        p->iOff += p->nDoclist;
139326      }
139327    }
139328  }
139329
139330  assert( p->iOff<=p->nNode );
139331
139332  return rc;
139333}
139334
139335/*
139336** Release all dynamic resources held by node-reader object *p.
139337*/
139338static void nodeReaderRelease(NodeReader *p){
139339  sqlite3_free(p->term.a);
139340}
139341
139342/*
139343** Initialize a node-reader object to read the node in buffer aNode/nNode.
139344**
139345** If successful, SQLITE_OK is returned and the NodeReader object set to
139346** point to the first entry on the node (if any). Otherwise, an SQLite
139347** error code is returned.
139348*/
139349static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
139350  memset(p, 0, sizeof(NodeReader));
139351  p->aNode = aNode;
139352  p->nNode = nNode;
139353
139354  /* Figure out if this is a leaf or an internal node. */
139355  if( p->aNode[0] ){
139356    /* An internal node. */
139357    p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
139358  }else{
139359    p->iOff = 1;
139360  }
139361
139362  return nodeReaderNext(p);
139363}
139364
139365/*
139366** This function is called while writing an FTS segment each time a leaf o
139367** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
139368** to be greater than the largest key on the node just written, but smaller
139369** than or equal to the first key that will be written to the next leaf
139370** node.
139371**
139372** The block id of the leaf node just written to disk may be found in
139373** (pWriter->aNodeWriter[0].iBlock) when this function is called.
139374*/
139375static int fts3IncrmergePush(
139376  Fts3Table *p,                   /* Fts3 table handle */
139377  IncrmergeWriter *pWriter,       /* Writer object */
139378  const char *zTerm,              /* Term to write to internal node */
139379  int nTerm                       /* Bytes at zTerm */
139380){
139381  sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
139382  int iLayer;
139383
139384  assert( nTerm>0 );
139385  for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
139386    sqlite3_int64 iNextPtr = 0;
139387    NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
139388    int rc = SQLITE_OK;
139389    int nPrefix;
139390    int nSuffix;
139391    int nSpace;
139392
139393    /* Figure out how much space the key will consume if it is written to
139394    ** the current node of layer iLayer. Due to the prefix compression,
139395    ** the space required changes depending on which node the key is to
139396    ** be added to.  */
139397    nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
139398    nSuffix = nTerm - nPrefix;
139399    nSpace  = sqlite3Fts3VarintLen(nPrefix);
139400    nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
139401
139402    if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
139403      /* If the current node of layer iLayer contains zero keys, or if adding
139404      ** the key to it will not cause it to grow to larger than nNodeSize
139405      ** bytes in size, write the key here.  */
139406
139407      Blob *pBlk = &pNode->block;
139408      if( pBlk->n==0 ){
139409        blobGrowBuffer(pBlk, p->nNodeSize, &rc);
139410        if( rc==SQLITE_OK ){
139411          pBlk->a[0] = (char)iLayer;
139412          pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
139413        }
139414      }
139415      blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
139416      blobGrowBuffer(&pNode->key, nTerm, &rc);
139417
139418      if( rc==SQLITE_OK ){
139419        if( pNode->key.n ){
139420          pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
139421        }
139422        pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
139423        memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
139424        pBlk->n += nSuffix;
139425
139426        memcpy(pNode->key.a, zTerm, nTerm);
139427        pNode->key.n = nTerm;
139428      }
139429    }else{
139430      /* Otherwise, flush the current node of layer iLayer to disk.
139431      ** Then allocate a new, empty sibling node. The key will be written
139432      ** into the parent of this node. */
139433      rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
139434
139435      assert( pNode->block.nAlloc>=p->nNodeSize );
139436      pNode->block.a[0] = (char)iLayer;
139437      pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
139438
139439      iNextPtr = pNode->iBlock;
139440      pNode->iBlock++;
139441      pNode->key.n = 0;
139442    }
139443
139444    if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
139445    iPtr = iNextPtr;
139446  }
139447
139448  assert( 0 );
139449  return 0;
139450}
139451
139452/*
139453** Append a term and (optionally) doclist to the FTS segment node currently
139454** stored in blob *pNode. The node need not contain any terms, but the
139455** header must be written before this function is called.
139456**
139457** A node header is a single 0x00 byte for a leaf node, or a height varint
139458** followed by the left-hand-child varint for an internal node.
139459**
139460** The term to be appended is passed via arguments zTerm/nTerm. For a
139461** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
139462** node, both aDoclist and nDoclist must be passed 0.
139463**
139464** If the size of the value in blob pPrev is zero, then this is the first
139465** term written to the node. Otherwise, pPrev contains a copy of the
139466** previous term. Before this function returns, it is updated to contain a
139467** copy of zTerm/nTerm.
139468**
139469** It is assumed that the buffer associated with pNode is already large
139470** enough to accommodate the new entry. The buffer associated with pPrev
139471** is extended by this function if requrired.
139472**
139473** If an error (i.e. OOM condition) occurs, an SQLite error code is
139474** returned. Otherwise, SQLITE_OK.
139475*/
139476static int fts3AppendToNode(
139477  Blob *pNode,                    /* Current node image to append to */
139478  Blob *pPrev,                    /* Buffer containing previous term written */
139479  const char *zTerm,              /* New term to write */
139480  int nTerm,                      /* Size of zTerm in bytes */
139481  const char *aDoclist,           /* Doclist (or NULL) to write */
139482  int nDoclist                    /* Size of aDoclist in bytes */
139483){
139484  int rc = SQLITE_OK;             /* Return code */
139485  int bFirst = (pPrev->n==0);     /* True if this is the first term written */
139486  int nPrefix;                    /* Size of term prefix in bytes */
139487  int nSuffix;                    /* Size of term suffix in bytes */
139488
139489  /* Node must have already been started. There must be a doclist for a
139490  ** leaf node, and there must not be a doclist for an internal node.  */
139491  assert( pNode->n>0 );
139492  assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
139493
139494  blobGrowBuffer(pPrev, nTerm, &rc);
139495  if( rc!=SQLITE_OK ) return rc;
139496
139497  nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
139498  nSuffix = nTerm - nPrefix;
139499  memcpy(pPrev->a, zTerm, nTerm);
139500  pPrev->n = nTerm;
139501
139502  if( bFirst==0 ){
139503    pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
139504  }
139505  pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
139506  memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
139507  pNode->n += nSuffix;
139508
139509  if( aDoclist ){
139510    pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
139511    memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
139512    pNode->n += nDoclist;
139513  }
139514
139515  assert( pNode->n<=pNode->nAlloc );
139516
139517  return SQLITE_OK;
139518}
139519
139520/*
139521** Append the current term and doclist pointed to by cursor pCsr to the
139522** appendable b-tree segment opened for writing by pWriter.
139523**
139524** Return SQLITE_OK if successful, or an SQLite error code otherwise.
139525*/
139526static int fts3IncrmergeAppend(
139527  Fts3Table *p,                   /* Fts3 table handle */
139528  IncrmergeWriter *pWriter,       /* Writer object */
139529  Fts3MultiSegReader *pCsr        /* Cursor containing term and doclist */
139530){
139531  const char *zTerm = pCsr->zTerm;
139532  int nTerm = pCsr->nTerm;
139533  const char *aDoclist = pCsr->aDoclist;
139534  int nDoclist = pCsr->nDoclist;
139535  int rc = SQLITE_OK;           /* Return code */
139536  int nSpace;                   /* Total space in bytes required on leaf */
139537  int nPrefix;                  /* Size of prefix shared with previous term */
139538  int nSuffix;                  /* Size of suffix (nTerm - nPrefix) */
139539  NodeWriter *pLeaf;            /* Object used to write leaf nodes */
139540
139541  pLeaf = &pWriter->aNodeWriter[0];
139542  nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
139543  nSuffix = nTerm - nPrefix;
139544
139545  nSpace  = sqlite3Fts3VarintLen(nPrefix);
139546  nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
139547  nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
139548
139549  /* If the current block is not empty, and if adding this term/doclist
139550  ** to the current block would make it larger than Fts3Table.nNodeSize
139551  ** bytes, write this block out to the database. */
139552  if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
139553    rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
139554    pWriter->nWork++;
139555
139556    /* Add the current term to the parent node. The term added to the
139557    ** parent must:
139558    **
139559    **   a) be greater than the largest term on the leaf node just written
139560    **      to the database (still available in pLeaf->key), and
139561    **
139562    **   b) be less than or equal to the term about to be added to the new
139563    **      leaf node (zTerm/nTerm).
139564    **
139565    ** In other words, it must be the prefix of zTerm 1 byte longer than
139566    ** the common prefix (if any) of zTerm and pWriter->zTerm.
139567    */
139568    if( rc==SQLITE_OK ){
139569      rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
139570    }
139571
139572    /* Advance to the next output block */
139573    pLeaf->iBlock++;
139574    pLeaf->key.n = 0;
139575    pLeaf->block.n = 0;
139576
139577    nSuffix = nTerm;
139578    nSpace  = 1;
139579    nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
139580    nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
139581  }
139582
139583  pWriter->nLeafData += nSpace;
139584  blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
139585  if( rc==SQLITE_OK ){
139586    if( pLeaf->block.n==0 ){
139587      pLeaf->block.n = 1;
139588      pLeaf->block.a[0] = '\0';
139589    }
139590    rc = fts3AppendToNode(
139591        &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
139592    );
139593  }
139594
139595  return rc;
139596}
139597
139598/*
139599** This function is called to release all dynamic resources held by the
139600** merge-writer object pWriter, and if no error has occurred, to flush
139601** all outstanding node buffers held by pWriter to disk.
139602**
139603** If *pRc is not SQLITE_OK when this function is called, then no attempt
139604** is made to write any data to disk. Instead, this function serves only
139605** to release outstanding resources.
139606**
139607** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
139608** flushing buffers to disk, *pRc is set to an SQLite error code before
139609** returning.
139610*/
139611static void fts3IncrmergeRelease(
139612  Fts3Table *p,                   /* FTS3 table handle */
139613  IncrmergeWriter *pWriter,       /* Merge-writer object */
139614  int *pRc                        /* IN/OUT: Error code */
139615){
139616  int i;                          /* Used to iterate through non-root layers */
139617  int iRoot;                      /* Index of root in pWriter->aNodeWriter */
139618  NodeWriter *pRoot;              /* NodeWriter for root node */
139619  int rc = *pRc;                  /* Error code */
139620
139621  /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
139622  ** root node. If the segment fits entirely on a single leaf node, iRoot
139623  ** will be set to 0. If the root node is the parent of the leaves, iRoot
139624  ** will be 1. And so on.  */
139625  for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
139626    NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
139627    if( pNode->block.n>0 ) break;
139628    assert( *pRc || pNode->block.nAlloc==0 );
139629    assert( *pRc || pNode->key.nAlloc==0 );
139630    sqlite3_free(pNode->block.a);
139631    sqlite3_free(pNode->key.a);
139632  }
139633
139634  /* Empty output segment. This is a no-op. */
139635  if( iRoot<0 ) return;
139636
139637  /* The entire output segment fits on a single node. Normally, this means
139638  ** the node would be stored as a blob in the "root" column of the %_segdir
139639  ** table. However, this is not permitted in this case. The problem is that
139640  ** space has already been reserved in the %_segments table, and so the
139641  ** start_block and end_block fields of the %_segdir table must be populated.
139642  ** And, by design or by accident, released versions of FTS cannot handle
139643  ** segments that fit entirely on the root node with start_block!=0.
139644  **
139645  ** Instead, create a synthetic root node that contains nothing but a
139646  ** pointer to the single content node. So that the segment consists of a
139647  ** single leaf and a single interior (root) node.
139648  **
139649  ** Todo: Better might be to defer allocating space in the %_segments
139650  ** table until we are sure it is needed.
139651  */
139652  if( iRoot==0 ){
139653    Blob *pBlock = &pWriter->aNodeWriter[1].block;
139654    blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
139655    if( rc==SQLITE_OK ){
139656      pBlock->a[0] = 0x01;
139657      pBlock->n = 1 + sqlite3Fts3PutVarint(
139658          &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
139659      );
139660    }
139661    iRoot = 1;
139662  }
139663  pRoot = &pWriter->aNodeWriter[iRoot];
139664
139665  /* Flush all currently outstanding nodes to disk. */
139666  for(i=0; i<iRoot; i++){
139667    NodeWriter *pNode = &pWriter->aNodeWriter[i];
139668    if( pNode->block.n>0 && rc==SQLITE_OK ){
139669      rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
139670    }
139671    sqlite3_free(pNode->block.a);
139672    sqlite3_free(pNode->key.a);
139673  }
139674
139675  /* Write the %_segdir record. */
139676  if( rc==SQLITE_OK ){
139677    rc = fts3WriteSegdir(p,
139678        pWriter->iAbsLevel+1,               /* level */
139679        pWriter->iIdx,                      /* idx */
139680        pWriter->iStart,                    /* start_block */
139681        pWriter->aNodeWriter[0].iBlock,     /* leaves_end_block */
139682        pWriter->iEnd,                      /* end_block */
139683        (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0),   /* end_block */
139684        pRoot->block.a, pRoot->block.n      /* root */
139685    );
139686  }
139687  sqlite3_free(pRoot->block.a);
139688  sqlite3_free(pRoot->key.a);
139689
139690  *pRc = rc;
139691}
139692
139693/*
139694** Compare the term in buffer zLhs (size in bytes nLhs) with that in
139695** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
139696** the other, it is considered to be smaller than the other.
139697**
139698** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
139699** if it is greater.
139700*/
139701static int fts3TermCmp(
139702  const char *zLhs, int nLhs,     /* LHS of comparison */
139703  const char *zRhs, int nRhs      /* RHS of comparison */
139704){
139705  int nCmp = MIN(nLhs, nRhs);
139706  int res;
139707
139708  res = memcmp(zLhs, zRhs, nCmp);
139709  if( res==0 ) res = nLhs - nRhs;
139710
139711  return res;
139712}
139713
139714
139715/*
139716** Query to see if the entry in the %_segments table with blockid iEnd is
139717** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
139718** returning. Otherwise, set *pbRes to 0.
139719**
139720** Or, if an error occurs while querying the database, return an SQLite
139721** error code. The final value of *pbRes is undefined in this case.
139722**
139723** This is used to test if a segment is an "appendable" segment. If it
139724** is, then a NULL entry has been inserted into the %_segments table
139725** with blockid %_segdir.end_block.
139726*/
139727static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
139728  int bRes = 0;                   /* Result to set *pbRes to */
139729  sqlite3_stmt *pCheck = 0;       /* Statement to query database with */
139730  int rc;                         /* Return code */
139731
139732  rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
139733  if( rc==SQLITE_OK ){
139734    sqlite3_bind_int64(pCheck, 1, iEnd);
139735    if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
139736    rc = sqlite3_reset(pCheck);
139737  }
139738
139739  *pbRes = bRes;
139740  return rc;
139741}
139742
139743/*
139744** This function is called when initializing an incremental-merge operation.
139745** It checks if the existing segment with index value iIdx at absolute level
139746** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
139747** merge-writer object *pWriter is initialized to write to it.
139748**
139749** An existing segment can be appended to by an incremental merge if:
139750**
139751**   * It was initially created as an appendable segment (with all required
139752**     space pre-allocated), and
139753**
139754**   * The first key read from the input (arguments zKey and nKey) is
139755**     greater than the largest key currently stored in the potential
139756**     output segment.
139757*/
139758static int fts3IncrmergeLoad(
139759  Fts3Table *p,                   /* Fts3 table handle */
139760  sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
139761  int iIdx,                       /* Index of candidate output segment */
139762  const char *zKey,               /* First key to write */
139763  int nKey,                       /* Number of bytes in nKey */
139764  IncrmergeWriter *pWriter        /* Populate this object */
139765){
139766  int rc;                         /* Return code */
139767  sqlite3_stmt *pSelect = 0;      /* SELECT to read %_segdir entry */
139768
139769  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
139770  if( rc==SQLITE_OK ){
139771    sqlite3_int64 iStart = 0;     /* Value of %_segdir.start_block */
139772    sqlite3_int64 iLeafEnd = 0;   /* Value of %_segdir.leaves_end_block */
139773    sqlite3_int64 iEnd = 0;       /* Value of %_segdir.end_block */
139774    const char *aRoot = 0;        /* Pointer to %_segdir.root buffer */
139775    int nRoot = 0;                /* Size of aRoot[] in bytes */
139776    int rc2;                      /* Return code from sqlite3_reset() */
139777    int bAppendable = 0;          /* Set to true if segment is appendable */
139778
139779    /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
139780    sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
139781    sqlite3_bind_int(pSelect, 2, iIdx);
139782    if( sqlite3_step(pSelect)==SQLITE_ROW ){
139783      iStart = sqlite3_column_int64(pSelect, 1);
139784      iLeafEnd = sqlite3_column_int64(pSelect, 2);
139785      fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
139786      if( pWriter->nLeafData<0 ){
139787        pWriter->nLeafData = pWriter->nLeafData * -1;
139788      }
139789      pWriter->bNoLeafData = (pWriter->nLeafData==0);
139790      nRoot = sqlite3_column_bytes(pSelect, 4);
139791      aRoot = sqlite3_column_blob(pSelect, 4);
139792    }else{
139793      return sqlite3_reset(pSelect);
139794    }
139795
139796    /* Check for the zero-length marker in the %_segments table */
139797    rc = fts3IsAppendable(p, iEnd, &bAppendable);
139798
139799    /* Check that zKey/nKey is larger than the largest key the candidate */
139800    if( rc==SQLITE_OK && bAppendable ){
139801      char *aLeaf = 0;
139802      int nLeaf = 0;
139803
139804      rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
139805      if( rc==SQLITE_OK ){
139806        NodeReader reader;
139807        for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
139808            rc==SQLITE_OK && reader.aNode;
139809            rc = nodeReaderNext(&reader)
139810        ){
139811          assert( reader.aNode );
139812        }
139813        if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
139814          bAppendable = 0;
139815        }
139816        nodeReaderRelease(&reader);
139817      }
139818      sqlite3_free(aLeaf);
139819    }
139820
139821    if( rc==SQLITE_OK && bAppendable ){
139822      /* It is possible to append to this segment. Set up the IncrmergeWriter
139823      ** object to do so.  */
139824      int i;
139825      int nHeight = (int)aRoot[0];
139826      NodeWriter *pNode;
139827
139828      pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
139829      pWriter->iStart = iStart;
139830      pWriter->iEnd = iEnd;
139831      pWriter->iAbsLevel = iAbsLevel;
139832      pWriter->iIdx = iIdx;
139833
139834      for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
139835        pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
139836      }
139837
139838      pNode = &pWriter->aNodeWriter[nHeight];
139839      pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
139840      blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
139841      if( rc==SQLITE_OK ){
139842        memcpy(pNode->block.a, aRoot, nRoot);
139843        pNode->block.n = nRoot;
139844      }
139845
139846      for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
139847        NodeReader reader;
139848        pNode = &pWriter->aNodeWriter[i];
139849
139850        rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
139851        while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
139852        blobGrowBuffer(&pNode->key, reader.term.n, &rc);
139853        if( rc==SQLITE_OK ){
139854          memcpy(pNode->key.a, reader.term.a, reader.term.n);
139855          pNode->key.n = reader.term.n;
139856          if( i>0 ){
139857            char *aBlock = 0;
139858            int nBlock = 0;
139859            pNode = &pWriter->aNodeWriter[i-1];
139860            pNode->iBlock = reader.iChild;
139861            rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
139862            blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
139863            if( rc==SQLITE_OK ){
139864              memcpy(pNode->block.a, aBlock, nBlock);
139865              pNode->block.n = nBlock;
139866            }
139867            sqlite3_free(aBlock);
139868          }
139869        }
139870        nodeReaderRelease(&reader);
139871      }
139872    }
139873
139874    rc2 = sqlite3_reset(pSelect);
139875    if( rc==SQLITE_OK ) rc = rc2;
139876  }
139877
139878  return rc;
139879}
139880
139881/*
139882** Determine the largest segment index value that exists within absolute
139883** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
139884** one before returning SQLITE_OK. Or, if there are no segments at all
139885** within level iAbsLevel, set *piIdx to zero.
139886**
139887** If an error occurs, return an SQLite error code. The final value of
139888** *piIdx is undefined in this case.
139889*/
139890static int fts3IncrmergeOutputIdx(
139891  Fts3Table *p,                   /* FTS Table handle */
139892  sqlite3_int64 iAbsLevel,        /* Absolute index of input segments */
139893  int *piIdx                      /* OUT: Next free index at iAbsLevel+1 */
139894){
139895  int rc;
139896  sqlite3_stmt *pOutputIdx = 0;   /* SQL used to find output index */
139897
139898  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
139899  if( rc==SQLITE_OK ){
139900    sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
139901    sqlite3_step(pOutputIdx);
139902    *piIdx = sqlite3_column_int(pOutputIdx, 0);
139903    rc = sqlite3_reset(pOutputIdx);
139904  }
139905
139906  return rc;
139907}
139908
139909/*
139910** Allocate an appendable output segment on absolute level iAbsLevel+1
139911** with idx value iIdx.
139912**
139913** In the %_segdir table, a segment is defined by the values in three
139914** columns:
139915**
139916**     start_block
139917**     leaves_end_block
139918**     end_block
139919**
139920** When an appendable segment is allocated, it is estimated that the
139921** maximum number of leaf blocks that may be required is the sum of the
139922** number of leaf blocks consumed by the input segments, plus the number
139923** of input segments, multiplied by two. This value is stored in stack
139924** variable nLeafEst.
139925**
139926** A total of 16*nLeafEst blocks are allocated when an appendable segment
139927** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
139928** array of leaf nodes starts at the first block allocated. The array
139929** of interior nodes that are parents of the leaf nodes start at block
139930** (start_block + (1 + end_block - start_block) / 16). And so on.
139931**
139932** In the actual code below, the value "16" is replaced with the
139933** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
139934*/
139935static int fts3IncrmergeWriter(
139936  Fts3Table *p,                   /* Fts3 table handle */
139937  sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
139938  int iIdx,                       /* Index of new output segment */
139939  Fts3MultiSegReader *pCsr,       /* Cursor that data will be read from */
139940  IncrmergeWriter *pWriter        /* Populate this object */
139941){
139942  int rc;                         /* Return Code */
139943  int i;                          /* Iterator variable */
139944  int nLeafEst = 0;               /* Blocks allocated for leaf nodes */
139945  sqlite3_stmt *pLeafEst = 0;     /* SQL used to determine nLeafEst */
139946  sqlite3_stmt *pFirstBlock = 0;  /* SQL used to determine first block */
139947
139948  /* Calculate nLeafEst. */
139949  rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
139950  if( rc==SQLITE_OK ){
139951    sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
139952    sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
139953    if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
139954      nLeafEst = sqlite3_column_int(pLeafEst, 0);
139955    }
139956    rc = sqlite3_reset(pLeafEst);
139957  }
139958  if( rc!=SQLITE_OK ) return rc;
139959
139960  /* Calculate the first block to use in the output segment */
139961  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
139962  if( rc==SQLITE_OK ){
139963    if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
139964      pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
139965      pWriter->iEnd = pWriter->iStart - 1;
139966      pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
139967    }
139968    rc = sqlite3_reset(pFirstBlock);
139969  }
139970  if( rc!=SQLITE_OK ) return rc;
139971
139972  /* Insert the marker in the %_segments table to make sure nobody tries
139973  ** to steal the space just allocated. This is also used to identify
139974  ** appendable segments.  */
139975  rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
139976  if( rc!=SQLITE_OK ) return rc;
139977
139978  pWriter->iAbsLevel = iAbsLevel;
139979  pWriter->nLeafEst = nLeafEst;
139980  pWriter->iIdx = iIdx;
139981
139982  /* Set up the array of NodeWriter objects */
139983  for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
139984    pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
139985  }
139986  return SQLITE_OK;
139987}
139988
139989/*
139990** Remove an entry from the %_segdir table. This involves running the
139991** following two statements:
139992**
139993**   DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
139994**   UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
139995**
139996** The DELETE statement removes the specific %_segdir level. The UPDATE
139997** statement ensures that the remaining segments have contiguously allocated
139998** idx values.
139999*/
140000static int fts3RemoveSegdirEntry(
140001  Fts3Table *p,                   /* FTS3 table handle */
140002  sqlite3_int64 iAbsLevel,        /* Absolute level to delete from */
140003  int iIdx                        /* Index of %_segdir entry to delete */
140004){
140005  int rc;                         /* Return code */
140006  sqlite3_stmt *pDelete = 0;      /* DELETE statement */
140007
140008  rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
140009  if( rc==SQLITE_OK ){
140010    sqlite3_bind_int64(pDelete, 1, iAbsLevel);
140011    sqlite3_bind_int(pDelete, 2, iIdx);
140012    sqlite3_step(pDelete);
140013    rc = sqlite3_reset(pDelete);
140014  }
140015
140016  return rc;
140017}
140018
140019/*
140020** One or more segments have just been removed from absolute level iAbsLevel.
140021** Update the 'idx' values of the remaining segments in the level so that
140022** the idx values are a contiguous sequence starting from 0.
140023*/
140024static int fts3RepackSegdirLevel(
140025  Fts3Table *p,                   /* FTS3 table handle */
140026  sqlite3_int64 iAbsLevel         /* Absolute level to repack */
140027){
140028  int rc;                         /* Return code */
140029  int *aIdx = 0;                  /* Array of remaining idx values */
140030  int nIdx = 0;                   /* Valid entries in aIdx[] */
140031  int nAlloc = 0;                 /* Allocated size of aIdx[] */
140032  int i;                          /* Iterator variable */
140033  sqlite3_stmt *pSelect = 0;      /* Select statement to read idx values */
140034  sqlite3_stmt *pUpdate = 0;      /* Update statement to modify idx values */
140035
140036  rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
140037  if( rc==SQLITE_OK ){
140038    int rc2;
140039    sqlite3_bind_int64(pSelect, 1, iAbsLevel);
140040    while( SQLITE_ROW==sqlite3_step(pSelect) ){
140041      if( nIdx>=nAlloc ){
140042        int *aNew;
140043        nAlloc += 16;
140044        aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
140045        if( !aNew ){
140046          rc = SQLITE_NOMEM;
140047          break;
140048        }
140049        aIdx = aNew;
140050      }
140051      aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
140052    }
140053    rc2 = sqlite3_reset(pSelect);
140054    if( rc==SQLITE_OK ) rc = rc2;
140055  }
140056
140057  if( rc==SQLITE_OK ){
140058    rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
140059  }
140060  if( rc==SQLITE_OK ){
140061    sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
140062  }
140063
140064  assert( p->bIgnoreSavepoint==0 );
140065  p->bIgnoreSavepoint = 1;
140066  for(i=0; rc==SQLITE_OK && i<nIdx; i++){
140067    if( aIdx[i]!=i ){
140068      sqlite3_bind_int(pUpdate, 3, aIdx[i]);
140069      sqlite3_bind_int(pUpdate, 1, i);
140070      sqlite3_step(pUpdate);
140071      rc = sqlite3_reset(pUpdate);
140072    }
140073  }
140074  p->bIgnoreSavepoint = 0;
140075
140076  sqlite3_free(aIdx);
140077  return rc;
140078}
140079
140080static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
140081  pNode->a[0] = (char)iHeight;
140082  if( iChild ){
140083    assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
140084    pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
140085  }else{
140086    assert( pNode->nAlloc>=1 );
140087    pNode->n = 1;
140088  }
140089}
140090
140091/*
140092** The first two arguments are a pointer to and the size of a segment b-tree
140093** node. The node may be a leaf or an internal node.
140094**
140095** This function creates a new node image in blob object *pNew by copying
140096** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
140097** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
140098*/
140099static int fts3TruncateNode(
140100  const char *aNode,              /* Current node image */
140101  int nNode,                      /* Size of aNode in bytes */
140102  Blob *pNew,                     /* OUT: Write new node image here */
140103  const char *zTerm,              /* Omit all terms smaller than this */
140104  int nTerm,                      /* Size of zTerm in bytes */
140105  sqlite3_int64 *piBlock          /* OUT: Block number in next layer down */
140106){
140107  NodeReader reader;              /* Reader object */
140108  Blob prev = {0, 0, 0};          /* Previous term written to new node */
140109  int rc = SQLITE_OK;             /* Return code */
140110  int bLeaf = aNode[0]=='\0';     /* True for a leaf node */
140111
140112  /* Allocate required output space */
140113  blobGrowBuffer(pNew, nNode, &rc);
140114  if( rc!=SQLITE_OK ) return rc;
140115  pNew->n = 0;
140116
140117  /* Populate new node buffer */
140118  for(rc = nodeReaderInit(&reader, aNode, nNode);
140119      rc==SQLITE_OK && reader.aNode;
140120      rc = nodeReaderNext(&reader)
140121  ){
140122    if( pNew->n==0 ){
140123      int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
140124      if( res<0 || (bLeaf==0 && res==0) ) continue;
140125      fts3StartNode(pNew, (int)aNode[0], reader.iChild);
140126      *piBlock = reader.iChild;
140127    }
140128    rc = fts3AppendToNode(
140129        pNew, &prev, reader.term.a, reader.term.n,
140130        reader.aDoclist, reader.nDoclist
140131    );
140132    if( rc!=SQLITE_OK ) break;
140133  }
140134  if( pNew->n==0 ){
140135    fts3StartNode(pNew, (int)aNode[0], reader.iChild);
140136    *piBlock = reader.iChild;
140137  }
140138  assert( pNew->n<=pNew->nAlloc );
140139
140140  nodeReaderRelease(&reader);
140141  sqlite3_free(prev.a);
140142  return rc;
140143}
140144
140145/*
140146** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
140147** level iAbsLevel. This may involve deleting entries from the %_segments
140148** table, and modifying existing entries in both the %_segments and %_segdir
140149** tables.
140150**
140151** SQLITE_OK is returned if the segment is updated successfully. Or an
140152** SQLite error code otherwise.
140153*/
140154static int fts3TruncateSegment(
140155  Fts3Table *p,                   /* FTS3 table handle */
140156  sqlite3_int64 iAbsLevel,        /* Absolute level of segment to modify */
140157  int iIdx,                       /* Index within level of segment to modify */
140158  const char *zTerm,              /* Remove terms smaller than this */
140159  int nTerm                      /* Number of bytes in buffer zTerm */
140160){
140161  int rc = SQLITE_OK;             /* Return code */
140162  Blob root = {0,0,0};            /* New root page image */
140163  Blob block = {0,0,0};           /* Buffer used for any other block */
140164  sqlite3_int64 iBlock = 0;       /* Block id */
140165  sqlite3_int64 iNewStart = 0;    /* New value for iStartBlock */
140166  sqlite3_int64 iOldStart = 0;    /* Old value for iStartBlock */
140167  sqlite3_stmt *pFetch = 0;       /* Statement used to fetch segdir */
140168
140169  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
140170  if( rc==SQLITE_OK ){
140171    int rc2;                      /* sqlite3_reset() return code */
140172    sqlite3_bind_int64(pFetch, 1, iAbsLevel);
140173    sqlite3_bind_int(pFetch, 2, iIdx);
140174    if( SQLITE_ROW==sqlite3_step(pFetch) ){
140175      const char *aRoot = sqlite3_column_blob(pFetch, 4);
140176      int nRoot = sqlite3_column_bytes(pFetch, 4);
140177      iOldStart = sqlite3_column_int64(pFetch, 1);
140178      rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
140179    }
140180    rc2 = sqlite3_reset(pFetch);
140181    if( rc==SQLITE_OK ) rc = rc2;
140182  }
140183
140184  while( rc==SQLITE_OK && iBlock ){
140185    char *aBlock = 0;
140186    int nBlock = 0;
140187    iNewStart = iBlock;
140188
140189    rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
140190    if( rc==SQLITE_OK ){
140191      rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
140192    }
140193    if( rc==SQLITE_OK ){
140194      rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
140195    }
140196    sqlite3_free(aBlock);
140197  }
140198
140199  /* Variable iNewStart now contains the first valid leaf node. */
140200  if( rc==SQLITE_OK && iNewStart ){
140201    sqlite3_stmt *pDel = 0;
140202    rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
140203    if( rc==SQLITE_OK ){
140204      sqlite3_bind_int64(pDel, 1, iOldStart);
140205      sqlite3_bind_int64(pDel, 2, iNewStart-1);
140206      sqlite3_step(pDel);
140207      rc = sqlite3_reset(pDel);
140208    }
140209  }
140210
140211  if( rc==SQLITE_OK ){
140212    sqlite3_stmt *pChomp = 0;
140213    rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
140214    if( rc==SQLITE_OK ){
140215      sqlite3_bind_int64(pChomp, 1, iNewStart);
140216      sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
140217      sqlite3_bind_int64(pChomp, 3, iAbsLevel);
140218      sqlite3_bind_int(pChomp, 4, iIdx);
140219      sqlite3_step(pChomp);
140220      rc = sqlite3_reset(pChomp);
140221    }
140222  }
140223
140224  sqlite3_free(root.a);
140225  sqlite3_free(block.a);
140226  return rc;
140227}
140228
140229/*
140230** This function is called after an incrmental-merge operation has run to
140231** merge (or partially merge) two or more segments from absolute level
140232** iAbsLevel.
140233**
140234** Each input segment is either removed from the db completely (if all of
140235** its data was copied to the output segment by the incrmerge operation)
140236** or modified in place so that it no longer contains those entries that
140237** have been duplicated in the output segment.
140238*/
140239static int fts3IncrmergeChomp(
140240  Fts3Table *p,                   /* FTS table handle */
140241  sqlite3_int64 iAbsLevel,        /* Absolute level containing segments */
140242  Fts3MultiSegReader *pCsr,       /* Chomp all segments opened by this cursor */
140243  int *pnRem                      /* Number of segments not deleted */
140244){
140245  int i;
140246  int nRem = 0;
140247  int rc = SQLITE_OK;
140248
140249  for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
140250    Fts3SegReader *pSeg = 0;
140251    int j;
140252
140253    /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
140254    ** somewhere in the pCsr->apSegment[] array.  */
140255    for(j=0; ALWAYS(j<pCsr->nSegment); j++){
140256      pSeg = pCsr->apSegment[j];
140257      if( pSeg->iIdx==i ) break;
140258    }
140259    assert( j<pCsr->nSegment && pSeg->iIdx==i );
140260
140261    if( pSeg->aNode==0 ){
140262      /* Seg-reader is at EOF. Remove the entire input segment. */
140263      rc = fts3DeleteSegment(p, pSeg);
140264      if( rc==SQLITE_OK ){
140265        rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
140266      }
140267      *pnRem = 0;
140268    }else{
140269      /* The incremental merge did not copy all the data from this
140270      ** segment to the upper level. The segment is modified in place
140271      ** so that it contains no keys smaller than zTerm/nTerm. */
140272      const char *zTerm = pSeg->zTerm;
140273      int nTerm = pSeg->nTerm;
140274      rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
140275      nRem++;
140276    }
140277  }
140278
140279  if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
140280    rc = fts3RepackSegdirLevel(p, iAbsLevel);
140281  }
140282
140283  *pnRem = nRem;
140284  return rc;
140285}
140286
140287/*
140288** Store an incr-merge hint in the database.
140289*/
140290static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
140291  sqlite3_stmt *pReplace = 0;
140292  int rc;                         /* Return code */
140293
140294  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
140295  if( rc==SQLITE_OK ){
140296    sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
140297    sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
140298    sqlite3_step(pReplace);
140299    rc = sqlite3_reset(pReplace);
140300  }
140301
140302  return rc;
140303}
140304
140305/*
140306** Load an incr-merge hint from the database. The incr-merge hint, if one
140307** exists, is stored in the rowid==1 row of the %_stat table.
140308**
140309** If successful, populate blob *pHint with the value read from the %_stat
140310** table and return SQLITE_OK. Otherwise, if an error occurs, return an
140311** SQLite error code.
140312*/
140313static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
140314  sqlite3_stmt *pSelect = 0;
140315  int rc;
140316
140317  pHint->n = 0;
140318  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
140319  if( rc==SQLITE_OK ){
140320    int rc2;
140321    sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
140322    if( SQLITE_ROW==sqlite3_step(pSelect) ){
140323      const char *aHint = sqlite3_column_blob(pSelect, 0);
140324      int nHint = sqlite3_column_bytes(pSelect, 0);
140325      if( aHint ){
140326        blobGrowBuffer(pHint, nHint, &rc);
140327        if( rc==SQLITE_OK ){
140328          memcpy(pHint->a, aHint, nHint);
140329          pHint->n = nHint;
140330        }
140331      }
140332    }
140333    rc2 = sqlite3_reset(pSelect);
140334    if( rc==SQLITE_OK ) rc = rc2;
140335  }
140336
140337  return rc;
140338}
140339
140340/*
140341** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
140342** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
140343** consists of two varints, the absolute level number of the input segments
140344** and the number of input segments.
140345**
140346** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
140347** set *pRc to an SQLite error code before returning.
140348*/
140349static void fts3IncrmergeHintPush(
140350  Blob *pHint,                    /* Hint blob to append to */
140351  i64 iAbsLevel,                  /* First varint to store in hint */
140352  int nInput,                     /* Second varint to store in hint */
140353  int *pRc                        /* IN/OUT: Error code */
140354){
140355  blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
140356  if( *pRc==SQLITE_OK ){
140357    pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
140358    pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
140359  }
140360}
140361
140362/*
140363** Read the last entry (most recently pushed) from the hint blob *pHint
140364** and then remove the entry. Write the two values read to *piAbsLevel and
140365** *pnInput before returning.
140366**
140367** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
140368** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
140369*/
140370static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
140371  const int nHint = pHint->n;
140372  int i;
140373
140374  i = pHint->n-2;
140375  while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
140376  while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
140377
140378  pHint->n = i;
140379  i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
140380  i += fts3GetVarint32(&pHint->a[i], pnInput);
140381  if( i!=nHint ) return SQLITE_CORRUPT_VTAB;
140382
140383  return SQLITE_OK;
140384}
140385
140386
140387/*
140388** Attempt an incremental merge that writes nMerge leaf blocks.
140389**
140390** Incremental merges happen nMin segments at a time. The segments
140391** to be merged are the nMin oldest segments (the ones with the smallest
140392** values for the _segdir.idx field) in the highest level that contains
140393** at least nMin segments. Multiple merges might occur in an attempt to
140394** write the quota of nMerge leaf blocks.
140395*/
140396SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
140397  int rc;                         /* Return code */
140398  int nRem = nMerge;              /* Number of leaf pages yet to  be written */
140399  Fts3MultiSegReader *pCsr;       /* Cursor used to read input data */
140400  Fts3SegFilter *pFilter;         /* Filter used with cursor pCsr */
140401  IncrmergeWriter *pWriter;       /* Writer object */
140402  int nSeg = 0;                   /* Number of input segments */
140403  sqlite3_int64 iAbsLevel = 0;    /* Absolute level number to work on */
140404  Blob hint = {0, 0, 0};          /* Hint read from %_stat table */
140405  int bDirtyHint = 0;             /* True if blob 'hint' has been modified */
140406
140407  /* Allocate space for the cursor, filter and writer objects */
140408  const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
140409  pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
140410  if( !pWriter ) return SQLITE_NOMEM;
140411  pFilter = (Fts3SegFilter *)&pWriter[1];
140412  pCsr = (Fts3MultiSegReader *)&pFilter[1];
140413
140414  rc = fts3IncrmergeHintLoad(p, &hint);
140415  while( rc==SQLITE_OK && nRem>0 ){
140416    const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
140417    sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
140418    int bUseHint = 0;             /* True if attempting to append */
140419    int iIdx = 0;                 /* Largest idx in level (iAbsLevel+1) */
140420
140421    /* Search the %_segdir table for the absolute level with the smallest
140422    ** relative level number that contains at least nMin segments, if any.
140423    ** If one is found, set iAbsLevel to the absolute level number and
140424    ** nSeg to nMin. If no level with at least nMin segments can be found,
140425    ** set nSeg to -1.
140426    */
140427    rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
140428    sqlite3_bind_int(pFindLevel, 1, nMin);
140429    if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
140430      iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
140431      nSeg = nMin;
140432    }else{
140433      nSeg = -1;
140434    }
140435    rc = sqlite3_reset(pFindLevel);
140436
140437    /* If the hint read from the %_stat table is not empty, check if the
140438    ** last entry in it specifies a relative level smaller than or equal
140439    ** to the level identified by the block above (if any). If so, this
140440    ** iteration of the loop will work on merging at the hinted level.
140441    */
140442    if( rc==SQLITE_OK && hint.n ){
140443      int nHint = hint.n;
140444      sqlite3_int64 iHintAbsLevel = 0;      /* Hint level */
140445      int nHintSeg = 0;                     /* Hint number of segments */
140446
140447      rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
140448      if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
140449        iAbsLevel = iHintAbsLevel;
140450        nSeg = nHintSeg;
140451        bUseHint = 1;
140452        bDirtyHint = 1;
140453      }else{
140454        /* This undoes the effect of the HintPop() above - so that no entry
140455        ** is removed from the hint blob.  */
140456        hint.n = nHint;
140457      }
140458    }
140459
140460    /* If nSeg is less that zero, then there is no level with at least
140461    ** nMin segments and no hint in the %_stat table. No work to do.
140462    ** Exit early in this case.  */
140463    if( nSeg<0 ) break;
140464
140465    /* Open a cursor to iterate through the contents of the oldest nSeg
140466    ** indexes of absolute level iAbsLevel. If this cursor is opened using
140467    ** the 'hint' parameters, it is possible that there are less than nSeg
140468    ** segments available in level iAbsLevel. In this case, no work is
140469    ** done on iAbsLevel - fall through to the next iteration of the loop
140470    ** to start work on some other level.  */
140471    memset(pWriter, 0, nAlloc);
140472    pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
140473
140474    if( rc==SQLITE_OK ){
140475      rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
140476      assert( bUseHint==1 || bUseHint==0 );
140477      if( iIdx==0 || (bUseHint && iIdx==1) ){
140478        int bIgnore = 0;
140479        rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
140480        if( bIgnore ){
140481          pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
140482        }
140483      }
140484    }
140485
140486    if( rc==SQLITE_OK ){
140487      rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
140488    }
140489    if( SQLITE_OK==rc && pCsr->nSegment==nSeg
140490     && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
140491     && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
140492    ){
140493      if( bUseHint && iIdx>0 ){
140494        const char *zKey = pCsr->zTerm;
140495        int nKey = pCsr->nTerm;
140496        rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
140497      }else{
140498        rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
140499      }
140500
140501      if( rc==SQLITE_OK && pWriter->nLeafEst ){
140502        fts3LogMerge(nSeg, iAbsLevel);
140503        do {
140504          rc = fts3IncrmergeAppend(p, pWriter, pCsr);
140505          if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
140506          if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
140507        }while( rc==SQLITE_ROW );
140508
140509        /* Update or delete the input segments */
140510        if( rc==SQLITE_OK ){
140511          nRem -= (1 + pWriter->nWork);
140512          rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
140513          if( nSeg!=0 ){
140514            bDirtyHint = 1;
140515            fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
140516          }
140517        }
140518      }
140519
140520      if( nSeg!=0 ){
140521        pWriter->nLeafData = pWriter->nLeafData * -1;
140522      }
140523      fts3IncrmergeRelease(p, pWriter, &rc);
140524      if( nSeg==0 && pWriter->bNoLeafData==0 ){
140525        fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
140526      }
140527    }
140528
140529    sqlite3Fts3SegReaderFinish(pCsr);
140530  }
140531
140532  /* Write the hint values into the %_stat table for the next incr-merger */
140533  if( bDirtyHint && rc==SQLITE_OK ){
140534    rc = fts3IncrmergeHintStore(p, &hint);
140535  }
140536
140537  sqlite3_free(pWriter);
140538  sqlite3_free(hint.a);
140539  return rc;
140540}
140541
140542/*
140543** Convert the text beginning at *pz into an integer and return
140544** its value.  Advance *pz to point to the first character past
140545** the integer.
140546*/
140547static int fts3Getint(const char **pz){
140548  const char *z = *pz;
140549  int i = 0;
140550  while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
140551  *pz = z;
140552  return i;
140553}
140554
140555/*
140556** Process statements of the form:
140557**
140558**    INSERT INTO table(table) VALUES('merge=A,B');
140559**
140560** A and B are integers that decode to be the number of leaf pages
140561** written for the merge, and the minimum number of segments on a level
140562** before it will be selected for a merge, respectively.
140563*/
140564static int fts3DoIncrmerge(
140565  Fts3Table *p,                   /* FTS3 table handle */
140566  const char *zParam              /* Nul-terminated string containing "A,B" */
140567){
140568  int rc;
140569  int nMin = (FTS3_MERGE_COUNT / 2);
140570  int nMerge = 0;
140571  const char *z = zParam;
140572
140573  /* Read the first integer value */
140574  nMerge = fts3Getint(&z);
140575
140576  /* If the first integer value is followed by a ',',  read the second
140577  ** integer value. */
140578  if( z[0]==',' && z[1]!='\0' ){
140579    z++;
140580    nMin = fts3Getint(&z);
140581  }
140582
140583  if( z[0]!='\0' || nMin<2 ){
140584    rc = SQLITE_ERROR;
140585  }else{
140586    rc = SQLITE_OK;
140587    if( !p->bHasStat ){
140588      assert( p->bFts4==0 );
140589      sqlite3Fts3CreateStatTable(&rc, p);
140590    }
140591    if( rc==SQLITE_OK ){
140592      rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
140593    }
140594    sqlite3Fts3SegmentsClose(p);
140595  }
140596  return rc;
140597}
140598
140599/*
140600** Process statements of the form:
140601**
140602**    INSERT INTO table(table) VALUES('automerge=X');
140603**
140604** where X is an integer.  X==0 means to turn automerge off.  X!=0 means
140605** turn it on.  The setting is persistent.
140606*/
140607static int fts3DoAutoincrmerge(
140608  Fts3Table *p,                   /* FTS3 table handle */
140609  const char *zParam              /* Nul-terminated string containing boolean */
140610){
140611  int rc = SQLITE_OK;
140612  sqlite3_stmt *pStmt = 0;
140613  p->nAutoincrmerge = fts3Getint(&zParam);
140614  if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
140615    p->nAutoincrmerge = 8;
140616  }
140617  if( !p->bHasStat ){
140618    assert( p->bFts4==0 );
140619    sqlite3Fts3CreateStatTable(&rc, p);
140620    if( rc ) return rc;
140621  }
140622  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
140623  if( rc ) return rc;
140624  sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
140625  sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
140626  sqlite3_step(pStmt);
140627  rc = sqlite3_reset(pStmt);
140628  return rc;
140629}
140630
140631/*
140632** Return a 64-bit checksum for the FTS index entry specified by the
140633** arguments to this function.
140634*/
140635static u64 fts3ChecksumEntry(
140636  const char *zTerm,              /* Pointer to buffer containing term */
140637  int nTerm,                      /* Size of zTerm in bytes */
140638  int iLangid,                    /* Language id for current row */
140639  int iIndex,                     /* Index (0..Fts3Table.nIndex-1) */
140640  i64 iDocid,                     /* Docid for current row. */
140641  int iCol,                       /* Column number */
140642  int iPos                        /* Position */
140643){
140644  int i;
140645  u64 ret = (u64)iDocid;
140646
140647  ret += (ret<<3) + iLangid;
140648  ret += (ret<<3) + iIndex;
140649  ret += (ret<<3) + iCol;
140650  ret += (ret<<3) + iPos;
140651  for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
140652
140653  return ret;
140654}
140655
140656/*
140657** Return a checksum of all entries in the FTS index that correspond to
140658** language id iLangid. The checksum is calculated by XORing the checksums
140659** of each individual entry (see fts3ChecksumEntry()) together.
140660**
140661** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
140662** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
140663** return value is undefined in this case.
140664*/
140665static u64 fts3ChecksumIndex(
140666  Fts3Table *p,                   /* FTS3 table handle */
140667  int iLangid,                    /* Language id to return cksum for */
140668  int iIndex,                     /* Index to cksum (0..p->nIndex-1) */
140669  int *pRc                        /* OUT: Return code */
140670){
140671  Fts3SegFilter filter;
140672  Fts3MultiSegReader csr;
140673  int rc;
140674  u64 cksum = 0;
140675
140676  assert( *pRc==SQLITE_OK );
140677
140678  memset(&filter, 0, sizeof(filter));
140679  memset(&csr, 0, sizeof(csr));
140680  filter.flags =  FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
140681  filter.flags |= FTS3_SEGMENT_SCAN;
140682
140683  rc = sqlite3Fts3SegReaderCursor(
140684      p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
140685  );
140686  if( rc==SQLITE_OK ){
140687    rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
140688  }
140689
140690  if( rc==SQLITE_OK ){
140691    while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
140692      char *pCsr = csr.aDoclist;
140693      char *pEnd = &pCsr[csr.nDoclist];
140694
140695      i64 iDocid = 0;
140696      i64 iCol = 0;
140697      i64 iPos = 0;
140698
140699      pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
140700      while( pCsr<pEnd ){
140701        i64 iVal = 0;
140702        pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
140703        if( pCsr<pEnd ){
140704          if( iVal==0 || iVal==1 ){
140705            iCol = 0;
140706            iPos = 0;
140707            if( iVal ){
140708              pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
140709            }else{
140710              pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
140711              iDocid += iVal;
140712            }
140713          }else{
140714            iPos += (iVal - 2);
140715            cksum = cksum ^ fts3ChecksumEntry(
140716                csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
140717                (int)iCol, (int)iPos
140718            );
140719          }
140720        }
140721      }
140722    }
140723  }
140724  sqlite3Fts3SegReaderFinish(&csr);
140725
140726  *pRc = rc;
140727  return cksum;
140728}
140729
140730/*
140731** Check if the contents of the FTS index match the current contents of the
140732** content table. If no error occurs and the contents do match, set *pbOk
140733** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
140734** to false before returning.
140735**
140736** If an error occurs (e.g. an OOM or IO error), return an SQLite error
140737** code. The final value of *pbOk is undefined in this case.
140738*/
140739static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
140740  int rc = SQLITE_OK;             /* Return code */
140741  u64 cksum1 = 0;                 /* Checksum based on FTS index contents */
140742  u64 cksum2 = 0;                 /* Checksum based on %_content contents */
140743  sqlite3_stmt *pAllLangid = 0;   /* Statement to return all language-ids */
140744
140745  /* This block calculates the checksum according to the FTS index. */
140746  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
140747  if( rc==SQLITE_OK ){
140748    int rc2;
140749    sqlite3_bind_int(pAllLangid, 1, p->nIndex);
140750    while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
140751      int iLangid = sqlite3_column_int(pAllLangid, 0);
140752      int i;
140753      for(i=0; i<p->nIndex; i++){
140754        cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
140755      }
140756    }
140757    rc2 = sqlite3_reset(pAllLangid);
140758    if( rc==SQLITE_OK ) rc = rc2;
140759  }
140760
140761  /* This block calculates the checksum according to the %_content table */
140762  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
140763  if( rc==SQLITE_OK ){
140764    sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
140765    sqlite3_stmt *pStmt = 0;
140766    char *zSql;
140767
140768    zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
140769    if( !zSql ){
140770      rc = SQLITE_NOMEM;
140771    }else{
140772      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
140773      sqlite3_free(zSql);
140774    }
140775
140776    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
140777      i64 iDocid = sqlite3_column_int64(pStmt, 0);
140778      int iLang = langidFromSelect(p, pStmt);
140779      int iCol;
140780
140781      for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
140782        const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
140783        int nText = sqlite3_column_bytes(pStmt, iCol+1);
140784        sqlite3_tokenizer_cursor *pT = 0;
140785
140786        rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText, &pT);
140787        while( rc==SQLITE_OK ){
140788          char const *zToken;       /* Buffer containing token */
140789          int nToken = 0;           /* Number of bytes in token */
140790          int iDum1 = 0, iDum2 = 0; /* Dummy variables */
140791          int iPos = 0;             /* Position of token in zText */
140792
140793          rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
140794          if( rc==SQLITE_OK ){
140795            int i;
140796            cksum2 = cksum2 ^ fts3ChecksumEntry(
140797                zToken, nToken, iLang, 0, iDocid, iCol, iPos
140798            );
140799            for(i=1; i<p->nIndex; i++){
140800              if( p->aIndex[i].nPrefix<=nToken ){
140801                cksum2 = cksum2 ^ fts3ChecksumEntry(
140802                  zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
140803                );
140804              }
140805            }
140806          }
140807        }
140808        if( pT ) pModule->xClose(pT);
140809        if( rc==SQLITE_DONE ) rc = SQLITE_OK;
140810      }
140811    }
140812
140813    sqlite3_finalize(pStmt);
140814  }
140815
140816  *pbOk = (cksum1==cksum2);
140817  return rc;
140818}
140819
140820/*
140821** Run the integrity-check. If no error occurs and the current contents of
140822** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
140823** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
140824**
140825** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
140826** error code.
140827**
140828** The integrity-check works as follows. For each token and indexed token
140829** prefix in the document set, a 64-bit checksum is calculated (by code
140830** in fts3ChecksumEntry()) based on the following:
140831**
140832**     + The index number (0 for the main index, 1 for the first prefix
140833**       index etc.),
140834**     + The token (or token prefix) text itself,
140835**     + The language-id of the row it appears in,
140836**     + The docid of the row it appears in,
140837**     + The column it appears in, and
140838**     + The tokens position within that column.
140839**
140840** The checksums for all entries in the index are XORed together to create
140841** a single checksum for the entire index.
140842**
140843** The integrity-check code calculates the same checksum in two ways:
140844**
140845**     1. By scanning the contents of the FTS index, and
140846**     2. By scanning and tokenizing the content table.
140847**
140848** If the two checksums are identical, the integrity-check is deemed to have
140849** passed.
140850*/
140851static int fts3DoIntegrityCheck(
140852  Fts3Table *p                    /* FTS3 table handle */
140853){
140854  int rc;
140855  int bOk = 0;
140856  rc = fts3IntegrityCheck(p, &bOk);
140857  if( rc==SQLITE_OK && bOk==0 ) rc = SQLITE_CORRUPT_VTAB;
140858  return rc;
140859}
140860
140861/*
140862** Handle a 'special' INSERT of the form:
140863**
140864**   "INSERT INTO tbl(tbl) VALUES(<expr>)"
140865**
140866** Argument pVal contains the result of <expr>. Currently the only
140867** meaningful value to insert is the text 'optimize'.
140868*/
140869static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
140870  int rc;                         /* Return Code */
140871  const char *zVal = (const char *)sqlite3_value_text(pVal);
140872  int nVal = sqlite3_value_bytes(pVal);
140873
140874  if( !zVal ){
140875    return SQLITE_NOMEM;
140876  }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
140877    rc = fts3DoOptimize(p, 0);
140878  }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
140879    rc = fts3DoRebuild(p);
140880  }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
140881    rc = fts3DoIntegrityCheck(p);
140882  }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
140883    rc = fts3DoIncrmerge(p, &zVal[6]);
140884  }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
140885    rc = fts3DoAutoincrmerge(p, &zVal[10]);
140886#ifdef SQLITE_TEST
140887  }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
140888    p->nNodeSize = atoi(&zVal[9]);
140889    rc = SQLITE_OK;
140890  }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
140891    p->nMaxPendingData = atoi(&zVal[11]);
140892    rc = SQLITE_OK;
140893  }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
140894    p->bNoIncrDoclist = atoi(&zVal[21]);
140895    rc = SQLITE_OK;
140896#endif
140897  }else{
140898    rc = SQLITE_ERROR;
140899  }
140900
140901  return rc;
140902}
140903
140904#ifndef SQLITE_DISABLE_FTS4_DEFERRED
140905/*
140906** Delete all cached deferred doclists. Deferred doclists are cached
140907** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
140908*/
140909SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
140910  Fts3DeferredToken *pDef;
140911  for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
140912    fts3PendingListDelete(pDef->pList);
140913    pDef->pList = 0;
140914  }
140915}
140916
140917/*
140918** Free all entries in the pCsr->pDeffered list. Entries are added to
140919** this list using sqlite3Fts3DeferToken().
140920*/
140921SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
140922  Fts3DeferredToken *pDef;
140923  Fts3DeferredToken *pNext;
140924  for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
140925    pNext = pDef->pNext;
140926    fts3PendingListDelete(pDef->pList);
140927    sqlite3_free(pDef);
140928  }
140929  pCsr->pDeferred = 0;
140930}
140931
140932/*
140933** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
140934** based on the row that pCsr currently points to.
140935**
140936** A deferred-doclist is like any other doclist with position information
140937** included, except that it only contains entries for a single row of the
140938** table, not for all rows.
140939*/
140940SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
140941  int rc = SQLITE_OK;             /* Return code */
140942  if( pCsr->pDeferred ){
140943    int i;                        /* Used to iterate through table columns */
140944    sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
140945    Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
140946
140947    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
140948    sqlite3_tokenizer *pT = p->pTokenizer;
140949    sqlite3_tokenizer_module const *pModule = pT->pModule;
140950
140951    assert( pCsr->isRequireSeek==0 );
140952    iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
140953
140954    for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
140955      if( p->abNotindexed[i]==0 ){
140956        const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
140957        sqlite3_tokenizer_cursor *pTC = 0;
140958
140959        rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
140960        while( rc==SQLITE_OK ){
140961          char const *zToken;       /* Buffer containing token */
140962          int nToken = 0;           /* Number of bytes in token */
140963          int iDum1 = 0, iDum2 = 0; /* Dummy variables */
140964          int iPos = 0;             /* Position of token in zText */
140965
140966          rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
140967          for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
140968            Fts3PhraseToken *pPT = pDef->pToken;
140969            if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
140970                && (pPT->bFirst==0 || iPos==0)
140971                && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
140972                && (0==memcmp(zToken, pPT->z, pPT->n))
140973              ){
140974              fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
140975            }
140976          }
140977        }
140978        if( pTC ) pModule->xClose(pTC);
140979        if( rc==SQLITE_DONE ) rc = SQLITE_OK;
140980      }
140981    }
140982
140983    for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
140984      if( pDef->pList ){
140985        rc = fts3PendingListAppendVarint(&pDef->pList, 0);
140986      }
140987    }
140988  }
140989
140990  return rc;
140991}
140992
140993SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
140994  Fts3DeferredToken *p,
140995  char **ppData,
140996  int *pnData
140997){
140998  char *pRet;
140999  int nSkip;
141000  sqlite3_int64 dummy;
141001
141002  *ppData = 0;
141003  *pnData = 0;
141004
141005  if( p->pList==0 ){
141006    return SQLITE_OK;
141007  }
141008
141009  pRet = (char *)sqlite3_malloc(p->pList->nData);
141010  if( !pRet ) return SQLITE_NOMEM;
141011
141012  nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
141013  *pnData = p->pList->nData - nSkip;
141014  *ppData = pRet;
141015
141016  memcpy(pRet, &p->pList->aData[nSkip], *pnData);
141017  return SQLITE_OK;
141018}
141019
141020/*
141021** Add an entry for token pToken to the pCsr->pDeferred list.
141022*/
141023SQLITE_PRIVATE int sqlite3Fts3DeferToken(
141024  Fts3Cursor *pCsr,               /* Fts3 table cursor */
141025  Fts3PhraseToken *pToken,        /* Token to defer */
141026  int iCol                        /* Column that token must appear in (or -1) */
141027){
141028  Fts3DeferredToken *pDeferred;
141029  pDeferred = sqlite3_malloc(sizeof(*pDeferred));
141030  if( !pDeferred ){
141031    return SQLITE_NOMEM;
141032  }
141033  memset(pDeferred, 0, sizeof(*pDeferred));
141034  pDeferred->pToken = pToken;
141035  pDeferred->pNext = pCsr->pDeferred;
141036  pDeferred->iCol = iCol;
141037  pCsr->pDeferred = pDeferred;
141038
141039  assert( pToken->pDeferred==0 );
141040  pToken->pDeferred = pDeferred;
141041
141042  return SQLITE_OK;
141043}
141044#endif
141045
141046/*
141047** SQLite value pRowid contains the rowid of a row that may or may not be
141048** present in the FTS3 table. If it is, delete it and adjust the contents
141049** of subsiduary data structures accordingly.
141050*/
141051static int fts3DeleteByRowid(
141052  Fts3Table *p,
141053  sqlite3_value *pRowid,
141054  int *pnChng,                    /* IN/OUT: Decrement if row is deleted */
141055  u32 *aSzDel
141056){
141057  int rc = SQLITE_OK;             /* Return code */
141058  int bFound = 0;                 /* True if *pRowid really is in the table */
141059
141060  fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
141061  if( bFound && rc==SQLITE_OK ){
141062    int isEmpty = 0;              /* Deleting *pRowid leaves the table empty */
141063    rc = fts3IsEmpty(p, pRowid, &isEmpty);
141064    if( rc==SQLITE_OK ){
141065      if( isEmpty ){
141066        /* Deleting this row means the whole table is empty. In this case
141067        ** delete the contents of all three tables and throw away any
141068        ** data in the pendingTerms hash table.  */
141069        rc = fts3DeleteAll(p, 1);
141070        *pnChng = 0;
141071        memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
141072      }else{
141073        *pnChng = *pnChng - 1;
141074        if( p->zContentTbl==0 ){
141075          fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
141076        }
141077        if( p->bHasDocsize ){
141078          fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
141079        }
141080      }
141081    }
141082  }
141083
141084  return rc;
141085}
141086
141087/*
141088** This function does the work for the xUpdate method of FTS3 virtual
141089** tables. The schema of the virtual table being:
141090**
141091**     CREATE TABLE <table name>(
141092**       <user columns>,
141093**       <table name> HIDDEN,
141094**       docid HIDDEN,
141095**       <langid> HIDDEN
141096**     );
141097**
141098**
141099*/
141100SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
141101  sqlite3_vtab *pVtab,            /* FTS3 vtab object */
141102  int nArg,                       /* Size of argument array */
141103  sqlite3_value **apVal,          /* Array of arguments */
141104  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
141105){
141106  Fts3Table *p = (Fts3Table *)pVtab;
141107  int rc = SQLITE_OK;             /* Return Code */
141108  int isRemove = 0;               /* True for an UPDATE or DELETE */
141109  u32 *aSzIns = 0;                /* Sizes of inserted documents */
141110  u32 *aSzDel = 0;                /* Sizes of deleted documents */
141111  int nChng = 0;                  /* Net change in number of documents */
141112  int bInsertDone = 0;
141113
141114  /* At this point it must be known if the %_stat table exists or not.
141115  ** So bHasStat may not be 2.  */
141116  assert( p->bHasStat==0 || p->bHasStat==1 );
141117
141118  assert( p->pSegments==0 );
141119  assert(
141120      nArg==1                     /* DELETE operations */
141121   || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
141122  );
141123
141124  /* Check for a "special" INSERT operation. One of the form:
141125  **
141126  **   INSERT INTO xyz(xyz) VALUES('command');
141127  */
141128  if( nArg>1
141129   && sqlite3_value_type(apVal[0])==SQLITE_NULL
141130   && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
141131  ){
141132    rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
141133    goto update_out;
141134  }
141135
141136  if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
141137    rc = SQLITE_CONSTRAINT;
141138    goto update_out;
141139  }
141140
141141  /* Allocate space to hold the change in document sizes */
141142  aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
141143  if( aSzDel==0 ){
141144    rc = SQLITE_NOMEM;
141145    goto update_out;
141146  }
141147  aSzIns = &aSzDel[p->nColumn+1];
141148  memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
141149
141150  rc = fts3Writelock(p);
141151  if( rc!=SQLITE_OK ) goto update_out;
141152
141153  /* If this is an INSERT operation, or an UPDATE that modifies the rowid
141154  ** value, then this operation requires constraint handling.
141155  **
141156  ** If the on-conflict mode is REPLACE, this means that the existing row
141157  ** should be deleted from the database before inserting the new row. Or,
141158  ** if the on-conflict mode is other than REPLACE, then this method must
141159  ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
141160  ** modify the database file.
141161  */
141162  if( nArg>1 && p->zContentTbl==0 ){
141163    /* Find the value object that holds the new rowid value. */
141164    sqlite3_value *pNewRowid = apVal[3+p->nColumn];
141165    if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
141166      pNewRowid = apVal[1];
141167    }
141168
141169    if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
141170        sqlite3_value_type(apVal[0])==SQLITE_NULL
141171     || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
141172    )){
141173      /* The new rowid is not NULL (in this case the rowid will be
141174      ** automatically assigned and there is no chance of a conflict), and
141175      ** the statement is either an INSERT or an UPDATE that modifies the
141176      ** rowid column. So if the conflict mode is REPLACE, then delete any
141177      ** existing row with rowid=pNewRowid.
141178      **
141179      ** Or, if the conflict mode is not REPLACE, insert the new record into
141180      ** the %_content table. If we hit the duplicate rowid constraint (or any
141181      ** other error) while doing so, return immediately.
141182      **
141183      ** This branch may also run if pNewRowid contains a value that cannot
141184      ** be losslessly converted to an integer. In this case, the eventual
141185      ** call to fts3InsertData() (either just below or further on in this
141186      ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
141187      ** invoked, it will delete zero rows (since no row will have
141188      ** docid=$pNewRowid if $pNewRowid is not an integer value).
141189      */
141190      if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
141191        rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
141192      }else{
141193        rc = fts3InsertData(p, apVal, pRowid);
141194        bInsertDone = 1;
141195      }
141196    }
141197  }
141198  if( rc!=SQLITE_OK ){
141199    goto update_out;
141200  }
141201
141202  /* If this is a DELETE or UPDATE operation, remove the old record. */
141203  if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
141204    assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
141205    rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
141206    isRemove = 1;
141207  }
141208
141209  /* If this is an INSERT or UPDATE operation, insert the new record. */
141210  if( nArg>1 && rc==SQLITE_OK ){
141211    int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
141212    if( bInsertDone==0 ){
141213      rc = fts3InsertData(p, apVal, pRowid);
141214      if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
141215        rc = FTS_CORRUPT_VTAB;
141216      }
141217    }
141218    if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
141219      rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
141220    }
141221    if( rc==SQLITE_OK ){
141222      assert( p->iPrevDocid==*pRowid );
141223      rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
141224    }
141225    if( p->bHasDocsize ){
141226      fts3InsertDocsize(&rc, p, aSzIns);
141227    }
141228    nChng++;
141229  }
141230
141231  if( p->bFts4 ){
141232    fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
141233  }
141234
141235 update_out:
141236  sqlite3_free(aSzDel);
141237  sqlite3Fts3SegmentsClose(p);
141238  return rc;
141239}
141240
141241/*
141242** Flush any data in the pending-terms hash table to disk. If successful,
141243** merge all segments in the database (including the new segment, if
141244** there was any data to flush) into a single segment.
141245*/
141246SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
141247  int rc;
141248  rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
141249  if( rc==SQLITE_OK ){
141250    rc = fts3DoOptimize(p, 1);
141251    if( rc==SQLITE_OK || rc==SQLITE_DONE ){
141252      int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
141253      if( rc2!=SQLITE_OK ) rc = rc2;
141254    }else{
141255      sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
141256      sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
141257    }
141258  }
141259  sqlite3Fts3SegmentsClose(p);
141260  return rc;
141261}
141262
141263#endif
141264
141265/************** End of fts3_write.c ******************************************/
141266/************** Begin file fts3_snippet.c ************************************/
141267/*
141268** 2009 Oct 23
141269**
141270** The author disclaims copyright to this source code.  In place of
141271** a legal notice, here is a blessing:
141272**
141273**    May you do good and not evil.
141274**    May you find forgiveness for yourself and forgive others.
141275**    May you share freely, never taking more than you give.
141276**
141277******************************************************************************
141278*/
141279
141280#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
141281
141282/* #include <string.h> */
141283/* #include <assert.h> */
141284
141285/*
141286** Characters that may appear in the second argument to matchinfo().
141287*/
141288#define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
141289#define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
141290#define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
141291#define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
141292#define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
141293#define FTS3_MATCHINFO_LCS       's'        /* nCol values */
141294#define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
141295
141296/*
141297** The default value for the second argument to matchinfo().
141298*/
141299#define FTS3_MATCHINFO_DEFAULT   "pcx"
141300
141301
141302/*
141303** Used as an fts3ExprIterate() context when loading phrase doclists to
141304** Fts3Expr.aDoclist[]/nDoclist.
141305*/
141306typedef struct LoadDoclistCtx LoadDoclistCtx;
141307struct LoadDoclistCtx {
141308  Fts3Cursor *pCsr;               /* FTS3 Cursor */
141309  int nPhrase;                    /* Number of phrases seen so far */
141310  int nToken;                     /* Number of tokens seen so far */
141311};
141312
141313/*
141314** The following types are used as part of the implementation of the
141315** fts3BestSnippet() routine.
141316*/
141317typedef struct SnippetIter SnippetIter;
141318typedef struct SnippetPhrase SnippetPhrase;
141319typedef struct SnippetFragment SnippetFragment;
141320
141321struct SnippetIter {
141322  Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
141323  int iCol;                       /* Extract snippet from this column */
141324  int nSnippet;                   /* Requested snippet length (in tokens) */
141325  int nPhrase;                    /* Number of phrases in query */
141326  SnippetPhrase *aPhrase;         /* Array of size nPhrase */
141327  int iCurrent;                   /* First token of current snippet */
141328};
141329
141330struct SnippetPhrase {
141331  int nToken;                     /* Number of tokens in phrase */
141332  char *pList;                    /* Pointer to start of phrase position list */
141333  int iHead;                      /* Next value in position list */
141334  char *pHead;                    /* Position list data following iHead */
141335  int iTail;                      /* Next value in trailing position list */
141336  char *pTail;                    /* Position list data following iTail */
141337};
141338
141339struct SnippetFragment {
141340  int iCol;                       /* Column snippet is extracted from */
141341  int iPos;                       /* Index of first token in snippet */
141342  u64 covered;                    /* Mask of query phrases covered */
141343  u64 hlmask;                     /* Mask of snippet terms to highlight */
141344};
141345
141346/*
141347** This type is used as an fts3ExprIterate() context object while
141348** accumulating the data returned by the matchinfo() function.
141349*/
141350typedef struct MatchInfo MatchInfo;
141351struct MatchInfo {
141352  Fts3Cursor *pCursor;            /* FTS3 Cursor */
141353  int nCol;                       /* Number of columns in table */
141354  int nPhrase;                    /* Number of matchable phrases in query */
141355  sqlite3_int64 nDoc;             /* Number of docs in database */
141356  u32 *aMatchinfo;                /* Pre-allocated buffer */
141357};
141358
141359
141360
141361/*
141362** The snippet() and offsets() functions both return text values. An instance
141363** of the following structure is used to accumulate those values while the
141364** functions are running. See fts3StringAppend() for details.
141365*/
141366typedef struct StrBuffer StrBuffer;
141367struct StrBuffer {
141368  char *z;                        /* Pointer to buffer containing string */
141369  int n;                          /* Length of z in bytes (excl. nul-term) */
141370  int nAlloc;                     /* Allocated size of buffer z in bytes */
141371};
141372
141373
141374/*
141375** This function is used to help iterate through a position-list. A position
141376** list is a list of unique integers, sorted from smallest to largest. Each
141377** element of the list is represented by an FTS3 varint that takes the value
141378** of the difference between the current element and the previous one plus
141379** two. For example, to store the position-list:
141380**
141381**     4 9 113
141382**
141383** the three varints:
141384**
141385**     6 7 106
141386**
141387** are encoded.
141388**
141389** When this function is called, *pp points to the start of an element of
141390** the list. *piPos contains the value of the previous entry in the list.
141391** After it returns, *piPos contains the value of the next element of the
141392** list and *pp is advanced to the following varint.
141393*/
141394static void fts3GetDeltaPosition(char **pp, int *piPos){
141395  int iVal;
141396  *pp += fts3GetVarint32(*pp, &iVal);
141397  *piPos += (iVal-2);
141398}
141399
141400/*
141401** Helper function for fts3ExprIterate() (see below).
141402*/
141403static int fts3ExprIterate2(
141404  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
141405  int *piPhrase,                  /* Pointer to phrase counter */
141406  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
141407  void *pCtx                      /* Second argument to pass to callback */
141408){
141409  int rc;                         /* Return code */
141410  int eType = pExpr->eType;       /* Type of expression node pExpr */
141411
141412  if( eType!=FTSQUERY_PHRASE ){
141413    assert( pExpr->pLeft && pExpr->pRight );
141414    rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
141415    if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
141416      rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
141417    }
141418  }else{
141419    rc = x(pExpr, *piPhrase, pCtx);
141420    (*piPhrase)++;
141421  }
141422  return rc;
141423}
141424
141425/*
141426** Iterate through all phrase nodes in an FTS3 query, except those that
141427** are part of a sub-tree that is the right-hand-side of a NOT operator.
141428** For each phrase node found, the supplied callback function is invoked.
141429**
141430** If the callback function returns anything other than SQLITE_OK,
141431** the iteration is abandoned and the error code returned immediately.
141432** Otherwise, SQLITE_OK is returned after a callback has been made for
141433** all eligible phrase nodes.
141434*/
141435static int fts3ExprIterate(
141436  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
141437  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
141438  void *pCtx                      /* Second argument to pass to callback */
141439){
141440  int iPhrase = 0;                /* Variable used as the phrase counter */
141441  return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
141442}
141443
141444/*
141445** This is an fts3ExprIterate() callback used while loading the doclists
141446** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
141447** fts3ExprLoadDoclists().
141448*/
141449static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
141450  int rc = SQLITE_OK;
141451  Fts3Phrase *pPhrase = pExpr->pPhrase;
141452  LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
141453
141454  UNUSED_PARAMETER(iPhrase);
141455
141456  p->nPhrase++;
141457  p->nToken += pPhrase->nToken;
141458
141459  return rc;
141460}
141461
141462/*
141463** Load the doclists for each phrase in the query associated with FTS3 cursor
141464** pCsr.
141465**
141466** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
141467** phrases in the expression (all phrases except those directly or
141468** indirectly descended from the right-hand-side of a NOT operator). If
141469** pnToken is not NULL, then it is set to the number of tokens in all
141470** matchable phrases of the expression.
141471*/
141472static int fts3ExprLoadDoclists(
141473  Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
141474  int *pnPhrase,                  /* OUT: Number of phrases in query */
141475  int *pnToken                    /* OUT: Number of tokens in query */
141476){
141477  int rc;                         /* Return Code */
141478  LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
141479  sCtx.pCsr = pCsr;
141480  rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
141481  if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
141482  if( pnToken ) *pnToken = sCtx.nToken;
141483  return rc;
141484}
141485
141486static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
141487  (*(int *)ctx)++;
141488  UNUSED_PARAMETER(pExpr);
141489  UNUSED_PARAMETER(iPhrase);
141490  return SQLITE_OK;
141491}
141492static int fts3ExprPhraseCount(Fts3Expr *pExpr){
141493  int nPhrase = 0;
141494  (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
141495  return nPhrase;
141496}
141497
141498/*
141499** Advance the position list iterator specified by the first two
141500** arguments so that it points to the first element with a value greater
141501** than or equal to parameter iNext.
141502*/
141503static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
141504  char *pIter = *ppIter;
141505  if( pIter ){
141506    int iIter = *piIter;
141507
141508    while( iIter<iNext ){
141509      if( 0==(*pIter & 0xFE) ){
141510        iIter = -1;
141511        pIter = 0;
141512        break;
141513      }
141514      fts3GetDeltaPosition(&pIter, &iIter);
141515    }
141516
141517    *piIter = iIter;
141518    *ppIter = pIter;
141519  }
141520}
141521
141522/*
141523** Advance the snippet iterator to the next candidate snippet.
141524*/
141525static int fts3SnippetNextCandidate(SnippetIter *pIter){
141526  int i;                          /* Loop counter */
141527
141528  if( pIter->iCurrent<0 ){
141529    /* The SnippetIter object has just been initialized. The first snippet
141530    ** candidate always starts at offset 0 (even if this candidate has a
141531    ** score of 0.0).
141532    */
141533    pIter->iCurrent = 0;
141534
141535    /* Advance the 'head' iterator of each phrase to the first offset that
141536    ** is greater than or equal to (iNext+nSnippet).
141537    */
141538    for(i=0; i<pIter->nPhrase; i++){
141539      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
141540      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
141541    }
141542  }else{
141543    int iStart;
141544    int iEnd = 0x7FFFFFFF;
141545
141546    for(i=0; i<pIter->nPhrase; i++){
141547      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
141548      if( pPhrase->pHead && pPhrase->iHead<iEnd ){
141549        iEnd = pPhrase->iHead;
141550      }
141551    }
141552    if( iEnd==0x7FFFFFFF ){
141553      return 1;
141554    }
141555
141556    pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
141557    for(i=0; i<pIter->nPhrase; i++){
141558      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
141559      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
141560      fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
141561    }
141562  }
141563
141564  return 0;
141565}
141566
141567/*
141568** Retrieve information about the current candidate snippet of snippet
141569** iterator pIter.
141570*/
141571static void fts3SnippetDetails(
141572  SnippetIter *pIter,             /* Snippet iterator */
141573  u64 mCovered,                   /* Bitmask of phrases already covered */
141574  int *piToken,                   /* OUT: First token of proposed snippet */
141575  int *piScore,                   /* OUT: "Score" for this snippet */
141576  u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
141577  u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
141578){
141579  int iStart = pIter->iCurrent;   /* First token of snippet */
141580  int iScore = 0;                 /* Score of this snippet */
141581  int i;                          /* Loop counter */
141582  u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
141583  u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
141584
141585  for(i=0; i<pIter->nPhrase; i++){
141586    SnippetPhrase *pPhrase = &pIter->aPhrase[i];
141587    if( pPhrase->pTail ){
141588      char *pCsr = pPhrase->pTail;
141589      int iCsr = pPhrase->iTail;
141590
141591      while( iCsr<(iStart+pIter->nSnippet) ){
141592        int j;
141593        u64 mPhrase = (u64)1 << i;
141594        u64 mPos = (u64)1 << (iCsr - iStart);
141595        assert( iCsr>=iStart );
141596        if( (mCover|mCovered)&mPhrase ){
141597          iScore++;
141598        }else{
141599          iScore += 1000;
141600        }
141601        mCover |= mPhrase;
141602
141603        for(j=0; j<pPhrase->nToken; j++){
141604          mHighlight |= (mPos>>j);
141605        }
141606
141607        if( 0==(*pCsr & 0x0FE) ) break;
141608        fts3GetDeltaPosition(&pCsr, &iCsr);
141609      }
141610    }
141611  }
141612
141613  /* Set the output variables before returning. */
141614  *piToken = iStart;
141615  *piScore = iScore;
141616  *pmCover = mCover;
141617  *pmHighlight = mHighlight;
141618}
141619
141620/*
141621** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
141622** Each invocation populates an element of the SnippetIter.aPhrase[] array.
141623*/
141624static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
141625  SnippetIter *p = (SnippetIter *)ctx;
141626  SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
141627  char *pCsr;
141628  int rc;
141629
141630  pPhrase->nToken = pExpr->pPhrase->nToken;
141631  rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
141632  assert( rc==SQLITE_OK || pCsr==0 );
141633  if( pCsr ){
141634    int iFirst = 0;
141635    pPhrase->pList = pCsr;
141636    fts3GetDeltaPosition(&pCsr, &iFirst);
141637    assert( iFirst>=0 );
141638    pPhrase->pHead = pCsr;
141639    pPhrase->pTail = pCsr;
141640    pPhrase->iHead = iFirst;
141641    pPhrase->iTail = iFirst;
141642  }else{
141643    assert( rc!=SQLITE_OK || (
141644       pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
141645    ));
141646  }
141647
141648  return rc;
141649}
141650
141651/*
141652** Select the fragment of text consisting of nFragment contiguous tokens
141653** from column iCol that represent the "best" snippet. The best snippet
141654** is the snippet with the highest score, where scores are calculated
141655** by adding:
141656**
141657**   (a) +1 point for each occurrence of a matchable phrase in the snippet.
141658**
141659**   (b) +1000 points for the first occurrence of each matchable phrase in
141660**       the snippet for which the corresponding mCovered bit is not set.
141661**
141662** The selected snippet parameters are stored in structure *pFragment before
141663** returning. The score of the selected snippet is stored in *piScore
141664** before returning.
141665*/
141666static int fts3BestSnippet(
141667  int nSnippet,                   /* Desired snippet length */
141668  Fts3Cursor *pCsr,               /* Cursor to create snippet for */
141669  int iCol,                       /* Index of column to create snippet from */
141670  u64 mCovered,                   /* Mask of phrases already covered */
141671  u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
141672  SnippetFragment *pFragment,     /* OUT: Best snippet found */
141673  int *piScore                    /* OUT: Score of snippet pFragment */
141674){
141675  int rc;                         /* Return Code */
141676  int nList;                      /* Number of phrases in expression */
141677  SnippetIter sIter;              /* Iterates through snippet candidates */
141678  int nByte;                      /* Number of bytes of space to allocate */
141679  int iBestScore = -1;            /* Best snippet score found so far */
141680  int i;                          /* Loop counter */
141681
141682  memset(&sIter, 0, sizeof(sIter));
141683
141684  /* Iterate through the phrases in the expression to count them. The same
141685  ** callback makes sure the doclists are loaded for each phrase.
141686  */
141687  rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
141688  if( rc!=SQLITE_OK ){
141689    return rc;
141690  }
141691
141692  /* Now that it is known how many phrases there are, allocate and zero
141693  ** the required space using malloc().
141694  */
141695  nByte = sizeof(SnippetPhrase) * nList;
141696  sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
141697  if( !sIter.aPhrase ){
141698    return SQLITE_NOMEM;
141699  }
141700  memset(sIter.aPhrase, 0, nByte);
141701
141702  /* Initialize the contents of the SnippetIter object. Then iterate through
141703  ** the set of phrases in the expression to populate the aPhrase[] array.
141704  */
141705  sIter.pCsr = pCsr;
141706  sIter.iCol = iCol;
141707  sIter.nSnippet = nSnippet;
141708  sIter.nPhrase = nList;
141709  sIter.iCurrent = -1;
141710  (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
141711
141712  /* Set the *pmSeen output variable. */
141713  for(i=0; i<nList; i++){
141714    if( sIter.aPhrase[i].pHead ){
141715      *pmSeen |= (u64)1 << i;
141716    }
141717  }
141718
141719  /* Loop through all candidate snippets. Store the best snippet in
141720  ** *pFragment. Store its associated 'score' in iBestScore.
141721  */
141722  pFragment->iCol = iCol;
141723  while( !fts3SnippetNextCandidate(&sIter) ){
141724    int iPos;
141725    int iScore;
141726    u64 mCover;
141727    u64 mHighlight;
141728    fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
141729    assert( iScore>=0 );
141730    if( iScore>iBestScore ){
141731      pFragment->iPos = iPos;
141732      pFragment->hlmask = mHighlight;
141733      pFragment->covered = mCover;
141734      iBestScore = iScore;
141735    }
141736  }
141737
141738  sqlite3_free(sIter.aPhrase);
141739  *piScore = iBestScore;
141740  return SQLITE_OK;
141741}
141742
141743
141744/*
141745** Append a string to the string-buffer passed as the first argument.
141746**
141747** If nAppend is negative, then the length of the string zAppend is
141748** determined using strlen().
141749*/
141750static int fts3StringAppend(
141751  StrBuffer *pStr,                /* Buffer to append to */
141752  const char *zAppend,            /* Pointer to data to append to buffer */
141753  int nAppend                     /* Size of zAppend in bytes (or -1) */
141754){
141755  if( nAppend<0 ){
141756    nAppend = (int)strlen(zAppend);
141757  }
141758
141759  /* If there is insufficient space allocated at StrBuffer.z, use realloc()
141760  ** to grow the buffer until so that it is big enough to accomadate the
141761  ** appended data.
141762  */
141763  if( pStr->n+nAppend+1>=pStr->nAlloc ){
141764    int nAlloc = pStr->nAlloc+nAppend+100;
141765    char *zNew = sqlite3_realloc(pStr->z, nAlloc);
141766    if( !zNew ){
141767      return SQLITE_NOMEM;
141768    }
141769    pStr->z = zNew;
141770    pStr->nAlloc = nAlloc;
141771  }
141772  assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
141773
141774  /* Append the data to the string buffer. */
141775  memcpy(&pStr->z[pStr->n], zAppend, nAppend);
141776  pStr->n += nAppend;
141777  pStr->z[pStr->n] = '\0';
141778
141779  return SQLITE_OK;
141780}
141781
141782/*
141783** The fts3BestSnippet() function often selects snippets that end with a
141784** query term. That is, the final term of the snippet is always a term
141785** that requires highlighting. For example, if 'X' is a highlighted term
141786** and '.' is a non-highlighted term, BestSnippet() may select:
141787**
141788**     ........X.....X
141789**
141790** This function "shifts" the beginning of the snippet forward in the
141791** document so that there are approximately the same number of
141792** non-highlighted terms to the right of the final highlighted term as there
141793** are to the left of the first highlighted term. For example, to this:
141794**
141795**     ....X.....X....
141796**
141797** This is done as part of extracting the snippet text, not when selecting
141798** the snippet. Snippet selection is done based on doclists only, so there
141799** is no way for fts3BestSnippet() to know whether or not the document
141800** actually contains terms that follow the final highlighted term.
141801*/
141802static int fts3SnippetShift(
141803  Fts3Table *pTab,                /* FTS3 table snippet comes from */
141804  int iLangid,                    /* Language id to use in tokenizing */
141805  int nSnippet,                   /* Number of tokens desired for snippet */
141806  const char *zDoc,               /* Document text to extract snippet from */
141807  int nDoc,                       /* Size of buffer zDoc in bytes */
141808  int *piPos,                     /* IN/OUT: First token of snippet */
141809  u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
141810){
141811  u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
141812
141813  if( hlmask ){
141814    int nLeft;                    /* Tokens to the left of first highlight */
141815    int nRight;                   /* Tokens to the right of last highlight */
141816    int nDesired;                 /* Ideal number of tokens to shift forward */
141817
141818    for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
141819    for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
141820    nDesired = (nLeft-nRight)/2;
141821
141822    /* Ideally, the start of the snippet should be pushed forward in the
141823    ** document nDesired tokens. This block checks if there are actually
141824    ** nDesired tokens to the right of the snippet. If so, *piPos and
141825    ** *pHlMask are updated to shift the snippet nDesired tokens to the
141826    ** right. Otherwise, the snippet is shifted by the number of tokens
141827    ** available.
141828    */
141829    if( nDesired>0 ){
141830      int nShift;                 /* Number of tokens to shift snippet by */
141831      int iCurrent = 0;           /* Token counter */
141832      int rc;                     /* Return Code */
141833      sqlite3_tokenizer_module *pMod;
141834      sqlite3_tokenizer_cursor *pC;
141835      pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
141836
141837      /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
141838      ** or more tokens in zDoc/nDoc.
141839      */
141840      rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
141841      if( rc!=SQLITE_OK ){
141842        return rc;
141843      }
141844      while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
141845        const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
141846        rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
141847      }
141848      pMod->xClose(pC);
141849      if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
141850
141851      nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
141852      assert( nShift<=nDesired );
141853      if( nShift>0 ){
141854        *piPos += nShift;
141855        *pHlmask = hlmask >> nShift;
141856      }
141857    }
141858  }
141859  return SQLITE_OK;
141860}
141861
141862/*
141863** Extract the snippet text for fragment pFragment from cursor pCsr and
141864** append it to string buffer pOut.
141865*/
141866static int fts3SnippetText(
141867  Fts3Cursor *pCsr,               /* FTS3 Cursor */
141868  SnippetFragment *pFragment,     /* Snippet to extract */
141869  int iFragment,                  /* Fragment number */
141870  int isLast,                     /* True for final fragment in snippet */
141871  int nSnippet,                   /* Number of tokens in extracted snippet */
141872  const char *zOpen,              /* String inserted before highlighted term */
141873  const char *zClose,             /* String inserted after highlighted term */
141874  const char *zEllipsis,          /* String inserted between snippets */
141875  StrBuffer *pOut                 /* Write output here */
141876){
141877  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
141878  int rc;                         /* Return code */
141879  const char *zDoc;               /* Document text to extract snippet from */
141880  int nDoc;                       /* Size of zDoc in bytes */
141881  int iCurrent = 0;               /* Current token number of document */
141882  int iEnd = 0;                   /* Byte offset of end of current token */
141883  int isShiftDone = 0;            /* True after snippet is shifted */
141884  int iPos = pFragment->iPos;     /* First token of snippet */
141885  u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
141886  int iCol = pFragment->iCol+1;   /* Query column to extract text from */
141887  sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
141888  sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
141889
141890  zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
141891  if( zDoc==0 ){
141892    if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
141893      return SQLITE_NOMEM;
141894    }
141895    return SQLITE_OK;
141896  }
141897  nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
141898
141899  /* Open a token cursor on the document. */
141900  pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
141901  rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
141902  if( rc!=SQLITE_OK ){
141903    return rc;
141904  }
141905
141906  while( rc==SQLITE_OK ){
141907    const char *ZDUMMY;           /* Dummy argument used with tokenizer */
141908    int DUMMY1 = -1;              /* Dummy argument used with tokenizer */
141909    int iBegin = 0;               /* Offset in zDoc of start of token */
141910    int iFin = 0;                 /* Offset in zDoc of end of token */
141911    int isHighlight = 0;          /* True for highlighted terms */
141912
141913    /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
141914    ** in the FTS code the variable that the third argument to xNext points to
141915    ** is initialized to zero before the first (*but not necessarily
141916    ** subsequent*) call to xNext(). This is done for a particular application
141917    ** that needs to know whether or not the tokenizer is being used for
141918    ** snippet generation or for some other purpose.
141919    **
141920    ** Extreme care is required when writing code to depend on this
141921    ** initialization. It is not a documented part of the tokenizer interface.
141922    ** If a tokenizer is used directly by any code outside of FTS, this
141923    ** convention might not be respected.  */
141924    rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
141925    if( rc!=SQLITE_OK ){
141926      if( rc==SQLITE_DONE ){
141927        /* Special case - the last token of the snippet is also the last token
141928        ** of the column. Append any punctuation that occurred between the end
141929        ** of the previous token and the end of the document to the output.
141930        ** Then break out of the loop. */
141931        rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
141932      }
141933      break;
141934    }
141935    if( iCurrent<iPos ){ continue; }
141936
141937    if( !isShiftDone ){
141938      int n = nDoc - iBegin;
141939      rc = fts3SnippetShift(
141940          pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
141941      );
141942      isShiftDone = 1;
141943
141944      /* Now that the shift has been done, check if the initial "..." are
141945      ** required. They are required if (a) this is not the first fragment,
141946      ** or (b) this fragment does not begin at position 0 of its column.
141947      */
141948      if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
141949        rc = fts3StringAppend(pOut, zEllipsis, -1);
141950      }
141951      if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
141952    }
141953
141954    if( iCurrent>=(iPos+nSnippet) ){
141955      if( isLast ){
141956        rc = fts3StringAppend(pOut, zEllipsis, -1);
141957      }
141958      break;
141959    }
141960
141961    /* Set isHighlight to true if this term should be highlighted. */
141962    isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
141963
141964    if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
141965    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
141966    if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
141967    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
141968
141969    iEnd = iFin;
141970  }
141971
141972  pMod->xClose(pC);
141973  return rc;
141974}
141975
141976
141977/*
141978** This function is used to count the entries in a column-list (a
141979** delta-encoded list of term offsets within a single column of a single
141980** row). When this function is called, *ppCollist should point to the
141981** beginning of the first varint in the column-list (the varint that
141982** contains the position of the first matching term in the column data).
141983** Before returning, *ppCollist is set to point to the first byte after
141984** the last varint in the column-list (either the 0x00 signifying the end
141985** of the position-list, or the 0x01 that precedes the column number of
141986** the next column in the position-list).
141987**
141988** The number of elements in the column-list is returned.
141989*/
141990static int fts3ColumnlistCount(char **ppCollist){
141991  char *pEnd = *ppCollist;
141992  char c = 0;
141993  int nEntry = 0;
141994
141995  /* A column-list is terminated by either a 0x01 or 0x00. */
141996  while( 0xFE & (*pEnd | c) ){
141997    c = *pEnd++ & 0x80;
141998    if( !c ) nEntry++;
141999  }
142000
142001  *ppCollist = pEnd;
142002  return nEntry;
142003}
142004
142005/*
142006** fts3ExprIterate() callback used to collect the "global" matchinfo stats
142007** for a single query.
142008**
142009** fts3ExprIterate() callback to load the 'global' elements of a
142010** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
142011** of the matchinfo array that are constant for all rows returned by the
142012** current query.
142013**
142014** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
142015** function populates Matchinfo.aMatchinfo[] as follows:
142016**
142017**   for(iCol=0; iCol<nCol; iCol++){
142018**     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
142019**     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
142020**   }
142021**
142022** where X is the number of matches for phrase iPhrase is column iCol of all
142023** rows of the table. Y is the number of rows for which column iCol contains
142024** at least one instance of phrase iPhrase.
142025**
142026** If the phrase pExpr consists entirely of deferred tokens, then all X and
142027** Y values are set to nDoc, where nDoc is the number of documents in the
142028** file system. This is done because the full-text index doclist is required
142029** to calculate these values properly, and the full-text index doclist is
142030** not available for deferred tokens.
142031*/
142032static int fts3ExprGlobalHitsCb(
142033  Fts3Expr *pExpr,                /* Phrase expression node */
142034  int iPhrase,                    /* Phrase number (numbered from zero) */
142035  void *pCtx                      /* Pointer to MatchInfo structure */
142036){
142037  MatchInfo *p = (MatchInfo *)pCtx;
142038  return sqlite3Fts3EvalPhraseStats(
142039      p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
142040  );
142041}
142042
142043/*
142044** fts3ExprIterate() callback used to collect the "local" part of the
142045** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
142046** array that are different for each row returned by the query.
142047*/
142048static int fts3ExprLocalHitsCb(
142049  Fts3Expr *pExpr,                /* Phrase expression node */
142050  int iPhrase,                    /* Phrase number */
142051  void *pCtx                      /* Pointer to MatchInfo structure */
142052){
142053  int rc = SQLITE_OK;
142054  MatchInfo *p = (MatchInfo *)pCtx;
142055  int iStart = iPhrase * p->nCol * 3;
142056  int i;
142057
142058  for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
142059    char *pCsr;
142060    rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
142061    if( pCsr ){
142062      p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
142063    }else{
142064      p->aMatchinfo[iStart+i*3] = 0;
142065    }
142066  }
142067
142068  return rc;
142069}
142070
142071static int fts3MatchinfoCheck(
142072  Fts3Table *pTab,
142073  char cArg,
142074  char **pzErr
142075){
142076  if( (cArg==FTS3_MATCHINFO_NPHRASE)
142077   || (cArg==FTS3_MATCHINFO_NCOL)
142078   || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
142079   || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
142080   || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
142081   || (cArg==FTS3_MATCHINFO_LCS)
142082   || (cArg==FTS3_MATCHINFO_HITS)
142083  ){
142084    return SQLITE_OK;
142085  }
142086  *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
142087  return SQLITE_ERROR;
142088}
142089
142090static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
142091  int nVal;                       /* Number of integers output by cArg */
142092
142093  switch( cArg ){
142094    case FTS3_MATCHINFO_NDOC:
142095    case FTS3_MATCHINFO_NPHRASE:
142096    case FTS3_MATCHINFO_NCOL:
142097      nVal = 1;
142098      break;
142099
142100    case FTS3_MATCHINFO_AVGLENGTH:
142101    case FTS3_MATCHINFO_LENGTH:
142102    case FTS3_MATCHINFO_LCS:
142103      nVal = pInfo->nCol;
142104      break;
142105
142106    default:
142107      assert( cArg==FTS3_MATCHINFO_HITS );
142108      nVal = pInfo->nCol * pInfo->nPhrase * 3;
142109      break;
142110  }
142111
142112  return nVal;
142113}
142114
142115static int fts3MatchinfoSelectDoctotal(
142116  Fts3Table *pTab,
142117  sqlite3_stmt **ppStmt,
142118  sqlite3_int64 *pnDoc,
142119  const char **paLen
142120){
142121  sqlite3_stmt *pStmt;
142122  const char *a;
142123  sqlite3_int64 nDoc;
142124
142125  if( !*ppStmt ){
142126    int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
142127    if( rc!=SQLITE_OK ) return rc;
142128  }
142129  pStmt = *ppStmt;
142130  assert( sqlite3_data_count(pStmt)==1 );
142131
142132  a = sqlite3_column_blob(pStmt, 0);
142133  a += sqlite3Fts3GetVarint(a, &nDoc);
142134  if( nDoc==0 ) return FTS_CORRUPT_VTAB;
142135  *pnDoc = (u32)nDoc;
142136
142137  if( paLen ) *paLen = a;
142138  return SQLITE_OK;
142139}
142140
142141/*
142142** An instance of the following structure is used to store state while
142143** iterating through a multi-column position-list corresponding to the
142144** hits for a single phrase on a single row in order to calculate the
142145** values for a matchinfo() FTS3_MATCHINFO_LCS request.
142146*/
142147typedef struct LcsIterator LcsIterator;
142148struct LcsIterator {
142149  Fts3Expr *pExpr;                /* Pointer to phrase expression */
142150  int iPosOffset;                 /* Tokens count up to end of this phrase */
142151  char *pRead;                    /* Cursor used to iterate through aDoclist */
142152  int iPos;                       /* Current position */
142153};
142154
142155/*
142156** If LcsIterator.iCol is set to the following value, the iterator has
142157** finished iterating through all offsets for all columns.
142158*/
142159#define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
142160
142161static int fts3MatchinfoLcsCb(
142162  Fts3Expr *pExpr,                /* Phrase expression node */
142163  int iPhrase,                    /* Phrase number (numbered from zero) */
142164  void *pCtx                      /* Pointer to MatchInfo structure */
142165){
142166  LcsIterator *aIter = (LcsIterator *)pCtx;
142167  aIter[iPhrase].pExpr = pExpr;
142168  return SQLITE_OK;
142169}
142170
142171/*
142172** Advance the iterator passed as an argument to the next position. Return
142173** 1 if the iterator is at EOF or if it now points to the start of the
142174** position list for the next column.
142175*/
142176static int fts3LcsIteratorAdvance(LcsIterator *pIter){
142177  char *pRead = pIter->pRead;
142178  sqlite3_int64 iRead;
142179  int rc = 0;
142180
142181  pRead += sqlite3Fts3GetVarint(pRead, &iRead);
142182  if( iRead==0 || iRead==1 ){
142183    pRead = 0;
142184    rc = 1;
142185  }else{
142186    pIter->iPos += (int)(iRead-2);
142187  }
142188
142189  pIter->pRead = pRead;
142190  return rc;
142191}
142192
142193/*
142194** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
142195**
142196** If the call is successful, the longest-common-substring lengths for each
142197** column are written into the first nCol elements of the pInfo->aMatchinfo[]
142198** array before returning. SQLITE_OK is returned in this case.
142199**
142200** Otherwise, if an error occurs, an SQLite error code is returned and the
142201** data written to the first nCol elements of pInfo->aMatchinfo[] is
142202** undefined.
142203*/
142204static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
142205  LcsIterator *aIter;
142206  int i;
142207  int iCol;
142208  int nToken = 0;
142209
142210  /* Allocate and populate the array of LcsIterator objects. The array
142211  ** contains one element for each matchable phrase in the query.
142212  **/
142213  aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
142214  if( !aIter ) return SQLITE_NOMEM;
142215  memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
142216  (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
142217
142218  for(i=0; i<pInfo->nPhrase; i++){
142219    LcsIterator *pIter = &aIter[i];
142220    nToken -= pIter->pExpr->pPhrase->nToken;
142221    pIter->iPosOffset = nToken;
142222  }
142223
142224  for(iCol=0; iCol<pInfo->nCol; iCol++){
142225    int nLcs = 0;                 /* LCS value for this column */
142226    int nLive = 0;                /* Number of iterators in aIter not at EOF */
142227
142228    for(i=0; i<pInfo->nPhrase; i++){
142229      int rc;
142230      LcsIterator *pIt = &aIter[i];
142231      rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
142232      if( rc!=SQLITE_OK ) return rc;
142233      if( pIt->pRead ){
142234        pIt->iPos = pIt->iPosOffset;
142235        fts3LcsIteratorAdvance(&aIter[i]);
142236        nLive++;
142237      }
142238    }
142239
142240    while( nLive>0 ){
142241      LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
142242      int nThisLcs = 0;           /* LCS for the current iterator positions */
142243
142244      for(i=0; i<pInfo->nPhrase; i++){
142245        LcsIterator *pIter = &aIter[i];
142246        if( pIter->pRead==0 ){
142247          /* This iterator is already at EOF for this column. */
142248          nThisLcs = 0;
142249        }else{
142250          if( pAdv==0 || pIter->iPos<pAdv->iPos ){
142251            pAdv = pIter;
142252          }
142253          if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
142254            nThisLcs++;
142255          }else{
142256            nThisLcs = 1;
142257          }
142258          if( nThisLcs>nLcs ) nLcs = nThisLcs;
142259        }
142260      }
142261      if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
142262    }
142263
142264    pInfo->aMatchinfo[iCol] = nLcs;
142265  }
142266
142267  sqlite3_free(aIter);
142268  return SQLITE_OK;
142269}
142270
142271/*
142272** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
142273** be returned by the matchinfo() function. Argument zArg contains the
142274** format string passed as the second argument to matchinfo (or the
142275** default value "pcx" if no second argument was specified). The format
142276** string has already been validated and the pInfo->aMatchinfo[] array
142277** is guaranteed to be large enough for the output.
142278**
142279** If bGlobal is true, then populate all fields of the matchinfo() output.
142280** If it is false, then assume that those fields that do not change between
142281** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
142282** have already been populated.
142283**
142284** Return SQLITE_OK if successful, or an SQLite error code if an error
142285** occurs. If a value other than SQLITE_OK is returned, the state the
142286** pInfo->aMatchinfo[] buffer is left in is undefined.
142287*/
142288static int fts3MatchinfoValues(
142289  Fts3Cursor *pCsr,               /* FTS3 cursor object */
142290  int bGlobal,                    /* True to grab the global stats */
142291  MatchInfo *pInfo,               /* Matchinfo context object */
142292  const char *zArg                /* Matchinfo format string */
142293){
142294  int rc = SQLITE_OK;
142295  int i;
142296  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
142297  sqlite3_stmt *pSelect = 0;
142298
142299  for(i=0; rc==SQLITE_OK && zArg[i]; i++){
142300
142301    switch( zArg[i] ){
142302      case FTS3_MATCHINFO_NPHRASE:
142303        if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
142304        break;
142305
142306      case FTS3_MATCHINFO_NCOL:
142307        if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
142308        break;
142309
142310      case FTS3_MATCHINFO_NDOC:
142311        if( bGlobal ){
142312          sqlite3_int64 nDoc = 0;
142313          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
142314          pInfo->aMatchinfo[0] = (u32)nDoc;
142315        }
142316        break;
142317
142318      case FTS3_MATCHINFO_AVGLENGTH:
142319        if( bGlobal ){
142320          sqlite3_int64 nDoc;     /* Number of rows in table */
142321          const char *a;          /* Aggregate column length array */
142322
142323          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
142324          if( rc==SQLITE_OK ){
142325            int iCol;
142326            for(iCol=0; iCol<pInfo->nCol; iCol++){
142327              u32 iVal;
142328              sqlite3_int64 nToken;
142329              a += sqlite3Fts3GetVarint(a, &nToken);
142330              iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
142331              pInfo->aMatchinfo[iCol] = iVal;
142332            }
142333          }
142334        }
142335        break;
142336
142337      case FTS3_MATCHINFO_LENGTH: {
142338        sqlite3_stmt *pSelectDocsize = 0;
142339        rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
142340        if( rc==SQLITE_OK ){
142341          int iCol;
142342          const char *a = sqlite3_column_blob(pSelectDocsize, 0);
142343          for(iCol=0; iCol<pInfo->nCol; iCol++){
142344            sqlite3_int64 nToken;
142345            a += sqlite3Fts3GetVarint(a, &nToken);
142346            pInfo->aMatchinfo[iCol] = (u32)nToken;
142347          }
142348        }
142349        sqlite3_reset(pSelectDocsize);
142350        break;
142351      }
142352
142353      case FTS3_MATCHINFO_LCS:
142354        rc = fts3ExprLoadDoclists(pCsr, 0, 0);
142355        if( rc==SQLITE_OK ){
142356          rc = fts3MatchinfoLcs(pCsr, pInfo);
142357        }
142358        break;
142359
142360      default: {
142361        Fts3Expr *pExpr;
142362        assert( zArg[i]==FTS3_MATCHINFO_HITS );
142363        pExpr = pCsr->pExpr;
142364        rc = fts3ExprLoadDoclists(pCsr, 0, 0);
142365        if( rc!=SQLITE_OK ) break;
142366        if( bGlobal ){
142367          if( pCsr->pDeferred ){
142368            rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
142369            if( rc!=SQLITE_OK ) break;
142370          }
142371          rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
142372          if( rc!=SQLITE_OK ) break;
142373        }
142374        (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
142375        break;
142376      }
142377    }
142378
142379    pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
142380  }
142381
142382  sqlite3_reset(pSelect);
142383  return rc;
142384}
142385
142386
142387/*
142388** Populate pCsr->aMatchinfo[] with data for the current row. The
142389** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
142390*/
142391static int fts3GetMatchinfo(
142392  Fts3Cursor *pCsr,               /* FTS3 Cursor object */
142393  const char *zArg                /* Second argument to matchinfo() function */
142394){
142395  MatchInfo sInfo;
142396  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
142397  int rc = SQLITE_OK;
142398  int bGlobal = 0;                /* Collect 'global' stats as well as local */
142399
142400  memset(&sInfo, 0, sizeof(MatchInfo));
142401  sInfo.pCursor = pCsr;
142402  sInfo.nCol = pTab->nColumn;
142403
142404  /* If there is cached matchinfo() data, but the format string for the
142405  ** cache does not match the format string for this request, discard
142406  ** the cached data. */
142407  if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
142408    assert( pCsr->aMatchinfo );
142409    sqlite3_free(pCsr->aMatchinfo);
142410    pCsr->zMatchinfo = 0;
142411    pCsr->aMatchinfo = 0;
142412  }
142413
142414  /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
142415  ** matchinfo function has been called for this query. In this case
142416  ** allocate the array used to accumulate the matchinfo data and
142417  ** initialize those elements that are constant for every row.
142418  */
142419  if( pCsr->aMatchinfo==0 ){
142420    int nMatchinfo = 0;           /* Number of u32 elements in match-info */
142421    int nArg;                     /* Bytes in zArg */
142422    int i;                        /* Used to iterate through zArg */
142423
142424    /* Determine the number of phrases in the query */
142425    pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
142426    sInfo.nPhrase = pCsr->nPhrase;
142427
142428    /* Determine the number of integers in the buffer returned by this call. */
142429    for(i=0; zArg[i]; i++){
142430      nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
142431    }
142432
142433    /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
142434    nArg = (int)strlen(zArg);
142435    pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
142436    if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
142437
142438    pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
142439    pCsr->nMatchinfo = nMatchinfo;
142440    memcpy(pCsr->zMatchinfo, zArg, nArg+1);
142441    memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
142442    pCsr->isMatchinfoNeeded = 1;
142443    bGlobal = 1;
142444  }
142445
142446  sInfo.aMatchinfo = pCsr->aMatchinfo;
142447  sInfo.nPhrase = pCsr->nPhrase;
142448  if( pCsr->isMatchinfoNeeded ){
142449    rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
142450    pCsr->isMatchinfoNeeded = 0;
142451  }
142452
142453  return rc;
142454}
142455
142456/*
142457** Implementation of snippet() function.
142458*/
142459SQLITE_PRIVATE void sqlite3Fts3Snippet(
142460  sqlite3_context *pCtx,          /* SQLite function call context */
142461  Fts3Cursor *pCsr,               /* Cursor object */
142462  const char *zStart,             /* Snippet start text - "<b>" */
142463  const char *zEnd,               /* Snippet end text - "</b>" */
142464  const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
142465  int iCol,                       /* Extract snippet from this column */
142466  int nToken                      /* Approximate number of tokens in snippet */
142467){
142468  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
142469  int rc = SQLITE_OK;
142470  int i;
142471  StrBuffer res = {0, 0, 0};
142472
142473  /* The returned text includes up to four fragments of text extracted from
142474  ** the data in the current row. The first iteration of the for(...) loop
142475  ** below attempts to locate a single fragment of text nToken tokens in
142476  ** size that contains at least one instance of all phrases in the query
142477  ** expression that appear in the current row. If such a fragment of text
142478  ** cannot be found, the second iteration of the loop attempts to locate
142479  ** a pair of fragments, and so on.
142480  */
142481  int nSnippet = 0;               /* Number of fragments in this snippet */
142482  SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
142483  int nFToken = -1;               /* Number of tokens in each fragment */
142484
142485  if( !pCsr->pExpr ){
142486    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
142487    return;
142488  }
142489
142490  for(nSnippet=1; 1; nSnippet++){
142491
142492    int iSnip;                    /* Loop counter 0..nSnippet-1 */
142493    u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
142494    u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
142495
142496    if( nToken>=0 ){
142497      nFToken = (nToken+nSnippet-1) / nSnippet;
142498    }else{
142499      nFToken = -1 * nToken;
142500    }
142501
142502    for(iSnip=0; iSnip<nSnippet; iSnip++){
142503      int iBestScore = -1;        /* Best score of columns checked so far */
142504      int iRead;                  /* Used to iterate through columns */
142505      SnippetFragment *pFragment = &aSnippet[iSnip];
142506
142507      memset(pFragment, 0, sizeof(*pFragment));
142508
142509      /* Loop through all columns of the table being considered for snippets.
142510      ** If the iCol argument to this function was negative, this means all
142511      ** columns of the FTS3 table. Otherwise, only column iCol is considered.
142512      */
142513      for(iRead=0; iRead<pTab->nColumn; iRead++){
142514        SnippetFragment sF = {0, 0, 0, 0};
142515        int iS;
142516        if( iCol>=0 && iRead!=iCol ) continue;
142517
142518        /* Find the best snippet of nFToken tokens in column iRead. */
142519        rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
142520        if( rc!=SQLITE_OK ){
142521          goto snippet_out;
142522        }
142523        if( iS>iBestScore ){
142524          *pFragment = sF;
142525          iBestScore = iS;
142526        }
142527      }
142528
142529      mCovered |= pFragment->covered;
142530    }
142531
142532    /* If all query phrases seen by fts3BestSnippet() are present in at least
142533    ** one of the nSnippet snippet fragments, break out of the loop.
142534    */
142535    assert( (mCovered&mSeen)==mCovered );
142536    if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
142537  }
142538
142539  assert( nFToken>0 );
142540
142541  for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
142542    rc = fts3SnippetText(pCsr, &aSnippet[i],
142543        i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
142544    );
142545  }
142546
142547 snippet_out:
142548  sqlite3Fts3SegmentsClose(pTab);
142549  if( rc!=SQLITE_OK ){
142550    sqlite3_result_error_code(pCtx, rc);
142551    sqlite3_free(res.z);
142552  }else{
142553    sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
142554  }
142555}
142556
142557
142558typedef struct TermOffset TermOffset;
142559typedef struct TermOffsetCtx TermOffsetCtx;
142560
142561struct TermOffset {
142562  char *pList;                    /* Position-list */
142563  int iPos;                       /* Position just read from pList */
142564  int iOff;                       /* Offset of this term from read positions */
142565};
142566
142567struct TermOffsetCtx {
142568  Fts3Cursor *pCsr;
142569  int iCol;                       /* Column of table to populate aTerm for */
142570  int iTerm;
142571  sqlite3_int64 iDocid;
142572  TermOffset *aTerm;
142573};
142574
142575/*
142576** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
142577*/
142578static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
142579  TermOffsetCtx *p = (TermOffsetCtx *)ctx;
142580  int nTerm;                      /* Number of tokens in phrase */
142581  int iTerm;                      /* For looping through nTerm phrase terms */
142582  char *pList;                    /* Pointer to position list for phrase */
142583  int iPos = 0;                   /* First position in position-list */
142584  int rc;
142585
142586  UNUSED_PARAMETER(iPhrase);
142587  rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
142588  nTerm = pExpr->pPhrase->nToken;
142589  if( pList ){
142590    fts3GetDeltaPosition(&pList, &iPos);
142591    assert( iPos>=0 );
142592  }
142593
142594  for(iTerm=0; iTerm<nTerm; iTerm++){
142595    TermOffset *pT = &p->aTerm[p->iTerm++];
142596    pT->iOff = nTerm-iTerm-1;
142597    pT->pList = pList;
142598    pT->iPos = iPos;
142599  }
142600
142601  return rc;
142602}
142603
142604/*
142605** Implementation of offsets() function.
142606*/
142607SQLITE_PRIVATE void sqlite3Fts3Offsets(
142608  sqlite3_context *pCtx,          /* SQLite function call context */
142609  Fts3Cursor *pCsr                /* Cursor object */
142610){
142611  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
142612  sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
142613  int rc;                         /* Return Code */
142614  int nToken;                     /* Number of tokens in query */
142615  int iCol;                       /* Column currently being processed */
142616  StrBuffer res = {0, 0, 0};      /* Result string */
142617  TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
142618
142619  if( !pCsr->pExpr ){
142620    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
142621    return;
142622  }
142623
142624  memset(&sCtx, 0, sizeof(sCtx));
142625  assert( pCsr->isRequireSeek==0 );
142626
142627  /* Count the number of terms in the query */
142628  rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
142629  if( rc!=SQLITE_OK ) goto offsets_out;
142630
142631  /* Allocate the array of TermOffset iterators. */
142632  sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
142633  if( 0==sCtx.aTerm ){
142634    rc = SQLITE_NOMEM;
142635    goto offsets_out;
142636  }
142637  sCtx.iDocid = pCsr->iPrevId;
142638  sCtx.pCsr = pCsr;
142639
142640  /* Loop through the table columns, appending offset information to
142641  ** string-buffer res for each column.
142642  */
142643  for(iCol=0; iCol<pTab->nColumn; iCol++){
142644    sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
142645    const char *ZDUMMY;           /* Dummy argument used with xNext() */
142646    int NDUMMY = 0;               /* Dummy argument used with xNext() */
142647    int iStart = 0;
142648    int iEnd = 0;
142649    int iCurrent = 0;
142650    const char *zDoc;
142651    int nDoc;
142652
142653    /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
142654    ** no way that this operation can fail, so the return code from
142655    ** fts3ExprIterate() can be discarded.
142656    */
142657    sCtx.iCol = iCol;
142658    sCtx.iTerm = 0;
142659    (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
142660
142661    /* Retreive the text stored in column iCol. If an SQL NULL is stored
142662    ** in column iCol, jump immediately to the next iteration of the loop.
142663    ** If an OOM occurs while retrieving the data (this can happen if SQLite
142664    ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
142665    ** to the caller.
142666    */
142667    zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
142668    nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
142669    if( zDoc==0 ){
142670      if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
142671        continue;
142672      }
142673      rc = SQLITE_NOMEM;
142674      goto offsets_out;
142675    }
142676
142677    /* Initialize a tokenizer iterator to iterate through column iCol. */
142678    rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
142679        zDoc, nDoc, &pC
142680    );
142681    if( rc!=SQLITE_OK ) goto offsets_out;
142682
142683    rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
142684    while( rc==SQLITE_OK ){
142685      int i;                      /* Used to loop through terms */
142686      int iMinPos = 0x7FFFFFFF;   /* Position of next token */
142687      TermOffset *pTerm = 0;      /* TermOffset associated with next token */
142688
142689      for(i=0; i<nToken; i++){
142690        TermOffset *pT = &sCtx.aTerm[i];
142691        if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
142692          iMinPos = pT->iPos-pT->iOff;
142693          pTerm = pT;
142694        }
142695      }
142696
142697      if( !pTerm ){
142698        /* All offsets for this column have been gathered. */
142699        rc = SQLITE_DONE;
142700      }else{
142701        assert( iCurrent<=iMinPos );
142702        if( 0==(0xFE&*pTerm->pList) ){
142703          pTerm->pList = 0;
142704        }else{
142705          fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
142706        }
142707        while( rc==SQLITE_OK && iCurrent<iMinPos ){
142708          rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
142709        }
142710        if( rc==SQLITE_OK ){
142711          char aBuffer[64];
142712          sqlite3_snprintf(sizeof(aBuffer), aBuffer,
142713              "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
142714          );
142715          rc = fts3StringAppend(&res, aBuffer, -1);
142716        }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
142717          rc = FTS_CORRUPT_VTAB;
142718        }
142719      }
142720    }
142721    if( rc==SQLITE_DONE ){
142722      rc = SQLITE_OK;
142723    }
142724
142725    pMod->xClose(pC);
142726    if( rc!=SQLITE_OK ) goto offsets_out;
142727  }
142728
142729 offsets_out:
142730  sqlite3_free(sCtx.aTerm);
142731  assert( rc!=SQLITE_DONE );
142732  sqlite3Fts3SegmentsClose(pTab);
142733  if( rc!=SQLITE_OK ){
142734    sqlite3_result_error_code(pCtx,  rc);
142735    sqlite3_free(res.z);
142736  }else{
142737    sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
142738  }
142739  return;
142740}
142741
142742/*
142743** Implementation of matchinfo() function.
142744*/
142745SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
142746  sqlite3_context *pContext,      /* Function call context */
142747  Fts3Cursor *pCsr,               /* FTS3 table cursor */
142748  const char *zArg                /* Second arg to matchinfo() function */
142749){
142750  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
142751  int rc;
142752  int i;
142753  const char *zFormat;
142754
142755  if( zArg ){
142756    for(i=0; zArg[i]; i++){
142757      char *zErr = 0;
142758      if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
142759        sqlite3_result_error(pContext, zErr, -1);
142760        sqlite3_free(zErr);
142761        return;
142762      }
142763    }
142764    zFormat = zArg;
142765  }else{
142766    zFormat = FTS3_MATCHINFO_DEFAULT;
142767  }
142768
142769  if( !pCsr->pExpr ){
142770    sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
142771    return;
142772  }
142773
142774  /* Retrieve matchinfo() data. */
142775  rc = fts3GetMatchinfo(pCsr, zFormat);
142776  sqlite3Fts3SegmentsClose(pTab);
142777
142778  if( rc!=SQLITE_OK ){
142779    sqlite3_result_error_code(pContext, rc);
142780  }else{
142781    int n = pCsr->nMatchinfo * sizeof(u32);
142782    sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
142783  }
142784}
142785
142786#endif
142787
142788/************** End of fts3_snippet.c ****************************************/
142789/************** Begin file fts3_unicode.c ************************************/
142790/*
142791** 2012 May 24
142792**
142793** The author disclaims copyright to this source code.  In place of
142794** a legal notice, here is a blessing:
142795**
142796**    May you do good and not evil.
142797**    May you find forgiveness for yourself and forgive others.
142798**    May you share freely, never taking more than you give.
142799**
142800******************************************************************************
142801**
142802** Implementation of the "unicode" full-text-search tokenizer.
142803*/
142804
142805#ifdef SQLITE_ENABLE_FTS4_UNICODE61
142806
142807#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
142808
142809/* #include <assert.h> */
142810/* #include <stdlib.h> */
142811/* #include <stdio.h> */
142812/* #include <string.h> */
142813
142814
142815/*
142816** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
142817** from the sqlite3 source file utf.c. If this file is compiled as part
142818** of the amalgamation, they are not required.
142819*/
142820#ifndef SQLITE_AMALGAMATION
142821
142822static const unsigned char sqlite3Utf8Trans1[] = {
142823  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
142824  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
142825  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
142826  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
142827  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
142828  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
142829  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
142830  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
142831};
142832
142833#define READ_UTF8(zIn, zTerm, c)                           \
142834  c = *(zIn++);                                            \
142835  if( c>=0xc0 ){                                           \
142836    c = sqlite3Utf8Trans1[c-0xc0];                         \
142837    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
142838      c = (c<<6) + (0x3f & *(zIn++));                      \
142839    }                                                      \
142840    if( c<0x80                                             \
142841        || (c&0xFFFFF800)==0xD800                          \
142842        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
142843  }
142844
142845#define WRITE_UTF8(zOut, c) {                          \
142846  if( c<0x00080 ){                                     \
142847    *zOut++ = (u8)(c&0xFF);                            \
142848  }                                                    \
142849  else if( c<0x00800 ){                                \
142850    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
142851    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
142852  }                                                    \
142853  else if( c<0x10000 ){                                \
142854    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
142855    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
142856    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
142857  }else{                                               \
142858    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
142859    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
142860    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
142861    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
142862  }                                                    \
142863}
142864
142865#endif /* ifndef SQLITE_AMALGAMATION */
142866
142867typedef struct unicode_tokenizer unicode_tokenizer;
142868typedef struct unicode_cursor unicode_cursor;
142869
142870struct unicode_tokenizer {
142871  sqlite3_tokenizer base;
142872  int bRemoveDiacritic;
142873  int nException;
142874  int *aiException;
142875};
142876
142877struct unicode_cursor {
142878  sqlite3_tokenizer_cursor base;
142879  const unsigned char *aInput;    /* Input text being tokenized */
142880  int nInput;                     /* Size of aInput[] in bytes */
142881  int iOff;                       /* Current offset within aInput[] */
142882  int iToken;                     /* Index of next token to be returned */
142883  char *zToken;                   /* storage for current token */
142884  int nAlloc;                     /* space allocated at zToken */
142885};
142886
142887
142888/*
142889** Destroy a tokenizer allocated by unicodeCreate().
142890*/
142891static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
142892  if( pTokenizer ){
142893    unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
142894    sqlite3_free(p->aiException);
142895    sqlite3_free(p);
142896  }
142897  return SQLITE_OK;
142898}
142899
142900/*
142901** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
142902** statement has specified that the tokenizer for this table shall consider
142903** all characters in string zIn/nIn to be separators (if bAlnum==0) or
142904** token characters (if bAlnum==1).
142905**
142906** For each codepoint in the zIn/nIn string, this function checks if the
142907** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
142908** If so, no action is taken. Otherwise, the codepoint is added to the
142909** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
142910** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
142911** codepoints in the aiException[] array.
142912**
142913** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
142914** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
142915** It is not possible to change the behavior of the tokenizer with respect
142916** to these codepoints.
142917*/
142918static int unicodeAddExceptions(
142919  unicode_tokenizer *p,           /* Tokenizer to add exceptions to */
142920  int bAlnum,                     /* Replace Isalnum() return value with this */
142921  const char *zIn,                /* Array of characters to make exceptions */
142922  int nIn                         /* Length of z in bytes */
142923){
142924  const unsigned char *z = (const unsigned char *)zIn;
142925  const unsigned char *zTerm = &z[nIn];
142926  int iCode;
142927  int nEntry = 0;
142928
142929  assert( bAlnum==0 || bAlnum==1 );
142930
142931  while( z<zTerm ){
142932    READ_UTF8(z, zTerm, iCode);
142933    assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
142934    if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
142935     && sqlite3FtsUnicodeIsdiacritic(iCode)==0
142936    ){
142937      nEntry++;
142938    }
142939  }
142940
142941  if( nEntry ){
142942    int *aNew;                    /* New aiException[] array */
142943    int nNew;                     /* Number of valid entries in array aNew[] */
142944
142945    aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
142946    if( aNew==0 ) return SQLITE_NOMEM;
142947    nNew = p->nException;
142948
142949    z = (const unsigned char *)zIn;
142950    while( z<zTerm ){
142951      READ_UTF8(z, zTerm, iCode);
142952      if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
142953       && sqlite3FtsUnicodeIsdiacritic(iCode)==0
142954      ){
142955        int i, j;
142956        for(i=0; i<nNew && aNew[i]<iCode; i++);
142957        for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
142958        aNew[i] = iCode;
142959        nNew++;
142960      }
142961    }
142962    p->aiException = aNew;
142963    p->nException = nNew;
142964  }
142965
142966  return SQLITE_OK;
142967}
142968
142969/*
142970** Return true if the p->aiException[] array contains the value iCode.
142971*/
142972static int unicodeIsException(unicode_tokenizer *p, int iCode){
142973  if( p->nException>0 ){
142974    int *a = p->aiException;
142975    int iLo = 0;
142976    int iHi = p->nException-1;
142977
142978    while( iHi>=iLo ){
142979      int iTest = (iHi + iLo) / 2;
142980      if( iCode==a[iTest] ){
142981        return 1;
142982      }else if( iCode>a[iTest] ){
142983        iLo = iTest+1;
142984      }else{
142985        iHi = iTest-1;
142986      }
142987    }
142988  }
142989
142990  return 0;
142991}
142992
142993/*
142994** Return true if, for the purposes of tokenization, codepoint iCode is
142995** considered a token character (not a separator).
142996*/
142997static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
142998  assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
142999  return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
143000}
143001
143002/*
143003** Create a new tokenizer instance.
143004*/
143005static int unicodeCreate(
143006  int nArg,                       /* Size of array argv[] */
143007  const char * const *azArg,      /* Tokenizer creation arguments */
143008  sqlite3_tokenizer **pp          /* OUT: New tokenizer handle */
143009){
143010  unicode_tokenizer *pNew;        /* New tokenizer object */
143011  int i;
143012  int rc = SQLITE_OK;
143013
143014  pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
143015  if( pNew==NULL ) return SQLITE_NOMEM;
143016  memset(pNew, 0, sizeof(unicode_tokenizer));
143017  pNew->bRemoveDiacritic = 1;
143018
143019  for(i=0; rc==SQLITE_OK && i<nArg; i++){
143020    const char *z = azArg[i];
143021    int n = strlen(z);
143022
143023    if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
143024      pNew->bRemoveDiacritic = 1;
143025    }
143026    else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
143027      pNew->bRemoveDiacritic = 0;
143028    }
143029    else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
143030      rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
143031    }
143032    else if( n>=11 && memcmp("separators=", z, 11)==0 ){
143033      rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
143034    }
143035    else{
143036      /* Unrecognized argument */
143037      rc  = SQLITE_ERROR;
143038    }
143039  }
143040
143041  if( rc!=SQLITE_OK ){
143042    unicodeDestroy((sqlite3_tokenizer *)pNew);
143043    pNew = 0;
143044  }
143045  *pp = (sqlite3_tokenizer *)pNew;
143046  return rc;
143047}
143048
143049/*
143050** Prepare to begin tokenizing a particular string.  The input
143051** string to be tokenized is pInput[0..nBytes-1].  A cursor
143052** used to incrementally tokenize this string is returned in
143053** *ppCursor.
143054*/
143055static int unicodeOpen(
143056  sqlite3_tokenizer *p,           /* The tokenizer */
143057  const char *aInput,             /* Input string */
143058  int nInput,                     /* Size of string aInput in bytes */
143059  sqlite3_tokenizer_cursor **pp   /* OUT: New cursor object */
143060){
143061  unicode_cursor *pCsr;
143062
143063  pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
143064  if( pCsr==0 ){
143065    return SQLITE_NOMEM;
143066  }
143067  memset(pCsr, 0, sizeof(unicode_cursor));
143068
143069  pCsr->aInput = (const unsigned char *)aInput;
143070  if( aInput==0 ){
143071    pCsr->nInput = 0;
143072  }else if( nInput<0 ){
143073    pCsr->nInput = (int)strlen(aInput);
143074  }else{
143075    pCsr->nInput = nInput;
143076  }
143077
143078  *pp = &pCsr->base;
143079  UNUSED_PARAMETER(p);
143080  return SQLITE_OK;
143081}
143082
143083/*
143084** Close a tokenization cursor previously opened by a call to
143085** simpleOpen() above.
143086*/
143087static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
143088  unicode_cursor *pCsr = (unicode_cursor *) pCursor;
143089  sqlite3_free(pCsr->zToken);
143090  sqlite3_free(pCsr);
143091  return SQLITE_OK;
143092}
143093
143094/*
143095** Extract the next token from a tokenization cursor.  The cursor must
143096** have been opened by a prior call to simpleOpen().
143097*/
143098static int unicodeNext(
143099  sqlite3_tokenizer_cursor *pC,   /* Cursor returned by simpleOpen */
143100  const char **paToken,           /* OUT: Token text */
143101  int *pnToken,                   /* OUT: Number of bytes at *paToken */
143102  int *piStart,                   /* OUT: Starting offset of token */
143103  int *piEnd,                     /* OUT: Ending offset of token */
143104  int *piPos                      /* OUT: Position integer of token */
143105){
143106  unicode_cursor *pCsr = (unicode_cursor *)pC;
143107  unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
143108  int iCode;
143109  char *zOut;
143110  const unsigned char *z = &pCsr->aInput[pCsr->iOff];
143111  const unsigned char *zStart = z;
143112  const unsigned char *zEnd;
143113  const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
143114
143115  /* Scan past any delimiter characters before the start of the next token.
143116  ** Return SQLITE_DONE early if this takes us all the way to the end of
143117  ** the input.  */
143118  while( z<zTerm ){
143119    READ_UTF8(z, zTerm, iCode);
143120    if( unicodeIsAlnum(p, iCode) ) break;
143121    zStart = z;
143122  }
143123  if( zStart>=zTerm ) return SQLITE_DONE;
143124
143125  zOut = pCsr->zToken;
143126  do {
143127    int iOut;
143128
143129    /* Grow the output buffer if required. */
143130    if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
143131      char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
143132      if( !zNew ) return SQLITE_NOMEM;
143133      zOut = &zNew[zOut - pCsr->zToken];
143134      pCsr->zToken = zNew;
143135      pCsr->nAlloc += 64;
143136    }
143137
143138    /* Write the folded case of the last character read to the output */
143139    zEnd = z;
143140    iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
143141    if( iOut ){
143142      WRITE_UTF8(zOut, iOut);
143143    }
143144
143145    /* If the cursor is not at EOF, read the next character */
143146    if( z>=zTerm ) break;
143147    READ_UTF8(z, zTerm, iCode);
143148  }while( unicodeIsAlnum(p, iCode)
143149       || sqlite3FtsUnicodeIsdiacritic(iCode)
143150  );
143151
143152  /* Set the output variables and return. */
143153  pCsr->iOff = (z - pCsr->aInput);
143154  *paToken = pCsr->zToken;
143155  *pnToken = zOut - pCsr->zToken;
143156  *piStart = (zStart - pCsr->aInput);
143157  *piEnd = (zEnd - pCsr->aInput);
143158  *piPos = pCsr->iToken++;
143159  return SQLITE_OK;
143160}
143161
143162/*
143163** Set *ppModule to a pointer to the sqlite3_tokenizer_module
143164** structure for the unicode tokenizer.
143165*/
143166SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
143167  static const sqlite3_tokenizer_module module = {
143168    0,
143169    unicodeCreate,
143170    unicodeDestroy,
143171    unicodeOpen,
143172    unicodeClose,
143173    unicodeNext,
143174    0,
143175  };
143176  *ppModule = &module;
143177}
143178
143179#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
143180#endif /* ifndef SQLITE_ENABLE_FTS4_UNICODE61 */
143181
143182/************** End of fts3_unicode.c ****************************************/
143183/************** Begin file fts3_unicode2.c ***********************************/
143184/*
143185** 2012 May 25
143186**
143187** The author disclaims copyright to this source code.  In place of
143188** a legal notice, here is a blessing:
143189**
143190**    May you do good and not evil.
143191**    May you find forgiveness for yourself and forgive others.
143192**    May you share freely, never taking more than you give.
143193**
143194******************************************************************************
143195*/
143196
143197/*
143198** DO NOT EDIT THIS MACHINE GENERATED FILE.
143199*/
143200
143201#if defined(SQLITE_ENABLE_FTS4_UNICODE61)
143202#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
143203
143204/* #include <assert.h> */
143205
143206/*
143207** Return true if the argument corresponds to a unicode codepoint
143208** classified as either a letter or a number. Otherwise false.
143209**
143210** The results are undefined if the value passed to this function
143211** is less than zero.
143212*/
143213SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
143214  /* Each unsigned integer in the following array corresponds to a contiguous
143215  ** range of unicode codepoints that are not either letters or numbers (i.e.
143216  ** codepoints for which this function should return 0).
143217  **
143218  ** The most significant 22 bits in each 32-bit value contain the first
143219  ** codepoint in the range. The least significant 10 bits are used to store
143220  ** the size of the range (always at least 1). In other words, the value
143221  ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
143222  ** C. It is not possible to represent a range larger than 1023 codepoints
143223  ** using this format.
143224  */
143225  const static unsigned int aEntry[] = {
143226    0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
143227    0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
143228    0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
143229    0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
143230    0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
143231    0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
143232    0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
143233    0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
143234    0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
143235    0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
143236    0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
143237    0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
143238    0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
143239    0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
143240    0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
143241    0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
143242    0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
143243    0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
143244    0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
143245    0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
143246    0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
143247    0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
143248    0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
143249    0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
143250    0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
143251    0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
143252    0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
143253    0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
143254    0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
143255    0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
143256    0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
143257    0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
143258    0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
143259    0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
143260    0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
143261    0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
143262    0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
143263    0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
143264    0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
143265    0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
143266    0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
143267    0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
143268    0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
143269    0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
143270    0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
143271    0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
143272    0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
143273    0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
143274    0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
143275    0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
143276    0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
143277    0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
143278    0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
143279    0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
143280    0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
143281    0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
143282    0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
143283    0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
143284    0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
143285    0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
143286    0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
143287    0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
143288    0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
143289    0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
143290    0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
143291    0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
143292    0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
143293    0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
143294    0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
143295    0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
143296    0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
143297    0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
143298    0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
143299    0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
143300    0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
143301    0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
143302    0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
143303    0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
143304    0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
143305    0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
143306    0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
143307    0x380400F0,
143308  };
143309  static const unsigned int aAscii[4] = {
143310    0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
143311  };
143312
143313  if( c<128 ){
143314    return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
143315  }else if( c<(1<<22) ){
143316    unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
143317    int iRes;
143318    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
143319    int iLo = 0;
143320    while( iHi>=iLo ){
143321      int iTest = (iHi + iLo) / 2;
143322      if( key >= aEntry[iTest] ){
143323        iRes = iTest;
143324        iLo = iTest+1;
143325      }else{
143326        iHi = iTest-1;
143327      }
143328    }
143329    assert( aEntry[0]<key );
143330    assert( key>=aEntry[iRes] );
143331    return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
143332  }
143333  return 1;
143334}
143335
143336
143337/*
143338** If the argument is a codepoint corresponding to a lowercase letter
143339** in the ASCII range with a diacritic added, return the codepoint
143340** of the ASCII letter only. For example, if passed 235 - "LATIN
143341** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
143342** E"). The resuls of passing a codepoint that corresponds to an
143343** uppercase letter are undefined.
143344*/
143345static int remove_diacritic(int c){
143346  unsigned short aDia[] = {
143347        0,  1797,  1848,  1859,  1891,  1928,  1940,  1995,
143348     2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286,
143349     2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732,
143350     2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336,
143351     3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928,
143352     3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234,
143353     4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504,
143354     6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529,
143355    61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
143356    61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
143357    62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
143358    62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
143359    62924, 63050, 63082, 63274, 63390,
143360  };
143361  char aChar[] = {
143362    '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',
143363    'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',
143364    's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',
143365    'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',
143366    'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0',
143367    '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',
143368    'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',
143369    'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',
143370    'e',  'i',  'o',  'u',  'y',
143371  };
143372
143373  unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
143374  int iRes = 0;
143375  int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
143376  int iLo = 0;
143377  while( iHi>=iLo ){
143378    int iTest = (iHi + iLo) / 2;
143379    if( key >= aDia[iTest] ){
143380      iRes = iTest;
143381      iLo = iTest+1;
143382    }else{
143383      iHi = iTest-1;
143384    }
143385  }
143386  assert( key>=aDia[iRes] );
143387  return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
143388};
143389
143390
143391/*
143392** Return true if the argument interpreted as a unicode codepoint
143393** is a diacritical modifier character.
143394*/
143395SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
143396  unsigned int mask0 = 0x08029FDF;
143397  unsigned int mask1 = 0x000361F8;
143398  if( c<768 || c>817 ) return 0;
143399  return (c < 768+32) ?
143400      (mask0 & (1 << (c-768))) :
143401      (mask1 & (1 << (c-768-32)));
143402}
143403
143404
143405/*
143406** Interpret the argument as a unicode codepoint. If the codepoint
143407** is an upper case character that has a lower case equivalent,
143408** return the codepoint corresponding to the lower case version.
143409** Otherwise, return a copy of the argument.
143410**
143411** The results are undefined if the value passed to this function
143412** is less than zero.
143413*/
143414SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
143415  /* Each entry in the following array defines a rule for folding a range
143416  ** of codepoints to lower case. The rule applies to a range of nRange
143417  ** codepoints starting at codepoint iCode.
143418  **
143419  ** If the least significant bit in flags is clear, then the rule applies
143420  ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
143421  ** need to be folded). Or, if it is set, then the rule only applies to
143422  ** every second codepoint in the range, starting with codepoint C.
143423  **
143424  ** The 7 most significant bits in flags are an index into the aiOff[]
143425  ** array. If a specific codepoint C does require folding, then its lower
143426  ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
143427  **
143428  ** The contents of this array are generated by parsing the CaseFolding.txt
143429  ** file distributed as part of the "Unicode Character Database". See
143430  ** http://www.unicode.org for details.
143431  */
143432  static const struct TableEntry {
143433    unsigned short iCode;
143434    unsigned char flags;
143435    unsigned char nRange;
143436  } aEntry[] = {
143437    {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
143438    {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
143439    {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
143440    {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
143441    {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
143442    {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
143443    {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
143444    {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
143445    {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
143446    {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
143447    {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
143448    {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
143449    {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
143450    {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
143451    {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
143452    {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
143453    {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
143454    {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
143455    {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
143456    {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
143457    {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
143458    {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
143459    {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
143460    {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
143461    {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
143462    {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
143463    {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
143464    {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
143465    {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
143466    {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
143467    {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
143468    {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
143469    {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
143470    {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
143471    {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
143472    {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
143473    {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
143474    {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
143475    {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
143476    {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
143477    {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
143478    {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
143479    {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
143480    {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
143481    {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
143482    {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
143483    {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
143484    {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
143485    {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
143486    {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
143487    {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
143488    {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
143489    {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
143490    {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
143491    {65313, 14, 26},
143492  };
143493  static const unsigned short aiOff[] = {
143494   1,     2,     8,     15,    16,    26,    28,    32,
143495   37,    38,    40,    48,    63,    64,    69,    71,
143496   79,    80,    116,   202,   203,   205,   206,   207,
143497   209,   210,   211,   213,   214,   217,   218,   219,
143498   775,   7264,  10792, 10795, 23228, 23256, 30204, 54721,
143499   54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
143500   57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
143501   65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
143502   65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
143503   65514, 65521, 65527, 65528, 65529,
143504  };
143505
143506  int ret = c;
143507
143508  assert( c>=0 );
143509  assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
143510
143511  if( c<128 ){
143512    if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
143513  }else if( c<65536 ){
143514    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
143515    int iLo = 0;
143516    int iRes = -1;
143517
143518    while( iHi>=iLo ){
143519      int iTest = (iHi + iLo) / 2;
143520      int cmp = (c - aEntry[iTest].iCode);
143521      if( cmp>=0 ){
143522        iRes = iTest;
143523        iLo = iTest+1;
143524      }else{
143525        iHi = iTest-1;
143526      }
143527    }
143528    assert( iRes<0 || c>=aEntry[iRes].iCode );
143529
143530    if( iRes>=0 ){
143531      const struct TableEntry *p = &aEntry[iRes];
143532      if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
143533        ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
143534        assert( ret>0 );
143535      }
143536    }
143537
143538    if( bRemoveDiacritic ) ret = remove_diacritic(ret);
143539  }
143540
143541  else if( c>=66560 && c<66600 ){
143542    ret = c + 40;
143543  }
143544
143545  return ret;
143546}
143547#endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
143548#endif /* !defined(SQLITE_ENABLE_FTS4_UNICODE61) */
143549
143550/************** End of fts3_unicode2.c ***************************************/
143551/************** Begin file rtree.c *******************************************/
143552/*
143553** 2001 September 15
143554**
143555** The author disclaims copyright to this source code.  In place of
143556** a legal notice, here is a blessing:
143557**
143558**    May you do good and not evil.
143559**    May you find forgiveness for yourself and forgive others.
143560**    May you share freely, never taking more than you give.
143561**
143562*************************************************************************
143563** This file contains code for implementations of the r-tree and r*-tree
143564** algorithms packaged as an SQLite virtual table module.
143565*/
143566
143567/*
143568** Database Format of R-Tree Tables
143569** --------------------------------
143570**
143571** The data structure for a single virtual r-tree table is stored in three
143572** native SQLite tables declared as follows. In each case, the '%' character
143573** in the table name is replaced with the user-supplied name of the r-tree
143574** table.
143575**
143576**   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
143577**   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
143578**   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
143579**
143580** The data for each node of the r-tree structure is stored in the %_node
143581** table. For each node that is not the root node of the r-tree, there is
143582** an entry in the %_parent table associating the node with its parent.
143583** And for each row of data in the table, there is an entry in the %_rowid
143584** table that maps from the entries rowid to the id of the node that it
143585** is stored on.
143586**
143587** The root node of an r-tree always exists, even if the r-tree table is
143588** empty. The nodeno of the root node is always 1. All other nodes in the
143589** table must be the same size as the root node. The content of each node
143590** is formatted as follows:
143591**
143592**   1. If the node is the root node (node 1), then the first 2 bytes
143593**      of the node contain the tree depth as a big-endian integer.
143594**      For non-root nodes, the first 2 bytes are left unused.
143595**
143596**   2. The next 2 bytes contain the number of entries currently
143597**      stored in the node.
143598**
143599**   3. The remainder of the node contains the node entries. Each entry
143600**      consists of a single 8-byte integer followed by an even number
143601**      of 4-byte coordinates. For leaf nodes the integer is the rowid
143602**      of a record. For internal nodes it is the node number of a
143603**      child page.
143604*/
143605
143606#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
143607
143608#ifndef SQLITE_CORE
143609  SQLITE_EXTENSION_INIT1
143610#else
143611#endif
143612
143613/* #include <string.h> */
143614/* #include <assert.h> */
143615/* #include <stdio.h> */
143616
143617#ifndef SQLITE_AMALGAMATION
143618#include "sqlite3rtree.h"
143619typedef sqlite3_int64 i64;
143620typedef unsigned char u8;
143621typedef unsigned short u16;
143622typedef unsigned int u32;
143623#endif
143624
143625/*  The following macro is used to suppress compiler warnings.
143626*/
143627#ifndef UNUSED_PARAMETER
143628# define UNUSED_PARAMETER(x) (void)(x)
143629#endif
143630
143631typedef struct Rtree Rtree;
143632typedef struct RtreeCursor RtreeCursor;
143633typedef struct RtreeNode RtreeNode;
143634typedef struct RtreeCell RtreeCell;
143635typedef struct RtreeConstraint RtreeConstraint;
143636typedef struct RtreeMatchArg RtreeMatchArg;
143637typedef struct RtreeGeomCallback RtreeGeomCallback;
143638typedef union RtreeCoord RtreeCoord;
143639typedef struct RtreeSearchPoint RtreeSearchPoint;
143640
143641/* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
143642#define RTREE_MAX_DIMENSIONS 5
143643
143644/* Size of hash table Rtree.aHash. This hash table is not expected to
143645** ever contain very many entries, so a fixed number of buckets is
143646** used.
143647*/
143648#define HASHSIZE 97
143649
143650/* The xBestIndex method of this virtual table requires an estimate of
143651** the number of rows in the virtual table to calculate the costs of
143652** various strategies. If possible, this estimate is loaded from the
143653** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
143654** Otherwise, if no sqlite_stat1 entry is available, use
143655** RTREE_DEFAULT_ROWEST.
143656*/
143657#define RTREE_DEFAULT_ROWEST 1048576
143658#define RTREE_MIN_ROWEST         100
143659
143660/*
143661** An rtree virtual-table object.
143662*/
143663struct Rtree {
143664  sqlite3_vtab base;          /* Base class.  Must be first */
143665  sqlite3 *db;                /* Host database connection */
143666  int iNodeSize;              /* Size in bytes of each node in the node table */
143667  u8 nDim;                    /* Number of dimensions */
143668  u8 eCoordType;              /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
143669  u8 nBytesPerCell;           /* Bytes consumed per cell */
143670  int iDepth;                 /* Current depth of the r-tree structure */
143671  char *zDb;                  /* Name of database containing r-tree table */
143672  char *zName;                /* Name of r-tree table */
143673  int nBusy;                  /* Current number of users of this structure */
143674  i64 nRowEst;                /* Estimated number of rows in this table */
143675
143676  /* List of nodes removed during a CondenseTree operation. List is
143677  ** linked together via the pointer normally used for hash chains -
143678  ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
143679  ** headed by the node (leaf nodes have RtreeNode.iNode==0).
143680  */
143681  RtreeNode *pDeleted;
143682  int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
143683
143684  /* Statements to read/write/delete a record from xxx_node */
143685  sqlite3_stmt *pReadNode;
143686  sqlite3_stmt *pWriteNode;
143687  sqlite3_stmt *pDeleteNode;
143688
143689  /* Statements to read/write/delete a record from xxx_rowid */
143690  sqlite3_stmt *pReadRowid;
143691  sqlite3_stmt *pWriteRowid;
143692  sqlite3_stmt *pDeleteRowid;
143693
143694  /* Statements to read/write/delete a record from xxx_parent */
143695  sqlite3_stmt *pReadParent;
143696  sqlite3_stmt *pWriteParent;
143697  sqlite3_stmt *pDeleteParent;
143698
143699  RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
143700};
143701
143702/* Possible values for Rtree.eCoordType: */
143703#define RTREE_COORD_REAL32 0
143704#define RTREE_COORD_INT32  1
143705
143706/*
143707** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
143708** only deal with integer coordinates.  No floating point operations
143709** will be done.
143710*/
143711#ifdef SQLITE_RTREE_INT_ONLY
143712  typedef sqlite3_int64 RtreeDValue;       /* High accuracy coordinate */
143713  typedef int RtreeValue;                  /* Low accuracy coordinate */
143714# define RTREE_ZERO 0
143715#else
143716  typedef double RtreeDValue;              /* High accuracy coordinate */
143717  typedef float RtreeValue;                /* Low accuracy coordinate */
143718# define RTREE_ZERO 0.0
143719#endif
143720
143721/*
143722** When doing a search of an r-tree, instances of the following structure
143723** record intermediate results from the tree walk.
143724**
143725** The id is always a node-id.  For iLevel>=1 the id is the node-id of
143726** the node that the RtreeSearchPoint represents.  When iLevel==0, however,
143727** the id is of the parent node and the cell that RtreeSearchPoint
143728** represents is the iCell-th entry in the parent node.
143729*/
143730struct RtreeSearchPoint {
143731  RtreeDValue rScore;    /* The score for this node.  Smallest goes first. */
143732  sqlite3_int64 id;      /* Node ID */
143733  u8 iLevel;             /* 0=entries.  1=leaf node.  2+ for higher */
143734  u8 eWithin;            /* PARTLY_WITHIN or FULLY_WITHIN */
143735  u8 iCell;              /* Cell index within the node */
143736};
143737
143738/*
143739** The minimum number of cells allowed for a node is a third of the
143740** maximum. In Gutman's notation:
143741**
143742**     m = M/3
143743**
143744** If an R*-tree "Reinsert" operation is required, the same number of
143745** cells are removed from the overfull node and reinserted into the tree.
143746*/
143747#define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
143748#define RTREE_REINSERT(p) RTREE_MINCELLS(p)
143749#define RTREE_MAXCELLS 51
143750
143751/*
143752** The smallest possible node-size is (512-64)==448 bytes. And the largest
143753** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
143754** Therefore all non-root nodes must contain at least 3 entries. Since
143755** 2^40 is greater than 2^64, an r-tree structure always has a depth of
143756** 40 or less.
143757*/
143758#define RTREE_MAX_DEPTH 40
143759
143760
143761/*
143762** Number of entries in the cursor RtreeNode cache.  The first entry is
143763** used to cache the RtreeNode for RtreeCursor.sPoint.  The remaining
143764** entries cache the RtreeNode for the first elements of the priority queue.
143765*/
143766#define RTREE_CACHE_SZ  5
143767
143768/*
143769** An rtree cursor object.
143770*/
143771struct RtreeCursor {
143772  sqlite3_vtab_cursor base;         /* Base class.  Must be first */
143773  u8 atEOF;                         /* True if at end of search */
143774  u8 bPoint;                        /* True if sPoint is valid */
143775  int iStrategy;                    /* Copy of idxNum search parameter */
143776  int nConstraint;                  /* Number of entries in aConstraint */
143777  RtreeConstraint *aConstraint;     /* Search constraints. */
143778  int nPointAlloc;                  /* Number of slots allocated for aPoint[] */
143779  int nPoint;                       /* Number of slots used in aPoint[] */
143780  int mxLevel;                      /* iLevel value for root of the tree */
143781  RtreeSearchPoint *aPoint;         /* Priority queue for search points */
143782  RtreeSearchPoint sPoint;          /* Cached next search point */
143783  RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
143784  u32 anQueue[RTREE_MAX_DEPTH+1];   /* Number of queued entries by iLevel */
143785};
143786
143787/* Return the Rtree of a RtreeCursor */
143788#define RTREE_OF_CURSOR(X)   ((Rtree*)((X)->base.pVtab))
143789
143790/*
143791** A coordinate can be either a floating point number or a integer.  All
143792** coordinates within a single R-Tree are always of the same time.
143793*/
143794union RtreeCoord {
143795  RtreeValue f;      /* Floating point value */
143796  int i;             /* Integer value */
143797  u32 u;             /* Unsigned for byte-order conversions */
143798};
143799
143800/*
143801** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
143802** formatted as a RtreeDValue (double or int64). This macro assumes that local
143803** variable pRtree points to the Rtree structure associated with the
143804** RtreeCoord.
143805*/
143806#ifdef SQLITE_RTREE_INT_ONLY
143807# define DCOORD(coord) ((RtreeDValue)coord.i)
143808#else
143809# define DCOORD(coord) (                           \
143810    (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
143811      ((double)coord.f) :                           \
143812      ((double)coord.i)                             \
143813  )
143814#endif
143815
143816/*
143817** A search constraint.
143818*/
143819struct RtreeConstraint {
143820  int iCoord;                     /* Index of constrained coordinate */
143821  int op;                         /* Constraining operation */
143822  union {
143823    RtreeDValue rValue;             /* Constraint value. */
143824    int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
143825    int (*xQueryFunc)(sqlite3_rtree_query_info*);
143826  } u;
143827  sqlite3_rtree_query_info *pInfo;  /* xGeom and xQueryFunc argument */
143828};
143829
143830/* Possible values for RtreeConstraint.op */
143831#define RTREE_EQ    0x41  /* A */
143832#define RTREE_LE    0x42  /* B */
143833#define RTREE_LT    0x43  /* C */
143834#define RTREE_GE    0x44  /* D */
143835#define RTREE_GT    0x45  /* E */
143836#define RTREE_MATCH 0x46  /* F: Old-style sqlite3_rtree_geometry_callback() */
143837#define RTREE_QUERY 0x47  /* G: New-style sqlite3_rtree_query_callback() */
143838
143839
143840/*
143841** An rtree structure node.
143842*/
143843struct RtreeNode {
143844  RtreeNode *pParent;         /* Parent node */
143845  i64 iNode;                  /* The node number */
143846  int nRef;                   /* Number of references to this node */
143847  int isDirty;                /* True if the node needs to be written to disk */
143848  u8 *zData;                  /* Content of the node, as should be on disk */
143849  RtreeNode *pNext;           /* Next node in this hash collision chain */
143850};
143851
143852/* Return the number of cells in a node  */
143853#define NCELL(pNode) readInt16(&(pNode)->zData[2])
143854
143855/*
143856** A single cell from a node, deserialized
143857*/
143858struct RtreeCell {
143859  i64 iRowid;                                 /* Node or entry ID */
143860  RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];  /* Bounding box coordinates */
143861};
143862
143863
143864/*
143865** This object becomes the sqlite3_user_data() for the SQL functions
143866** that are created by sqlite3_rtree_geometry_callback() and
143867** sqlite3_rtree_query_callback() and which appear on the right of MATCH
143868** operators in order to constrain a search.
143869**
143870** xGeom and xQueryFunc are the callback functions.  Exactly one of
143871** xGeom and xQueryFunc fields is non-NULL, depending on whether the
143872** SQL function was created using sqlite3_rtree_geometry_callback() or
143873** sqlite3_rtree_query_callback().
143874**
143875** This object is deleted automatically by the destructor mechanism in
143876** sqlite3_create_function_v2().
143877*/
143878struct RtreeGeomCallback {
143879  int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
143880  int (*xQueryFunc)(sqlite3_rtree_query_info*);
143881  void (*xDestructor)(void*);
143882  void *pContext;
143883};
143884
143885
143886/*
143887** Value for the first field of every RtreeMatchArg object. The MATCH
143888** operator tests that the first field of a blob operand matches this
143889** value to avoid operating on invalid blobs (which could cause a segfault).
143890*/
143891#define RTREE_GEOMETRY_MAGIC 0x891245AB
143892
143893/*
143894** An instance of this structure (in the form of a BLOB) is returned by
143895** the SQL functions that sqlite3_rtree_geometry_callback() and
143896** sqlite3_rtree_query_callback() create, and is read as the right-hand
143897** operand to the MATCH operator of an R-Tree.
143898*/
143899struct RtreeMatchArg {
143900  u32 magic;                  /* Always RTREE_GEOMETRY_MAGIC */
143901  RtreeGeomCallback cb;       /* Info about the callback functions */
143902  int nParam;                 /* Number of parameters to the SQL function */
143903  RtreeDValue aParam[1];      /* Values for parameters to the SQL function */
143904};
143905
143906#ifndef MAX
143907# define MAX(x,y) ((x) < (y) ? (y) : (x))
143908#endif
143909#ifndef MIN
143910# define MIN(x,y) ((x) > (y) ? (y) : (x))
143911#endif
143912
143913/*
143914** Functions to deserialize a 16 bit integer, 32 bit real number and
143915** 64 bit integer. The deserialized value is returned.
143916*/
143917static int readInt16(u8 *p){
143918  return (p[0]<<8) + p[1];
143919}
143920static void readCoord(u8 *p, RtreeCoord *pCoord){
143921  u32 i = (
143922    (((u32)p[0]) << 24) +
143923    (((u32)p[1]) << 16) +
143924    (((u32)p[2]) <<  8) +
143925    (((u32)p[3]) <<  0)
143926  );
143927  *(u32 *)pCoord = i;
143928}
143929static i64 readInt64(u8 *p){
143930  return (
143931    (((i64)p[0]) << 56) +
143932    (((i64)p[1]) << 48) +
143933    (((i64)p[2]) << 40) +
143934    (((i64)p[3]) << 32) +
143935    (((i64)p[4]) << 24) +
143936    (((i64)p[5]) << 16) +
143937    (((i64)p[6]) <<  8) +
143938    (((i64)p[7]) <<  0)
143939  );
143940}
143941
143942/*
143943** Functions to serialize a 16 bit integer, 32 bit real number and
143944** 64 bit integer. The value returned is the number of bytes written
143945** to the argument buffer (always 2, 4 and 8 respectively).
143946*/
143947static int writeInt16(u8 *p, int i){
143948  p[0] = (i>> 8)&0xFF;
143949  p[1] = (i>> 0)&0xFF;
143950  return 2;
143951}
143952static int writeCoord(u8 *p, RtreeCoord *pCoord){
143953  u32 i;
143954  assert( sizeof(RtreeCoord)==4 );
143955  assert( sizeof(u32)==4 );
143956  i = *(u32 *)pCoord;
143957  p[0] = (i>>24)&0xFF;
143958  p[1] = (i>>16)&0xFF;
143959  p[2] = (i>> 8)&0xFF;
143960  p[3] = (i>> 0)&0xFF;
143961  return 4;
143962}
143963static int writeInt64(u8 *p, i64 i){
143964  p[0] = (i>>56)&0xFF;
143965  p[1] = (i>>48)&0xFF;
143966  p[2] = (i>>40)&0xFF;
143967  p[3] = (i>>32)&0xFF;
143968  p[4] = (i>>24)&0xFF;
143969  p[5] = (i>>16)&0xFF;
143970  p[6] = (i>> 8)&0xFF;
143971  p[7] = (i>> 0)&0xFF;
143972  return 8;
143973}
143974
143975/*
143976** Increment the reference count of node p.
143977*/
143978static void nodeReference(RtreeNode *p){
143979  if( p ){
143980    p->nRef++;
143981  }
143982}
143983
143984/*
143985** Clear the content of node p (set all bytes to 0x00).
143986*/
143987static void nodeZero(Rtree *pRtree, RtreeNode *p){
143988  memset(&p->zData[2], 0, pRtree->iNodeSize-2);
143989  p->isDirty = 1;
143990}
143991
143992/*
143993** Given a node number iNode, return the corresponding key to use
143994** in the Rtree.aHash table.
143995*/
143996static int nodeHash(i64 iNode){
143997  return iNode % HASHSIZE;
143998}
143999
144000/*
144001** Search the node hash table for node iNode. If found, return a pointer
144002** to it. Otherwise, return 0.
144003*/
144004static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
144005  RtreeNode *p;
144006  for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
144007  return p;
144008}
144009
144010/*
144011** Add node pNode to the node hash table.
144012*/
144013static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
144014  int iHash;
144015  assert( pNode->pNext==0 );
144016  iHash = nodeHash(pNode->iNode);
144017  pNode->pNext = pRtree->aHash[iHash];
144018  pRtree->aHash[iHash] = pNode;
144019}
144020
144021/*
144022** Remove node pNode from the node hash table.
144023*/
144024static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
144025  RtreeNode **pp;
144026  if( pNode->iNode!=0 ){
144027    pp = &pRtree->aHash[nodeHash(pNode->iNode)];
144028    for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
144029    *pp = pNode->pNext;
144030    pNode->pNext = 0;
144031  }
144032}
144033
144034/*
144035** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
144036** indicating that node has not yet been assigned a node number. It is
144037** assigned a node number when nodeWrite() is called to write the
144038** node contents out to the database.
144039*/
144040static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
144041  RtreeNode *pNode;
144042  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
144043  if( pNode ){
144044    memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
144045    pNode->zData = (u8 *)&pNode[1];
144046    pNode->nRef = 1;
144047    pNode->pParent = pParent;
144048    pNode->isDirty = 1;
144049    nodeReference(pParent);
144050  }
144051  return pNode;
144052}
144053
144054/*
144055** Obtain a reference to an r-tree node.
144056*/
144057static int nodeAcquire(
144058  Rtree *pRtree,             /* R-tree structure */
144059  i64 iNode,                 /* Node number to load */
144060  RtreeNode *pParent,        /* Either the parent node or NULL */
144061  RtreeNode **ppNode         /* OUT: Acquired node */
144062){
144063  int rc;
144064  int rc2 = SQLITE_OK;
144065  RtreeNode *pNode;
144066
144067  /* Check if the requested node is already in the hash table. If so,
144068  ** increase its reference count and return it.
144069  */
144070  if( (pNode = nodeHashLookup(pRtree, iNode)) ){
144071    assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
144072    if( pParent && !pNode->pParent ){
144073      nodeReference(pParent);
144074      pNode->pParent = pParent;
144075    }
144076    pNode->nRef++;
144077    *ppNode = pNode;
144078    return SQLITE_OK;
144079  }
144080
144081  sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
144082  rc = sqlite3_step(pRtree->pReadNode);
144083  if( rc==SQLITE_ROW ){
144084    const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
144085    if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
144086      pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
144087      if( !pNode ){
144088        rc2 = SQLITE_NOMEM;
144089      }else{
144090        pNode->pParent = pParent;
144091        pNode->zData = (u8 *)&pNode[1];
144092        pNode->nRef = 1;
144093        pNode->iNode = iNode;
144094        pNode->isDirty = 0;
144095        pNode->pNext = 0;
144096        memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
144097        nodeReference(pParent);
144098      }
144099    }
144100  }
144101  rc = sqlite3_reset(pRtree->pReadNode);
144102  if( rc==SQLITE_OK ) rc = rc2;
144103
144104  /* If the root node was just loaded, set pRtree->iDepth to the height
144105  ** of the r-tree structure. A height of zero means all data is stored on
144106  ** the root node. A height of one means the children of the root node
144107  ** are the leaves, and so on. If the depth as specified on the root node
144108  ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
144109  */
144110  if( pNode && iNode==1 ){
144111    pRtree->iDepth = readInt16(pNode->zData);
144112    if( pRtree->iDepth>RTREE_MAX_DEPTH ){
144113      rc = SQLITE_CORRUPT_VTAB;
144114    }
144115  }
144116
144117  /* If no error has occurred so far, check if the "number of entries"
144118  ** field on the node is too large. If so, set the return code to
144119  ** SQLITE_CORRUPT_VTAB.
144120  */
144121  if( pNode && rc==SQLITE_OK ){
144122    if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
144123      rc = SQLITE_CORRUPT_VTAB;
144124    }
144125  }
144126
144127  if( rc==SQLITE_OK ){
144128    if( pNode!=0 ){
144129      nodeHashInsert(pRtree, pNode);
144130    }else{
144131      rc = SQLITE_CORRUPT_VTAB;
144132    }
144133    *ppNode = pNode;
144134  }else{
144135    sqlite3_free(pNode);
144136    *ppNode = 0;
144137  }
144138
144139  return rc;
144140}
144141
144142/*
144143** Overwrite cell iCell of node pNode with the contents of pCell.
144144*/
144145static void nodeOverwriteCell(
144146  Rtree *pRtree,             /* The overall R-Tree */
144147  RtreeNode *pNode,          /* The node into which the cell is to be written */
144148  RtreeCell *pCell,          /* The cell to write */
144149  int iCell                  /* Index into pNode into which pCell is written */
144150){
144151  int ii;
144152  u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
144153  p += writeInt64(p, pCell->iRowid);
144154  for(ii=0; ii<(pRtree->nDim*2); ii++){
144155    p += writeCoord(p, &pCell->aCoord[ii]);
144156  }
144157  pNode->isDirty = 1;
144158}
144159
144160/*
144161** Remove the cell with index iCell from node pNode.
144162*/
144163static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
144164  u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
144165  u8 *pSrc = &pDst[pRtree->nBytesPerCell];
144166  int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
144167  memmove(pDst, pSrc, nByte);
144168  writeInt16(&pNode->zData[2], NCELL(pNode)-1);
144169  pNode->isDirty = 1;
144170}
144171
144172/*
144173** Insert the contents of cell pCell into node pNode. If the insert
144174** is successful, return SQLITE_OK.
144175**
144176** If there is not enough free space in pNode, return SQLITE_FULL.
144177*/
144178static int nodeInsertCell(
144179  Rtree *pRtree,                /* The overall R-Tree */
144180  RtreeNode *pNode,             /* Write new cell into this node */
144181  RtreeCell *pCell              /* The cell to be inserted */
144182){
144183  int nCell;                    /* Current number of cells in pNode */
144184  int nMaxCell;                 /* Maximum number of cells for pNode */
144185
144186  nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
144187  nCell = NCELL(pNode);
144188
144189  assert( nCell<=nMaxCell );
144190  if( nCell<nMaxCell ){
144191    nodeOverwriteCell(pRtree, pNode, pCell, nCell);
144192    writeInt16(&pNode->zData[2], nCell+1);
144193    pNode->isDirty = 1;
144194  }
144195
144196  return (nCell==nMaxCell);
144197}
144198
144199/*
144200** If the node is dirty, write it out to the database.
144201*/
144202static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
144203  int rc = SQLITE_OK;
144204  if( pNode->isDirty ){
144205    sqlite3_stmt *p = pRtree->pWriteNode;
144206    if( pNode->iNode ){
144207      sqlite3_bind_int64(p, 1, pNode->iNode);
144208    }else{
144209      sqlite3_bind_null(p, 1);
144210    }
144211    sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
144212    sqlite3_step(p);
144213    pNode->isDirty = 0;
144214    rc = sqlite3_reset(p);
144215    if( pNode->iNode==0 && rc==SQLITE_OK ){
144216      pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
144217      nodeHashInsert(pRtree, pNode);
144218    }
144219  }
144220  return rc;
144221}
144222
144223/*
144224** Release a reference to a node. If the node is dirty and the reference
144225** count drops to zero, the node data is written to the database.
144226*/
144227static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
144228  int rc = SQLITE_OK;
144229  if( pNode ){
144230    assert( pNode->nRef>0 );
144231    pNode->nRef--;
144232    if( pNode->nRef==0 ){
144233      if( pNode->iNode==1 ){
144234        pRtree->iDepth = -1;
144235      }
144236      if( pNode->pParent ){
144237        rc = nodeRelease(pRtree, pNode->pParent);
144238      }
144239      if( rc==SQLITE_OK ){
144240        rc = nodeWrite(pRtree, pNode);
144241      }
144242      nodeHashDelete(pRtree, pNode);
144243      sqlite3_free(pNode);
144244    }
144245  }
144246  return rc;
144247}
144248
144249/*
144250** Return the 64-bit integer value associated with cell iCell of
144251** node pNode. If pNode is a leaf node, this is a rowid. If it is
144252** an internal node, then the 64-bit integer is a child page number.
144253*/
144254static i64 nodeGetRowid(
144255  Rtree *pRtree,       /* The overall R-Tree */
144256  RtreeNode *pNode,    /* The node from which to extract the ID */
144257  int iCell            /* The cell index from which to extract the ID */
144258){
144259  assert( iCell<NCELL(pNode) );
144260  return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
144261}
144262
144263/*
144264** Return coordinate iCoord from cell iCell in node pNode.
144265*/
144266static void nodeGetCoord(
144267  Rtree *pRtree,               /* The overall R-Tree */
144268  RtreeNode *pNode,            /* The node from which to extract a coordinate */
144269  int iCell,                   /* The index of the cell within the node */
144270  int iCoord,                  /* Which coordinate to extract */
144271  RtreeCoord *pCoord           /* OUT: Space to write result to */
144272){
144273  readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
144274}
144275
144276/*
144277** Deserialize cell iCell of node pNode. Populate the structure pointed
144278** to by pCell with the results.
144279*/
144280static void nodeGetCell(
144281  Rtree *pRtree,               /* The overall R-Tree */
144282  RtreeNode *pNode,            /* The node containing the cell to be read */
144283  int iCell,                   /* Index of the cell within the node */
144284  RtreeCell *pCell             /* OUT: Write the cell contents here */
144285){
144286  u8 *pData;
144287  u8 *pEnd;
144288  RtreeCoord *pCoord;
144289  pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
144290  pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
144291  pEnd = pData + pRtree->nDim*8;
144292  pCoord = pCell->aCoord;
144293  for(; pData<pEnd; pData+=4, pCoord++){
144294    readCoord(pData, pCoord);
144295  }
144296}
144297
144298
144299/* Forward declaration for the function that does the work of
144300** the virtual table module xCreate() and xConnect() methods.
144301*/
144302static int rtreeInit(
144303  sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
144304);
144305
144306/*
144307** Rtree virtual table module xCreate method.
144308*/
144309static int rtreeCreate(
144310  sqlite3 *db,
144311  void *pAux,
144312  int argc, const char *const*argv,
144313  sqlite3_vtab **ppVtab,
144314  char **pzErr
144315){
144316  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
144317}
144318
144319/*
144320** Rtree virtual table module xConnect method.
144321*/
144322static int rtreeConnect(
144323  sqlite3 *db,
144324  void *pAux,
144325  int argc, const char *const*argv,
144326  sqlite3_vtab **ppVtab,
144327  char **pzErr
144328){
144329  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
144330}
144331
144332/*
144333** Increment the r-tree reference count.
144334*/
144335static void rtreeReference(Rtree *pRtree){
144336  pRtree->nBusy++;
144337}
144338
144339/*
144340** Decrement the r-tree reference count. When the reference count reaches
144341** zero the structure is deleted.
144342*/
144343static void rtreeRelease(Rtree *pRtree){
144344  pRtree->nBusy--;
144345  if( pRtree->nBusy==0 ){
144346    sqlite3_finalize(pRtree->pReadNode);
144347    sqlite3_finalize(pRtree->pWriteNode);
144348    sqlite3_finalize(pRtree->pDeleteNode);
144349    sqlite3_finalize(pRtree->pReadRowid);
144350    sqlite3_finalize(pRtree->pWriteRowid);
144351    sqlite3_finalize(pRtree->pDeleteRowid);
144352    sqlite3_finalize(pRtree->pReadParent);
144353    sqlite3_finalize(pRtree->pWriteParent);
144354    sqlite3_finalize(pRtree->pDeleteParent);
144355    sqlite3_free(pRtree);
144356  }
144357}
144358
144359/*
144360** Rtree virtual table module xDisconnect method.
144361*/
144362static int rtreeDisconnect(sqlite3_vtab *pVtab){
144363  rtreeRelease((Rtree *)pVtab);
144364  return SQLITE_OK;
144365}
144366
144367/*
144368** Rtree virtual table module xDestroy method.
144369*/
144370static int rtreeDestroy(sqlite3_vtab *pVtab){
144371  Rtree *pRtree = (Rtree *)pVtab;
144372  int rc;
144373  char *zCreate = sqlite3_mprintf(
144374    "DROP TABLE '%q'.'%q_node';"
144375    "DROP TABLE '%q'.'%q_rowid';"
144376    "DROP TABLE '%q'.'%q_parent';",
144377    pRtree->zDb, pRtree->zName,
144378    pRtree->zDb, pRtree->zName,
144379    pRtree->zDb, pRtree->zName
144380  );
144381  if( !zCreate ){
144382    rc = SQLITE_NOMEM;
144383  }else{
144384    rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
144385    sqlite3_free(zCreate);
144386  }
144387  if( rc==SQLITE_OK ){
144388    rtreeRelease(pRtree);
144389  }
144390
144391  return rc;
144392}
144393
144394/*
144395** Rtree virtual table module xOpen method.
144396*/
144397static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
144398  int rc = SQLITE_NOMEM;
144399  RtreeCursor *pCsr;
144400
144401  pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
144402  if( pCsr ){
144403    memset(pCsr, 0, sizeof(RtreeCursor));
144404    pCsr->base.pVtab = pVTab;
144405    rc = SQLITE_OK;
144406  }
144407  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
144408
144409  return rc;
144410}
144411
144412
144413/*
144414** Free the RtreeCursor.aConstraint[] array and its contents.
144415*/
144416static void freeCursorConstraints(RtreeCursor *pCsr){
144417  if( pCsr->aConstraint ){
144418    int i;                        /* Used to iterate through constraint array */
144419    for(i=0; i<pCsr->nConstraint; i++){
144420      sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
144421      if( pInfo ){
144422        if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
144423        sqlite3_free(pInfo);
144424      }
144425    }
144426    sqlite3_free(pCsr->aConstraint);
144427    pCsr->aConstraint = 0;
144428  }
144429}
144430
144431/*
144432** Rtree virtual table module xClose method.
144433*/
144434static int rtreeClose(sqlite3_vtab_cursor *cur){
144435  Rtree *pRtree = (Rtree *)(cur->pVtab);
144436  int ii;
144437  RtreeCursor *pCsr = (RtreeCursor *)cur;
144438  freeCursorConstraints(pCsr);
144439  sqlite3_free(pCsr->aPoint);
144440  for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
144441  sqlite3_free(pCsr);
144442  return SQLITE_OK;
144443}
144444
144445/*
144446** Rtree virtual table module xEof method.
144447**
144448** Return non-zero if the cursor does not currently point to a valid
144449** record (i.e if the scan has finished), or zero otherwise.
144450*/
144451static int rtreeEof(sqlite3_vtab_cursor *cur){
144452  RtreeCursor *pCsr = (RtreeCursor *)cur;
144453  return pCsr->atEOF;
144454}
144455
144456/*
144457** Convert raw bits from the on-disk RTree record into a coordinate value.
144458** The on-disk format is big-endian and needs to be converted for little-
144459** endian platforms.  The on-disk record stores integer coordinates if
144460** eInt is true and it stores 32-bit floating point records if eInt is
144461** false.  a[] is the four bytes of the on-disk record to be decoded.
144462** Store the results in "r".
144463**
144464** There are three versions of this macro, one each for little-endian and
144465** big-endian processors and a third generic implementation.  The endian-
144466** specific implementations are much faster and are preferred if the
144467** processor endianness is known at compile-time.  The SQLITE_BYTEORDER
144468** macro is part of sqliteInt.h and hence the endian-specific
144469** implementation will only be used if this module is compiled as part
144470** of the amalgamation.
144471*/
144472#if defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==1234
144473#define RTREE_DECODE_COORD(eInt, a, r) {                        \
144474    RtreeCoord c;    /* Coordinate decoded */                   \
144475    memcpy(&c.u,a,4);                                           \
144476    c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)|                   \
144477          ((c.u&0xff)<<24)|((c.u&0xff00)<<8);                   \
144478    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
144479}
144480#elif defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==4321
144481#define RTREE_DECODE_COORD(eInt, a, r) {                        \
144482    RtreeCoord c;    /* Coordinate decoded */                   \
144483    memcpy(&c.u,a,4);                                           \
144484    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
144485}
144486#else
144487#define RTREE_DECODE_COORD(eInt, a, r) {                        \
144488    RtreeCoord c;    /* Coordinate decoded */                   \
144489    c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16)                     \
144490           +((u32)a[2]<<8) + a[3];                              \
144491    r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
144492}
144493#endif
144494
144495/*
144496** Check the RTree node or entry given by pCellData and p against the MATCH
144497** constraint pConstraint.
144498*/
144499static int rtreeCallbackConstraint(
144500  RtreeConstraint *pConstraint,  /* The constraint to test */
144501  int eInt,                      /* True if RTree holding integer coordinates */
144502  u8 *pCellData,                 /* Raw cell content */
144503  RtreeSearchPoint *pSearch,     /* Container of this cell */
144504  sqlite3_rtree_dbl *prScore,    /* OUT: score for the cell */
144505  int *peWithin                  /* OUT: visibility of the cell */
144506){
144507  int i;                                                /* Loop counter */
144508  sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
144509  int nCoord = pInfo->nCoord;                           /* No. of coordinates */
144510  int rc;                                             /* Callback return code */
144511  sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2];   /* Decoded coordinates */
144512
144513  assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
144514  assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
144515
144516  if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
144517    pInfo->iRowid = readInt64(pCellData);
144518  }
144519  pCellData += 8;
144520  for(i=0; i<nCoord; i++, pCellData += 4){
144521    RTREE_DECODE_COORD(eInt, pCellData, aCoord[i]);
144522  }
144523  if( pConstraint->op==RTREE_MATCH ){
144524    rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
144525                              nCoord, aCoord, &i);
144526    if( i==0 ) *peWithin = NOT_WITHIN;
144527    *prScore = RTREE_ZERO;
144528  }else{
144529    pInfo->aCoord = aCoord;
144530    pInfo->iLevel = pSearch->iLevel - 1;
144531    pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
144532    pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
144533    rc = pConstraint->u.xQueryFunc(pInfo);
144534    if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
144535    if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
144536      *prScore = pInfo->rScore;
144537    }
144538  }
144539  return rc;
144540}
144541
144542/*
144543** Check the internal RTree node given by pCellData against constraint p.
144544** If this constraint cannot be satisfied by any child within the node,
144545** set *peWithin to NOT_WITHIN.
144546*/
144547static void rtreeNonleafConstraint(
144548  RtreeConstraint *p,        /* The constraint to test */
144549  int eInt,                  /* True if RTree holds integer coordinates */
144550  u8 *pCellData,             /* Raw cell content as appears on disk */
144551  int *peWithin              /* Adjust downward, as appropriate */
144552){
144553  sqlite3_rtree_dbl val;     /* Coordinate value convert to a double */
144554
144555  /* p->iCoord might point to either a lower or upper bound coordinate
144556  ** in a coordinate pair.  But make pCellData point to the lower bound.
144557  */
144558  pCellData += 8 + 4*(p->iCoord&0xfe);
144559
144560  assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
144561      || p->op==RTREE_GT || p->op==RTREE_EQ );
144562  switch( p->op ){
144563    case RTREE_LE:
144564    case RTREE_LT:
144565    case RTREE_EQ:
144566      RTREE_DECODE_COORD(eInt, pCellData, val);
144567      /* val now holds the lower bound of the coordinate pair */
144568      if( p->u.rValue>=val ) return;
144569      if( p->op!=RTREE_EQ ) break;  /* RTREE_LE and RTREE_LT end here */
144570      /* Fall through for the RTREE_EQ case */
144571
144572    default: /* RTREE_GT or RTREE_GE,  or fallthrough of RTREE_EQ */
144573      pCellData += 4;
144574      RTREE_DECODE_COORD(eInt, pCellData, val);
144575      /* val now holds the upper bound of the coordinate pair */
144576      if( p->u.rValue<=val ) return;
144577  }
144578  *peWithin = NOT_WITHIN;
144579}
144580
144581/*
144582** Check the leaf RTree cell given by pCellData against constraint p.
144583** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
144584** If the constraint is satisfied, leave *peWithin unchanged.
144585**
144586** The constraint is of the form:  xN op $val
144587**
144588** The op is given by p->op.  The xN is p->iCoord-th coordinate in
144589** pCellData.  $val is given by p->u.rValue.
144590*/
144591static void rtreeLeafConstraint(
144592  RtreeConstraint *p,        /* The constraint to test */
144593  int eInt,                  /* True if RTree holds integer coordinates */
144594  u8 *pCellData,             /* Raw cell content as appears on disk */
144595  int *peWithin              /* Adjust downward, as appropriate */
144596){
144597  RtreeDValue xN;      /* Coordinate value converted to a double */
144598
144599  assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
144600      || p->op==RTREE_GT || p->op==RTREE_EQ );
144601  pCellData += 8 + p->iCoord*4;
144602  RTREE_DECODE_COORD(eInt, pCellData, xN);
144603  switch( p->op ){
144604    case RTREE_LE: if( xN <= p->u.rValue ) return;  break;
144605    case RTREE_LT: if( xN <  p->u.rValue ) return;  break;
144606    case RTREE_GE: if( xN >= p->u.rValue ) return;  break;
144607    case RTREE_GT: if( xN >  p->u.rValue ) return;  break;
144608    default:       if( xN == p->u.rValue ) return;  break;
144609  }
144610  *peWithin = NOT_WITHIN;
144611}
144612
144613/*
144614** One of the cells in node pNode is guaranteed to have a 64-bit
144615** integer value equal to iRowid. Return the index of this cell.
144616*/
144617static int nodeRowidIndex(
144618  Rtree *pRtree,
144619  RtreeNode *pNode,
144620  i64 iRowid,
144621  int *piIndex
144622){
144623  int ii;
144624  int nCell = NCELL(pNode);
144625  assert( nCell<200 );
144626  for(ii=0; ii<nCell; ii++){
144627    if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
144628      *piIndex = ii;
144629      return SQLITE_OK;
144630    }
144631  }
144632  return SQLITE_CORRUPT_VTAB;
144633}
144634
144635/*
144636** Return the index of the cell containing a pointer to node pNode
144637** in its parent. If pNode is the root node, return -1.
144638*/
144639static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
144640  RtreeNode *pParent = pNode->pParent;
144641  if( pParent ){
144642    return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
144643  }
144644  *piIndex = -1;
144645  return SQLITE_OK;
144646}
144647
144648/*
144649** Compare two search points.  Return negative, zero, or positive if the first
144650** is less than, equal to, or greater than the second.
144651**
144652** The rScore is the primary key.  Smaller rScore values come first.
144653** If the rScore is a tie, then use iLevel as the tie breaker with smaller
144654** iLevel values coming first.  In this way, if rScore is the same for all
144655** SearchPoints, then iLevel becomes the deciding factor and the result
144656** is a depth-first search, which is the desired default behavior.
144657*/
144658static int rtreeSearchPointCompare(
144659  const RtreeSearchPoint *pA,
144660  const RtreeSearchPoint *pB
144661){
144662  if( pA->rScore<pB->rScore ) return -1;
144663  if( pA->rScore>pB->rScore ) return +1;
144664  if( pA->iLevel<pB->iLevel ) return -1;
144665  if( pA->iLevel>pB->iLevel ) return +1;
144666  return 0;
144667}
144668
144669/*
144670** Interchange to search points in a cursor.
144671*/
144672static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
144673  RtreeSearchPoint t = p->aPoint[i];
144674  assert( i<j );
144675  p->aPoint[i] = p->aPoint[j];
144676  p->aPoint[j] = t;
144677  i++; j++;
144678  if( i<RTREE_CACHE_SZ ){
144679    if( j>=RTREE_CACHE_SZ ){
144680      nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
144681      p->aNode[i] = 0;
144682    }else{
144683      RtreeNode *pTemp = p->aNode[i];
144684      p->aNode[i] = p->aNode[j];
144685      p->aNode[j] = pTemp;
144686    }
144687  }
144688}
144689
144690/*
144691** Return the search point with the lowest current score.
144692*/
144693static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
144694  return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
144695}
144696
144697/*
144698** Get the RtreeNode for the search point with the lowest score.
144699*/
144700static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
144701  sqlite3_int64 id;
144702  int ii = 1 - pCur->bPoint;
144703  assert( ii==0 || ii==1 );
144704  assert( pCur->bPoint || pCur->nPoint );
144705  if( pCur->aNode[ii]==0 ){
144706    assert( pRC!=0 );
144707    id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
144708    *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
144709  }
144710  return pCur->aNode[ii];
144711}
144712
144713/*
144714** Push a new element onto the priority queue
144715*/
144716static RtreeSearchPoint *rtreeEnqueue(
144717  RtreeCursor *pCur,    /* The cursor */
144718  RtreeDValue rScore,   /* Score for the new search point */
144719  u8 iLevel             /* Level for the new search point */
144720){
144721  int i, j;
144722  RtreeSearchPoint *pNew;
144723  if( pCur->nPoint>=pCur->nPointAlloc ){
144724    int nNew = pCur->nPointAlloc*2 + 8;
144725    pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
144726    if( pNew==0 ) return 0;
144727    pCur->aPoint = pNew;
144728    pCur->nPointAlloc = nNew;
144729  }
144730  i = pCur->nPoint++;
144731  pNew = pCur->aPoint + i;
144732  pNew->rScore = rScore;
144733  pNew->iLevel = iLevel;
144734  assert( iLevel>=0 && iLevel<=RTREE_MAX_DEPTH );
144735  while( i>0 ){
144736    RtreeSearchPoint *pParent;
144737    j = (i-1)/2;
144738    pParent = pCur->aPoint + j;
144739    if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
144740    rtreeSearchPointSwap(pCur, j, i);
144741    i = j;
144742    pNew = pParent;
144743  }
144744  return pNew;
144745}
144746
144747/*
144748** Allocate a new RtreeSearchPoint and return a pointer to it.  Return
144749** NULL if malloc fails.
144750*/
144751static RtreeSearchPoint *rtreeSearchPointNew(
144752  RtreeCursor *pCur,    /* The cursor */
144753  RtreeDValue rScore,   /* Score for the new search point */
144754  u8 iLevel             /* Level for the new search point */
144755){
144756  RtreeSearchPoint *pNew, *pFirst;
144757  pFirst = rtreeSearchPointFirst(pCur);
144758  pCur->anQueue[iLevel]++;
144759  if( pFirst==0
144760   || pFirst->rScore>rScore
144761   || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
144762  ){
144763    if( pCur->bPoint ){
144764      int ii;
144765      pNew = rtreeEnqueue(pCur, rScore, iLevel);
144766      if( pNew==0 ) return 0;
144767      ii = (int)(pNew - pCur->aPoint) + 1;
144768      if( ii<RTREE_CACHE_SZ ){
144769        assert( pCur->aNode[ii]==0 );
144770        pCur->aNode[ii] = pCur->aNode[0];
144771       }else{
144772        nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
144773      }
144774      pCur->aNode[0] = 0;
144775      *pNew = pCur->sPoint;
144776    }
144777    pCur->sPoint.rScore = rScore;
144778    pCur->sPoint.iLevel = iLevel;
144779    pCur->bPoint = 1;
144780    return &pCur->sPoint;
144781  }else{
144782    return rtreeEnqueue(pCur, rScore, iLevel);
144783  }
144784}
144785
144786#if 0
144787/* Tracing routines for the RtreeSearchPoint queue */
144788static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
144789  if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
144790  printf(" %d.%05lld.%02d %g %d",
144791    p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
144792  );
144793  idx++;
144794  if( idx<RTREE_CACHE_SZ ){
144795    printf(" %p\n", pCur->aNode[idx]);
144796  }else{
144797    printf("\n");
144798  }
144799}
144800static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
144801  int ii;
144802  printf("=== %9s ", zPrefix);
144803  if( pCur->bPoint ){
144804    tracePoint(&pCur->sPoint, -1, pCur);
144805  }
144806  for(ii=0; ii<pCur->nPoint; ii++){
144807    if( ii>0 || pCur->bPoint ) printf("              ");
144808    tracePoint(&pCur->aPoint[ii], ii, pCur);
144809  }
144810}
144811# define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
144812#else
144813# define RTREE_QUEUE_TRACE(A,B)   /* no-op */
144814#endif
144815
144816/* Remove the search point with the lowest current score.
144817*/
144818static void rtreeSearchPointPop(RtreeCursor *p){
144819  int i, j, k, n;
144820  i = 1 - p->bPoint;
144821  assert( i==0 || i==1 );
144822  if( p->aNode[i] ){
144823    nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
144824    p->aNode[i] = 0;
144825  }
144826  if( p->bPoint ){
144827    p->anQueue[p->sPoint.iLevel]--;
144828    p->bPoint = 0;
144829  }else if( p->nPoint ){
144830    p->anQueue[p->aPoint[0].iLevel]--;
144831    n = --p->nPoint;
144832    p->aPoint[0] = p->aPoint[n];
144833    if( n<RTREE_CACHE_SZ-1 ){
144834      p->aNode[1] = p->aNode[n+1];
144835      p->aNode[n+1] = 0;
144836    }
144837    i = 0;
144838    while( (j = i*2+1)<n ){
144839      k = j+1;
144840      if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
144841        if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
144842          rtreeSearchPointSwap(p, i, k);
144843          i = k;
144844        }else{
144845          break;
144846        }
144847      }else{
144848        if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
144849          rtreeSearchPointSwap(p, i, j);
144850          i = j;
144851        }else{
144852          break;
144853        }
144854      }
144855    }
144856  }
144857}
144858
144859
144860/*
144861** Continue the search on cursor pCur until the front of the queue
144862** contains an entry suitable for returning as a result-set row,
144863** or until the RtreeSearchPoint queue is empty, indicating that the
144864** query has completed.
144865*/
144866static int rtreeStepToLeaf(RtreeCursor *pCur){
144867  RtreeSearchPoint *p;
144868  Rtree *pRtree = RTREE_OF_CURSOR(pCur);
144869  RtreeNode *pNode;
144870  int eWithin;
144871  int rc = SQLITE_OK;
144872  int nCell;
144873  int nConstraint = pCur->nConstraint;
144874  int ii;
144875  int eInt;
144876  RtreeSearchPoint x;
144877
144878  eInt = pRtree->eCoordType==RTREE_COORD_INT32;
144879  while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
144880    pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
144881    if( rc ) return rc;
144882    nCell = NCELL(pNode);
144883    assert( nCell<200 );
144884    while( p->iCell<nCell ){
144885      sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
144886      u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
144887      eWithin = FULLY_WITHIN;
144888      for(ii=0; ii<nConstraint; ii++){
144889        RtreeConstraint *pConstraint = pCur->aConstraint + ii;
144890        if( pConstraint->op>=RTREE_MATCH ){
144891          rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
144892                                       &rScore, &eWithin);
144893          if( rc ) return rc;
144894        }else if( p->iLevel==1 ){
144895          rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
144896        }else{
144897          rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
144898        }
144899        if( eWithin==NOT_WITHIN ) break;
144900      }
144901      p->iCell++;
144902      if( eWithin==NOT_WITHIN ) continue;
144903      x.iLevel = p->iLevel - 1;
144904      if( x.iLevel ){
144905        x.id = readInt64(pCellData);
144906        x.iCell = 0;
144907      }else{
144908        x.id = p->id;
144909        x.iCell = p->iCell - 1;
144910      }
144911      if( p->iCell>=nCell ){
144912        RTREE_QUEUE_TRACE(pCur, "POP-S:");
144913        rtreeSearchPointPop(pCur);
144914      }
144915      if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
144916      p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
144917      if( p==0 ) return SQLITE_NOMEM;
144918      p->eWithin = eWithin;
144919      p->id = x.id;
144920      p->iCell = x.iCell;
144921      RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
144922      break;
144923    }
144924    if( p->iCell>=nCell ){
144925      RTREE_QUEUE_TRACE(pCur, "POP-Se:");
144926      rtreeSearchPointPop(pCur);
144927    }
144928  }
144929  pCur->atEOF = p==0;
144930  return SQLITE_OK;
144931}
144932
144933/*
144934** Rtree virtual table module xNext method.
144935*/
144936static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
144937  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
144938  int rc = SQLITE_OK;
144939
144940  /* Move to the next entry that matches the configured constraints. */
144941  RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
144942  rtreeSearchPointPop(pCsr);
144943  rc = rtreeStepToLeaf(pCsr);
144944  return rc;
144945}
144946
144947/*
144948** Rtree virtual table module xRowid method.
144949*/
144950static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
144951  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
144952  RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
144953  int rc = SQLITE_OK;
144954  RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
144955  if( rc==SQLITE_OK && p ){
144956    *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
144957  }
144958  return rc;
144959}
144960
144961/*
144962** Rtree virtual table module xColumn method.
144963*/
144964static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
144965  Rtree *pRtree = (Rtree *)cur->pVtab;
144966  RtreeCursor *pCsr = (RtreeCursor *)cur;
144967  RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
144968  RtreeCoord c;
144969  int rc = SQLITE_OK;
144970  RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
144971
144972  if( rc ) return rc;
144973  if( p==0 ) return SQLITE_OK;
144974  if( i==0 ){
144975    sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
144976  }else{
144977    if( rc ) return rc;
144978    nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
144979#ifndef SQLITE_RTREE_INT_ONLY
144980    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
144981      sqlite3_result_double(ctx, c.f);
144982    }else
144983#endif
144984    {
144985      assert( pRtree->eCoordType==RTREE_COORD_INT32 );
144986      sqlite3_result_int(ctx, c.i);
144987    }
144988  }
144989  return SQLITE_OK;
144990}
144991
144992/*
144993** Use nodeAcquire() to obtain the leaf node containing the record with
144994** rowid iRowid. If successful, set *ppLeaf to point to the node and
144995** return SQLITE_OK. If there is no such record in the table, set
144996** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
144997** to zero and return an SQLite error code.
144998*/
144999static int findLeafNode(
145000  Rtree *pRtree,              /* RTree to search */
145001  i64 iRowid,                 /* The rowid searching for */
145002  RtreeNode **ppLeaf,         /* Write the node here */
145003  sqlite3_int64 *piNode       /* Write the node-id here */
145004){
145005  int rc;
145006  *ppLeaf = 0;
145007  sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
145008  if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
145009    i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
145010    if( piNode ) *piNode = iNode;
145011    rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
145012    sqlite3_reset(pRtree->pReadRowid);
145013  }else{
145014    rc = sqlite3_reset(pRtree->pReadRowid);
145015  }
145016  return rc;
145017}
145018
145019/*
145020** This function is called to configure the RtreeConstraint object passed
145021** as the second argument for a MATCH constraint. The value passed as the
145022** first argument to this function is the right-hand operand to the MATCH
145023** operator.
145024*/
145025static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
145026  RtreeMatchArg *pBlob;              /* BLOB returned by geometry function */
145027  sqlite3_rtree_query_info *pInfo;   /* Callback information */
145028  int nBlob;                         /* Size of the geometry function blob */
145029  int nExpected;                     /* Expected size of the BLOB */
145030
145031  /* Check that value is actually a blob. */
145032  if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
145033
145034  /* Check that the blob is roughly the right size. */
145035  nBlob = sqlite3_value_bytes(pValue);
145036  if( nBlob<(int)sizeof(RtreeMatchArg)
145037   || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0
145038  ){
145039    return SQLITE_ERROR;
145040  }
145041
145042  pInfo = (sqlite3_rtree_query_info*)sqlite3_malloc( sizeof(*pInfo)+nBlob );
145043  if( !pInfo ) return SQLITE_NOMEM;
145044  memset(pInfo, 0, sizeof(*pInfo));
145045  pBlob = (RtreeMatchArg*)&pInfo[1];
145046
145047  memcpy(pBlob, sqlite3_value_blob(pValue), nBlob);
145048  nExpected = (int)(sizeof(RtreeMatchArg) +
145049                    (pBlob->nParam-1)*sizeof(RtreeDValue));
145050  if( pBlob->magic!=RTREE_GEOMETRY_MAGIC || nBlob!=nExpected ){
145051    sqlite3_free(pInfo);
145052    return SQLITE_ERROR;
145053  }
145054  pInfo->pContext = pBlob->cb.pContext;
145055  pInfo->nParam = pBlob->nParam;
145056  pInfo->aParam = pBlob->aParam;
145057
145058  if( pBlob->cb.xGeom ){
145059    pCons->u.xGeom = pBlob->cb.xGeom;
145060  }else{
145061    pCons->op = RTREE_QUERY;
145062    pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
145063  }
145064  pCons->pInfo = pInfo;
145065  return SQLITE_OK;
145066}
145067
145068/*
145069** Rtree virtual table module xFilter method.
145070*/
145071static int rtreeFilter(
145072  sqlite3_vtab_cursor *pVtabCursor,
145073  int idxNum, const char *idxStr,
145074  int argc, sqlite3_value **argv
145075){
145076  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
145077  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
145078  RtreeNode *pRoot = 0;
145079  int ii;
145080  int rc = SQLITE_OK;
145081  int iCell = 0;
145082
145083  rtreeReference(pRtree);
145084
145085  freeCursorConstraints(pCsr);
145086  pCsr->iStrategy = idxNum;
145087
145088  if( idxNum==1 ){
145089    /* Special case - lookup by rowid. */
145090    RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
145091    RtreeSearchPoint *p;     /* Search point for the the leaf */
145092    i64 iRowid = sqlite3_value_int64(argv[0]);
145093    i64 iNode = 0;
145094    rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
145095    if( rc==SQLITE_OK && pLeaf!=0 ){
145096      p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
145097      assert( p!=0 );  /* Always returns pCsr->sPoint */
145098      pCsr->aNode[0] = pLeaf;
145099      p->id = iNode;
145100      p->eWithin = PARTLY_WITHIN;
145101      rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
145102      p->iCell = iCell;
145103      RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
145104    }else{
145105      pCsr->atEOF = 1;
145106    }
145107  }else{
145108    /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
145109    ** with the configured constraints.
145110    */
145111    rc = nodeAcquire(pRtree, 1, 0, &pRoot);
145112    if( rc==SQLITE_OK && argc>0 ){
145113      pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
145114      pCsr->nConstraint = argc;
145115      if( !pCsr->aConstraint ){
145116        rc = SQLITE_NOMEM;
145117      }else{
145118        memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
145119        memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
145120        assert( (idxStr==0 && argc==0)
145121                || (idxStr && (int)strlen(idxStr)==argc*2) );
145122        for(ii=0; ii<argc; ii++){
145123          RtreeConstraint *p = &pCsr->aConstraint[ii];
145124          p->op = idxStr[ii*2];
145125          p->iCoord = idxStr[ii*2+1]-'0';
145126          if( p->op>=RTREE_MATCH ){
145127            /* A MATCH operator. The right-hand-side must be a blob that
145128            ** can be cast into an RtreeMatchArg object. One created using
145129            ** an sqlite3_rtree_geometry_callback() SQL user function.
145130            */
145131            rc = deserializeGeometry(argv[ii], p);
145132            if( rc!=SQLITE_OK ){
145133              break;
145134            }
145135            p->pInfo->nCoord = pRtree->nDim*2;
145136            p->pInfo->anQueue = pCsr->anQueue;
145137            p->pInfo->mxLevel = pRtree->iDepth + 1;
145138          }else{
145139#ifdef SQLITE_RTREE_INT_ONLY
145140            p->u.rValue = sqlite3_value_int64(argv[ii]);
145141#else
145142            p->u.rValue = sqlite3_value_double(argv[ii]);
145143#endif
145144          }
145145        }
145146      }
145147    }
145148    if( rc==SQLITE_OK ){
145149      RtreeSearchPoint *pNew;
145150      pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, pRtree->iDepth+1);
145151      if( pNew==0 ) return SQLITE_NOMEM;
145152      pNew->id = 1;
145153      pNew->iCell = 0;
145154      pNew->eWithin = PARTLY_WITHIN;
145155      assert( pCsr->bPoint==1 );
145156      pCsr->aNode[0] = pRoot;
145157      pRoot = 0;
145158      RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
145159      rc = rtreeStepToLeaf(pCsr);
145160    }
145161  }
145162
145163  nodeRelease(pRtree, pRoot);
145164  rtreeRelease(pRtree);
145165  return rc;
145166}
145167
145168/*
145169** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
145170** extension is currently being used by a version of SQLite too old to
145171** support estimatedRows. In that case this function is a no-op.
145172*/
145173static void setEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
145174#if SQLITE_VERSION_NUMBER>=3008002
145175  if( sqlite3_libversion_number()>=3008002 ){
145176    pIdxInfo->estimatedRows = nRow;
145177  }
145178#endif
145179}
145180
145181/*
145182** Rtree virtual table module xBestIndex method. There are three
145183** table scan strategies to choose from (in order from most to
145184** least desirable):
145185**
145186**   idxNum     idxStr        Strategy
145187**   ------------------------------------------------
145188**     1        Unused        Direct lookup by rowid.
145189**     2        See below     R-tree query or full-table scan.
145190**   ------------------------------------------------
145191**
145192** If strategy 1 is used, then idxStr is not meaningful. If strategy
145193** 2 is used, idxStr is formatted to contain 2 bytes for each
145194** constraint used. The first two bytes of idxStr correspond to
145195** the constraint in sqlite3_index_info.aConstraintUsage[] with
145196** (argvIndex==1) etc.
145197**
145198** The first of each pair of bytes in idxStr identifies the constraint
145199** operator as follows:
145200**
145201**   Operator    Byte Value
145202**   ----------------------
145203**      =        0x41 ('A')
145204**     <=        0x42 ('B')
145205**      <        0x43 ('C')
145206**     >=        0x44 ('D')
145207**      >        0x45 ('E')
145208**   MATCH       0x46 ('F')
145209**   ----------------------
145210**
145211** The second of each pair of bytes identifies the coordinate column
145212** to which the constraint applies. The leftmost coordinate column
145213** is 'a', the second from the left 'b' etc.
145214*/
145215static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
145216  Rtree *pRtree = (Rtree*)tab;
145217  int rc = SQLITE_OK;
145218  int ii;
145219  i64 nRow;                       /* Estimated rows returned by this scan */
145220
145221  int iIdx = 0;
145222  char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
145223  memset(zIdxStr, 0, sizeof(zIdxStr));
145224
145225  assert( pIdxInfo->idxStr==0 );
145226  for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
145227    struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
145228
145229    if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
145230      /* We have an equality constraint on the rowid. Use strategy 1. */
145231      int jj;
145232      for(jj=0; jj<ii; jj++){
145233        pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
145234        pIdxInfo->aConstraintUsage[jj].omit = 0;
145235      }
145236      pIdxInfo->idxNum = 1;
145237      pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
145238      pIdxInfo->aConstraintUsage[jj].omit = 1;
145239
145240      /* This strategy involves a two rowid lookups on an B-Tree structures
145241      ** and then a linear search of an R-Tree node. This should be
145242      ** considered almost as quick as a direct rowid lookup (for which
145243      ** sqlite uses an internal cost of 0.0). It is expected to return
145244      ** a single row.
145245      */
145246      pIdxInfo->estimatedCost = 30.0;
145247      setEstimatedRows(pIdxInfo, 1);
145248      return SQLITE_OK;
145249    }
145250
145251    if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
145252      u8 op;
145253      switch( p->op ){
145254        case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
145255        case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
145256        case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
145257        case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
145258        case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
145259        default:
145260          assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
145261          op = RTREE_MATCH;
145262          break;
145263      }
145264      zIdxStr[iIdx++] = op;
145265      zIdxStr[iIdx++] = p->iColumn - 1 + '0';
145266      pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
145267      pIdxInfo->aConstraintUsage[ii].omit = 1;
145268    }
145269  }
145270
145271  pIdxInfo->idxNum = 2;
145272  pIdxInfo->needToFreeIdxStr = 1;
145273  if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
145274    return SQLITE_NOMEM;
145275  }
145276
145277  nRow = pRtree->nRowEst / (iIdx + 1);
145278  pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
145279  setEstimatedRows(pIdxInfo, nRow);
145280
145281  return rc;
145282}
145283
145284/*
145285** Return the N-dimensional volumn of the cell stored in *p.
145286*/
145287static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
145288  RtreeDValue area = (RtreeDValue)1;
145289  int ii;
145290  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
145291    area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
145292  }
145293  return area;
145294}
145295
145296/*
145297** Return the margin length of cell p. The margin length is the sum
145298** of the objects size in each dimension.
145299*/
145300static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
145301  RtreeDValue margin = (RtreeDValue)0;
145302  int ii;
145303  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
145304    margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
145305  }
145306  return margin;
145307}
145308
145309/*
145310** Store the union of cells p1 and p2 in p1.
145311*/
145312static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
145313  int ii;
145314  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
145315    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
145316      p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
145317      p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
145318    }
145319  }else{
145320    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
145321      p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
145322      p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
145323    }
145324  }
145325}
145326
145327/*
145328** Return true if the area covered by p2 is a subset of the area covered
145329** by p1. False otherwise.
145330*/
145331static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
145332  int ii;
145333  int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
145334  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
145335    RtreeCoord *a1 = &p1->aCoord[ii];
145336    RtreeCoord *a2 = &p2->aCoord[ii];
145337    if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
145338     || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
145339    ){
145340      return 0;
145341    }
145342  }
145343  return 1;
145344}
145345
145346/*
145347** Return the amount cell p would grow by if it were unioned with pCell.
145348*/
145349static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
145350  RtreeDValue area;
145351  RtreeCell cell;
145352  memcpy(&cell, p, sizeof(RtreeCell));
145353  area = cellArea(pRtree, &cell);
145354  cellUnion(pRtree, &cell, pCell);
145355  return (cellArea(pRtree, &cell)-area);
145356}
145357
145358static RtreeDValue cellOverlap(
145359  Rtree *pRtree,
145360  RtreeCell *p,
145361  RtreeCell *aCell,
145362  int nCell
145363){
145364  int ii;
145365  RtreeDValue overlap = RTREE_ZERO;
145366  for(ii=0; ii<nCell; ii++){
145367    int jj;
145368    RtreeDValue o = (RtreeDValue)1;
145369    for(jj=0; jj<(pRtree->nDim*2); jj+=2){
145370      RtreeDValue x1, x2;
145371      x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
145372      x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
145373      if( x2<x1 ){
145374        o = (RtreeDValue)0;
145375        break;
145376      }else{
145377        o = o * (x2-x1);
145378      }
145379    }
145380    overlap += o;
145381  }
145382  return overlap;
145383}
145384
145385
145386/*
145387** This function implements the ChooseLeaf algorithm from Gutman[84].
145388** ChooseSubTree in r*tree terminology.
145389*/
145390static int ChooseLeaf(
145391  Rtree *pRtree,               /* Rtree table */
145392  RtreeCell *pCell,            /* Cell to insert into rtree */
145393  int iHeight,                 /* Height of sub-tree rooted at pCell */
145394  RtreeNode **ppLeaf           /* OUT: Selected leaf page */
145395){
145396  int rc;
145397  int ii;
145398  RtreeNode *pNode;
145399  rc = nodeAcquire(pRtree, 1, 0, &pNode);
145400
145401  for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
145402    int iCell;
145403    sqlite3_int64 iBest = 0;
145404
145405    RtreeDValue fMinGrowth = RTREE_ZERO;
145406    RtreeDValue fMinArea = RTREE_ZERO;
145407
145408    int nCell = NCELL(pNode);
145409    RtreeCell cell;
145410    RtreeNode *pChild;
145411
145412    RtreeCell *aCell = 0;
145413
145414    /* Select the child node which will be enlarged the least if pCell
145415    ** is inserted into it. Resolve ties by choosing the entry with
145416    ** the smallest area.
145417    */
145418    for(iCell=0; iCell<nCell; iCell++){
145419      int bBest = 0;
145420      RtreeDValue growth;
145421      RtreeDValue area;
145422      nodeGetCell(pRtree, pNode, iCell, &cell);
145423      growth = cellGrowth(pRtree, &cell, pCell);
145424      area = cellArea(pRtree, &cell);
145425      if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
145426        bBest = 1;
145427      }
145428      if( bBest ){
145429        fMinGrowth = growth;
145430        fMinArea = area;
145431        iBest = cell.iRowid;
145432      }
145433    }
145434
145435    sqlite3_free(aCell);
145436    rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
145437    nodeRelease(pRtree, pNode);
145438    pNode = pChild;
145439  }
145440
145441  *ppLeaf = pNode;
145442  return rc;
145443}
145444
145445/*
145446** A cell with the same content as pCell has just been inserted into
145447** the node pNode. This function updates the bounding box cells in
145448** all ancestor elements.
145449*/
145450static int AdjustTree(
145451  Rtree *pRtree,                    /* Rtree table */
145452  RtreeNode *pNode,                 /* Adjust ancestry of this node. */
145453  RtreeCell *pCell                  /* This cell was just inserted */
145454){
145455  RtreeNode *p = pNode;
145456  while( p->pParent ){
145457    RtreeNode *pParent = p->pParent;
145458    RtreeCell cell;
145459    int iCell;
145460
145461    if( nodeParentIndex(pRtree, p, &iCell) ){
145462      return SQLITE_CORRUPT_VTAB;
145463    }
145464
145465    nodeGetCell(pRtree, pParent, iCell, &cell);
145466    if( !cellContains(pRtree, &cell, pCell) ){
145467      cellUnion(pRtree, &cell, pCell);
145468      nodeOverwriteCell(pRtree, pParent, &cell, iCell);
145469    }
145470
145471    p = pParent;
145472  }
145473  return SQLITE_OK;
145474}
145475
145476/*
145477** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
145478*/
145479static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
145480  sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
145481  sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
145482  sqlite3_step(pRtree->pWriteRowid);
145483  return sqlite3_reset(pRtree->pWriteRowid);
145484}
145485
145486/*
145487** Write mapping (iNode->iPar) to the <rtree>_parent table.
145488*/
145489static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
145490  sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
145491  sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
145492  sqlite3_step(pRtree->pWriteParent);
145493  return sqlite3_reset(pRtree->pWriteParent);
145494}
145495
145496static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
145497
145498
145499/*
145500** Arguments aIdx, aDistance and aSpare all point to arrays of size
145501** nIdx. The aIdx array contains the set of integers from 0 to
145502** (nIdx-1) in no particular order. This function sorts the values
145503** in aIdx according to the indexed values in aDistance. For
145504** example, assuming the inputs:
145505**
145506**   aIdx      = { 0,   1,   2,   3 }
145507**   aDistance = { 5.0, 2.0, 7.0, 6.0 }
145508**
145509** this function sets the aIdx array to contain:
145510**
145511**   aIdx      = { 0,   1,   2,   3 }
145512**
145513** The aSpare array is used as temporary working space by the
145514** sorting algorithm.
145515*/
145516static void SortByDistance(
145517  int *aIdx,
145518  int nIdx,
145519  RtreeDValue *aDistance,
145520  int *aSpare
145521){
145522  if( nIdx>1 ){
145523    int iLeft = 0;
145524    int iRight = 0;
145525
145526    int nLeft = nIdx/2;
145527    int nRight = nIdx-nLeft;
145528    int *aLeft = aIdx;
145529    int *aRight = &aIdx[nLeft];
145530
145531    SortByDistance(aLeft, nLeft, aDistance, aSpare);
145532    SortByDistance(aRight, nRight, aDistance, aSpare);
145533
145534    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
145535    aLeft = aSpare;
145536
145537    while( iLeft<nLeft || iRight<nRight ){
145538      if( iLeft==nLeft ){
145539        aIdx[iLeft+iRight] = aRight[iRight];
145540        iRight++;
145541      }else if( iRight==nRight ){
145542        aIdx[iLeft+iRight] = aLeft[iLeft];
145543        iLeft++;
145544      }else{
145545        RtreeDValue fLeft = aDistance[aLeft[iLeft]];
145546        RtreeDValue fRight = aDistance[aRight[iRight]];
145547        if( fLeft<fRight ){
145548          aIdx[iLeft+iRight] = aLeft[iLeft];
145549          iLeft++;
145550        }else{
145551          aIdx[iLeft+iRight] = aRight[iRight];
145552          iRight++;
145553        }
145554      }
145555    }
145556
145557#if 0
145558    /* Check that the sort worked */
145559    {
145560      int jj;
145561      for(jj=1; jj<nIdx; jj++){
145562        RtreeDValue left = aDistance[aIdx[jj-1]];
145563        RtreeDValue right = aDistance[aIdx[jj]];
145564        assert( left<=right );
145565      }
145566    }
145567#endif
145568  }
145569}
145570
145571/*
145572** Arguments aIdx, aCell and aSpare all point to arrays of size
145573** nIdx. The aIdx array contains the set of integers from 0 to
145574** (nIdx-1) in no particular order. This function sorts the values
145575** in aIdx according to dimension iDim of the cells in aCell. The
145576** minimum value of dimension iDim is considered first, the
145577** maximum used to break ties.
145578**
145579** The aSpare array is used as temporary working space by the
145580** sorting algorithm.
145581*/
145582static void SortByDimension(
145583  Rtree *pRtree,
145584  int *aIdx,
145585  int nIdx,
145586  int iDim,
145587  RtreeCell *aCell,
145588  int *aSpare
145589){
145590  if( nIdx>1 ){
145591
145592    int iLeft = 0;
145593    int iRight = 0;
145594
145595    int nLeft = nIdx/2;
145596    int nRight = nIdx-nLeft;
145597    int *aLeft = aIdx;
145598    int *aRight = &aIdx[nLeft];
145599
145600    SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
145601    SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
145602
145603    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
145604    aLeft = aSpare;
145605    while( iLeft<nLeft || iRight<nRight ){
145606      RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
145607      RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
145608      RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
145609      RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
145610      if( (iLeft!=nLeft) && ((iRight==nRight)
145611       || (xleft1<xright1)
145612       || (xleft1==xright1 && xleft2<xright2)
145613      )){
145614        aIdx[iLeft+iRight] = aLeft[iLeft];
145615        iLeft++;
145616      }else{
145617        aIdx[iLeft+iRight] = aRight[iRight];
145618        iRight++;
145619      }
145620    }
145621
145622#if 0
145623    /* Check that the sort worked */
145624    {
145625      int jj;
145626      for(jj=1; jj<nIdx; jj++){
145627        RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
145628        RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
145629        RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
145630        RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
145631        assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
145632      }
145633    }
145634#endif
145635  }
145636}
145637
145638/*
145639** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
145640*/
145641static int splitNodeStartree(
145642  Rtree *pRtree,
145643  RtreeCell *aCell,
145644  int nCell,
145645  RtreeNode *pLeft,
145646  RtreeNode *pRight,
145647  RtreeCell *pBboxLeft,
145648  RtreeCell *pBboxRight
145649){
145650  int **aaSorted;
145651  int *aSpare;
145652  int ii;
145653
145654  int iBestDim = 0;
145655  int iBestSplit = 0;
145656  RtreeDValue fBestMargin = RTREE_ZERO;
145657
145658  int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
145659
145660  aaSorted = (int **)sqlite3_malloc(nByte);
145661  if( !aaSorted ){
145662    return SQLITE_NOMEM;
145663  }
145664
145665  aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
145666  memset(aaSorted, 0, nByte);
145667  for(ii=0; ii<pRtree->nDim; ii++){
145668    int jj;
145669    aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
145670    for(jj=0; jj<nCell; jj++){
145671      aaSorted[ii][jj] = jj;
145672    }
145673    SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
145674  }
145675
145676  for(ii=0; ii<pRtree->nDim; ii++){
145677    RtreeDValue margin = RTREE_ZERO;
145678    RtreeDValue fBestOverlap = RTREE_ZERO;
145679    RtreeDValue fBestArea = RTREE_ZERO;
145680    int iBestLeft = 0;
145681    int nLeft;
145682
145683    for(
145684      nLeft=RTREE_MINCELLS(pRtree);
145685      nLeft<=(nCell-RTREE_MINCELLS(pRtree));
145686      nLeft++
145687    ){
145688      RtreeCell left;
145689      RtreeCell right;
145690      int kk;
145691      RtreeDValue overlap;
145692      RtreeDValue area;
145693
145694      memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
145695      memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
145696      for(kk=1; kk<(nCell-1); kk++){
145697        if( kk<nLeft ){
145698          cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
145699        }else{
145700          cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
145701        }
145702      }
145703      margin += cellMargin(pRtree, &left);
145704      margin += cellMargin(pRtree, &right);
145705      overlap = cellOverlap(pRtree, &left, &right, 1);
145706      area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
145707      if( (nLeft==RTREE_MINCELLS(pRtree))
145708       || (overlap<fBestOverlap)
145709       || (overlap==fBestOverlap && area<fBestArea)
145710      ){
145711        iBestLeft = nLeft;
145712        fBestOverlap = overlap;
145713        fBestArea = area;
145714      }
145715    }
145716
145717    if( ii==0 || margin<fBestMargin ){
145718      iBestDim = ii;
145719      fBestMargin = margin;
145720      iBestSplit = iBestLeft;
145721    }
145722  }
145723
145724  memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
145725  memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
145726  for(ii=0; ii<nCell; ii++){
145727    RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
145728    RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
145729    RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
145730    nodeInsertCell(pRtree, pTarget, pCell);
145731    cellUnion(pRtree, pBbox, pCell);
145732  }
145733
145734  sqlite3_free(aaSorted);
145735  return SQLITE_OK;
145736}
145737
145738
145739static int updateMapping(
145740  Rtree *pRtree,
145741  i64 iRowid,
145742  RtreeNode *pNode,
145743  int iHeight
145744){
145745  int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
145746  xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
145747  if( iHeight>0 ){
145748    RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
145749    if( pChild ){
145750      nodeRelease(pRtree, pChild->pParent);
145751      nodeReference(pNode);
145752      pChild->pParent = pNode;
145753    }
145754  }
145755  return xSetMapping(pRtree, iRowid, pNode->iNode);
145756}
145757
145758static int SplitNode(
145759  Rtree *pRtree,
145760  RtreeNode *pNode,
145761  RtreeCell *pCell,
145762  int iHeight
145763){
145764  int i;
145765  int newCellIsRight = 0;
145766
145767  int rc = SQLITE_OK;
145768  int nCell = NCELL(pNode);
145769  RtreeCell *aCell;
145770  int *aiUsed;
145771
145772  RtreeNode *pLeft = 0;
145773  RtreeNode *pRight = 0;
145774
145775  RtreeCell leftbbox;
145776  RtreeCell rightbbox;
145777
145778  /* Allocate an array and populate it with a copy of pCell and
145779  ** all cells from node pLeft. Then zero the original node.
145780  */
145781  aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
145782  if( !aCell ){
145783    rc = SQLITE_NOMEM;
145784    goto splitnode_out;
145785  }
145786  aiUsed = (int *)&aCell[nCell+1];
145787  memset(aiUsed, 0, sizeof(int)*(nCell+1));
145788  for(i=0; i<nCell; i++){
145789    nodeGetCell(pRtree, pNode, i, &aCell[i]);
145790  }
145791  nodeZero(pRtree, pNode);
145792  memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
145793  nCell++;
145794
145795  if( pNode->iNode==1 ){
145796    pRight = nodeNew(pRtree, pNode);
145797    pLeft = nodeNew(pRtree, pNode);
145798    pRtree->iDepth++;
145799    pNode->isDirty = 1;
145800    writeInt16(pNode->zData, pRtree->iDepth);
145801  }else{
145802    pLeft = pNode;
145803    pRight = nodeNew(pRtree, pLeft->pParent);
145804    nodeReference(pLeft);
145805  }
145806
145807  if( !pLeft || !pRight ){
145808    rc = SQLITE_NOMEM;
145809    goto splitnode_out;
145810  }
145811
145812  memset(pLeft->zData, 0, pRtree->iNodeSize);
145813  memset(pRight->zData, 0, pRtree->iNodeSize);
145814
145815  rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
145816                         &leftbbox, &rightbbox);
145817  if( rc!=SQLITE_OK ){
145818    goto splitnode_out;
145819  }
145820
145821  /* Ensure both child nodes have node numbers assigned to them by calling
145822  ** nodeWrite(). Node pRight always needs a node number, as it was created
145823  ** by nodeNew() above. But node pLeft sometimes already has a node number.
145824  ** In this case avoid the all to nodeWrite().
145825  */
145826  if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
145827   || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
145828  ){
145829    goto splitnode_out;
145830  }
145831
145832  rightbbox.iRowid = pRight->iNode;
145833  leftbbox.iRowid = pLeft->iNode;
145834
145835  if( pNode->iNode==1 ){
145836    rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
145837    if( rc!=SQLITE_OK ){
145838      goto splitnode_out;
145839    }
145840  }else{
145841    RtreeNode *pParent = pLeft->pParent;
145842    int iCell;
145843    rc = nodeParentIndex(pRtree, pLeft, &iCell);
145844    if( rc==SQLITE_OK ){
145845      nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
145846      rc = AdjustTree(pRtree, pParent, &leftbbox);
145847    }
145848    if( rc!=SQLITE_OK ){
145849      goto splitnode_out;
145850    }
145851  }
145852  if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
145853    goto splitnode_out;
145854  }
145855
145856  for(i=0; i<NCELL(pRight); i++){
145857    i64 iRowid = nodeGetRowid(pRtree, pRight, i);
145858    rc = updateMapping(pRtree, iRowid, pRight, iHeight);
145859    if( iRowid==pCell->iRowid ){
145860      newCellIsRight = 1;
145861    }
145862    if( rc!=SQLITE_OK ){
145863      goto splitnode_out;
145864    }
145865  }
145866  if( pNode->iNode==1 ){
145867    for(i=0; i<NCELL(pLeft); i++){
145868      i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
145869      rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
145870      if( rc!=SQLITE_OK ){
145871        goto splitnode_out;
145872      }
145873    }
145874  }else if( newCellIsRight==0 ){
145875    rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
145876  }
145877
145878  if( rc==SQLITE_OK ){
145879    rc = nodeRelease(pRtree, pRight);
145880    pRight = 0;
145881  }
145882  if( rc==SQLITE_OK ){
145883    rc = nodeRelease(pRtree, pLeft);
145884    pLeft = 0;
145885  }
145886
145887splitnode_out:
145888  nodeRelease(pRtree, pRight);
145889  nodeRelease(pRtree, pLeft);
145890  sqlite3_free(aCell);
145891  return rc;
145892}
145893
145894/*
145895** If node pLeaf is not the root of the r-tree and its pParent pointer is
145896** still NULL, load all ancestor nodes of pLeaf into memory and populate
145897** the pLeaf->pParent chain all the way up to the root node.
145898**
145899** This operation is required when a row is deleted (or updated - an update
145900** is implemented as a delete followed by an insert). SQLite provides the
145901** rowid of the row to delete, which can be used to find the leaf on which
145902** the entry resides (argument pLeaf). Once the leaf is located, this
145903** function is called to determine its ancestry.
145904*/
145905static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
145906  int rc = SQLITE_OK;
145907  RtreeNode *pChild = pLeaf;
145908  while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
145909    int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
145910    sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
145911    rc = sqlite3_step(pRtree->pReadParent);
145912    if( rc==SQLITE_ROW ){
145913      RtreeNode *pTest;           /* Used to test for reference loops */
145914      i64 iNode;                  /* Node number of parent node */
145915
145916      /* Before setting pChild->pParent, test that we are not creating a
145917      ** loop of references (as we would if, say, pChild==pParent). We don't
145918      ** want to do this as it leads to a memory leak when trying to delete
145919      ** the referenced counted node structures.
145920      */
145921      iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
145922      for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
145923      if( !pTest ){
145924        rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
145925      }
145926    }
145927    rc = sqlite3_reset(pRtree->pReadParent);
145928    if( rc==SQLITE_OK ) rc = rc2;
145929    if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
145930    pChild = pChild->pParent;
145931  }
145932  return rc;
145933}
145934
145935static int deleteCell(Rtree *, RtreeNode *, int, int);
145936
145937static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
145938  int rc;
145939  int rc2;
145940  RtreeNode *pParent = 0;
145941  int iCell;
145942
145943  assert( pNode->nRef==1 );
145944
145945  /* Remove the entry in the parent cell. */
145946  rc = nodeParentIndex(pRtree, pNode, &iCell);
145947  if( rc==SQLITE_OK ){
145948    pParent = pNode->pParent;
145949    pNode->pParent = 0;
145950    rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
145951  }
145952  rc2 = nodeRelease(pRtree, pParent);
145953  if( rc==SQLITE_OK ){
145954    rc = rc2;
145955  }
145956  if( rc!=SQLITE_OK ){
145957    return rc;
145958  }
145959
145960  /* Remove the xxx_node entry. */
145961  sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
145962  sqlite3_step(pRtree->pDeleteNode);
145963  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
145964    return rc;
145965  }
145966
145967  /* Remove the xxx_parent entry. */
145968  sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
145969  sqlite3_step(pRtree->pDeleteParent);
145970  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
145971    return rc;
145972  }
145973
145974  /* Remove the node from the in-memory hash table and link it into
145975  ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
145976  */
145977  nodeHashDelete(pRtree, pNode);
145978  pNode->iNode = iHeight;
145979  pNode->pNext = pRtree->pDeleted;
145980  pNode->nRef++;
145981  pRtree->pDeleted = pNode;
145982
145983  return SQLITE_OK;
145984}
145985
145986static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
145987  RtreeNode *pParent = pNode->pParent;
145988  int rc = SQLITE_OK;
145989  if( pParent ){
145990    int ii;
145991    int nCell = NCELL(pNode);
145992    RtreeCell box;                            /* Bounding box for pNode */
145993    nodeGetCell(pRtree, pNode, 0, &box);
145994    for(ii=1; ii<nCell; ii++){
145995      RtreeCell cell;
145996      nodeGetCell(pRtree, pNode, ii, &cell);
145997      cellUnion(pRtree, &box, &cell);
145998    }
145999    box.iRowid = pNode->iNode;
146000    rc = nodeParentIndex(pRtree, pNode, &ii);
146001    if( rc==SQLITE_OK ){
146002      nodeOverwriteCell(pRtree, pParent, &box, ii);
146003      rc = fixBoundingBox(pRtree, pParent);
146004    }
146005  }
146006  return rc;
146007}
146008
146009/*
146010** Delete the cell at index iCell of node pNode. After removing the
146011** cell, adjust the r-tree data structure if required.
146012*/
146013static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
146014  RtreeNode *pParent;
146015  int rc;
146016
146017  if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
146018    return rc;
146019  }
146020
146021  /* Remove the cell from the node. This call just moves bytes around
146022  ** the in-memory node image, so it cannot fail.
146023  */
146024  nodeDeleteCell(pRtree, pNode, iCell);
146025
146026  /* If the node is not the tree root and now has less than the minimum
146027  ** number of cells, remove it from the tree. Otherwise, update the
146028  ** cell in the parent node so that it tightly contains the updated
146029  ** node.
146030  */
146031  pParent = pNode->pParent;
146032  assert( pParent || pNode->iNode==1 );
146033  if( pParent ){
146034    if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
146035      rc = removeNode(pRtree, pNode, iHeight);
146036    }else{
146037      rc = fixBoundingBox(pRtree, pNode);
146038    }
146039  }
146040
146041  return rc;
146042}
146043
146044static int Reinsert(
146045  Rtree *pRtree,
146046  RtreeNode *pNode,
146047  RtreeCell *pCell,
146048  int iHeight
146049){
146050  int *aOrder;
146051  int *aSpare;
146052  RtreeCell *aCell;
146053  RtreeDValue *aDistance;
146054  int nCell;
146055  RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
146056  int iDim;
146057  int ii;
146058  int rc = SQLITE_OK;
146059  int n;
146060
146061  memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
146062
146063  nCell = NCELL(pNode)+1;
146064  n = (nCell+1)&(~1);
146065
146066  /* Allocate the buffers used by this operation. The allocation is
146067  ** relinquished before this function returns.
146068  */
146069  aCell = (RtreeCell *)sqlite3_malloc(n * (
146070    sizeof(RtreeCell)     +         /* aCell array */
146071    sizeof(int)           +         /* aOrder array */
146072    sizeof(int)           +         /* aSpare array */
146073    sizeof(RtreeDValue)             /* aDistance array */
146074  ));
146075  if( !aCell ){
146076    return SQLITE_NOMEM;
146077  }
146078  aOrder    = (int *)&aCell[n];
146079  aSpare    = (int *)&aOrder[n];
146080  aDistance = (RtreeDValue *)&aSpare[n];
146081
146082  for(ii=0; ii<nCell; ii++){
146083    if( ii==(nCell-1) ){
146084      memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
146085    }else{
146086      nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
146087    }
146088    aOrder[ii] = ii;
146089    for(iDim=0; iDim<pRtree->nDim; iDim++){
146090      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
146091      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
146092    }
146093  }
146094  for(iDim=0; iDim<pRtree->nDim; iDim++){
146095    aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
146096  }
146097
146098  for(ii=0; ii<nCell; ii++){
146099    aDistance[ii] = RTREE_ZERO;
146100    for(iDim=0; iDim<pRtree->nDim; iDim++){
146101      RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
146102                               DCOORD(aCell[ii].aCoord[iDim*2]));
146103      aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
146104    }
146105  }
146106
146107  SortByDistance(aOrder, nCell, aDistance, aSpare);
146108  nodeZero(pRtree, pNode);
146109
146110  for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
146111    RtreeCell *p = &aCell[aOrder[ii]];
146112    nodeInsertCell(pRtree, pNode, p);
146113    if( p->iRowid==pCell->iRowid ){
146114      if( iHeight==0 ){
146115        rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
146116      }else{
146117        rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
146118      }
146119    }
146120  }
146121  if( rc==SQLITE_OK ){
146122    rc = fixBoundingBox(pRtree, pNode);
146123  }
146124  for(; rc==SQLITE_OK && ii<nCell; ii++){
146125    /* Find a node to store this cell in. pNode->iNode currently contains
146126    ** the height of the sub-tree headed by the cell.
146127    */
146128    RtreeNode *pInsert;
146129    RtreeCell *p = &aCell[aOrder[ii]];
146130    rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
146131    if( rc==SQLITE_OK ){
146132      int rc2;
146133      rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
146134      rc2 = nodeRelease(pRtree, pInsert);
146135      if( rc==SQLITE_OK ){
146136        rc = rc2;
146137      }
146138    }
146139  }
146140
146141  sqlite3_free(aCell);
146142  return rc;
146143}
146144
146145/*
146146** Insert cell pCell into node pNode. Node pNode is the head of a
146147** subtree iHeight high (leaf nodes have iHeight==0).
146148*/
146149static int rtreeInsertCell(
146150  Rtree *pRtree,
146151  RtreeNode *pNode,
146152  RtreeCell *pCell,
146153  int iHeight
146154){
146155  int rc = SQLITE_OK;
146156  if( iHeight>0 ){
146157    RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
146158    if( pChild ){
146159      nodeRelease(pRtree, pChild->pParent);
146160      nodeReference(pNode);
146161      pChild->pParent = pNode;
146162    }
146163  }
146164  if( nodeInsertCell(pRtree, pNode, pCell) ){
146165    if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
146166      rc = SplitNode(pRtree, pNode, pCell, iHeight);
146167    }else{
146168      pRtree->iReinsertHeight = iHeight;
146169      rc = Reinsert(pRtree, pNode, pCell, iHeight);
146170    }
146171  }else{
146172    rc = AdjustTree(pRtree, pNode, pCell);
146173    if( rc==SQLITE_OK ){
146174      if( iHeight==0 ){
146175        rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
146176      }else{
146177        rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
146178      }
146179    }
146180  }
146181  return rc;
146182}
146183
146184static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
146185  int ii;
146186  int rc = SQLITE_OK;
146187  int nCell = NCELL(pNode);
146188
146189  for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
146190    RtreeNode *pInsert;
146191    RtreeCell cell;
146192    nodeGetCell(pRtree, pNode, ii, &cell);
146193
146194    /* Find a node to store this cell in. pNode->iNode currently contains
146195    ** the height of the sub-tree headed by the cell.
146196    */
146197    rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
146198    if( rc==SQLITE_OK ){
146199      int rc2;
146200      rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
146201      rc2 = nodeRelease(pRtree, pInsert);
146202      if( rc==SQLITE_OK ){
146203        rc = rc2;
146204      }
146205    }
146206  }
146207  return rc;
146208}
146209
146210/*
146211** Select a currently unused rowid for a new r-tree record.
146212*/
146213static int newRowid(Rtree *pRtree, i64 *piRowid){
146214  int rc;
146215  sqlite3_bind_null(pRtree->pWriteRowid, 1);
146216  sqlite3_bind_null(pRtree->pWriteRowid, 2);
146217  sqlite3_step(pRtree->pWriteRowid);
146218  rc = sqlite3_reset(pRtree->pWriteRowid);
146219  *piRowid = sqlite3_last_insert_rowid(pRtree->db);
146220  return rc;
146221}
146222
146223/*
146224** Remove the entry with rowid=iDelete from the r-tree structure.
146225*/
146226static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
146227  int rc;                         /* Return code */
146228  RtreeNode *pLeaf = 0;           /* Leaf node containing record iDelete */
146229  int iCell;                      /* Index of iDelete cell in pLeaf */
146230  RtreeNode *pRoot;               /* Root node of rtree structure */
146231
146232
146233  /* Obtain a reference to the root node to initialize Rtree.iDepth */
146234  rc = nodeAcquire(pRtree, 1, 0, &pRoot);
146235
146236  /* Obtain a reference to the leaf node that contains the entry
146237  ** about to be deleted.
146238  */
146239  if( rc==SQLITE_OK ){
146240    rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
146241  }
146242
146243  /* Delete the cell in question from the leaf node. */
146244  if( rc==SQLITE_OK ){
146245    int rc2;
146246    rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
146247    if( rc==SQLITE_OK ){
146248      rc = deleteCell(pRtree, pLeaf, iCell, 0);
146249    }
146250    rc2 = nodeRelease(pRtree, pLeaf);
146251    if( rc==SQLITE_OK ){
146252      rc = rc2;
146253    }
146254  }
146255
146256  /* Delete the corresponding entry in the <rtree>_rowid table. */
146257  if( rc==SQLITE_OK ){
146258    sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
146259    sqlite3_step(pRtree->pDeleteRowid);
146260    rc = sqlite3_reset(pRtree->pDeleteRowid);
146261  }
146262
146263  /* Check if the root node now has exactly one child. If so, remove
146264  ** it, schedule the contents of the child for reinsertion and
146265  ** reduce the tree height by one.
146266  **
146267  ** This is equivalent to copying the contents of the child into
146268  ** the root node (the operation that Gutman's paper says to perform
146269  ** in this scenario).
146270  */
146271  if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
146272    int rc2;
146273    RtreeNode *pChild;
146274    i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
146275    rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
146276    if( rc==SQLITE_OK ){
146277      rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
146278    }
146279    rc2 = nodeRelease(pRtree, pChild);
146280    if( rc==SQLITE_OK ) rc = rc2;
146281    if( rc==SQLITE_OK ){
146282      pRtree->iDepth--;
146283      writeInt16(pRoot->zData, pRtree->iDepth);
146284      pRoot->isDirty = 1;
146285    }
146286  }
146287
146288  /* Re-insert the contents of any underfull nodes removed from the tree. */
146289  for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
146290    if( rc==SQLITE_OK ){
146291      rc = reinsertNodeContent(pRtree, pLeaf);
146292    }
146293    pRtree->pDeleted = pLeaf->pNext;
146294    sqlite3_free(pLeaf);
146295  }
146296
146297  /* Release the reference to the root node. */
146298  if( rc==SQLITE_OK ){
146299    rc = nodeRelease(pRtree, pRoot);
146300  }else{
146301    nodeRelease(pRtree, pRoot);
146302  }
146303
146304  return rc;
146305}
146306
146307/*
146308** Rounding constants for float->double conversion.
146309*/
146310#define RNDTOWARDS  (1.0 - 1.0/8388608.0)  /* Round towards zero */
146311#define RNDAWAY     (1.0 + 1.0/8388608.0)  /* Round away from zero */
146312
146313#if !defined(SQLITE_RTREE_INT_ONLY)
146314/*
146315** Convert an sqlite3_value into an RtreeValue (presumably a float)
146316** while taking care to round toward negative or positive, respectively.
146317*/
146318static RtreeValue rtreeValueDown(sqlite3_value *v){
146319  double d = sqlite3_value_double(v);
146320  float f = (float)d;
146321  if( f>d ){
146322    f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
146323  }
146324  return f;
146325}
146326static RtreeValue rtreeValueUp(sqlite3_value *v){
146327  double d = sqlite3_value_double(v);
146328  float f = (float)d;
146329  if( f<d ){
146330    f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
146331  }
146332  return f;
146333}
146334#endif /* !defined(SQLITE_RTREE_INT_ONLY) */
146335
146336
146337/*
146338** The xUpdate method for rtree module virtual tables.
146339*/
146340static int rtreeUpdate(
146341  sqlite3_vtab *pVtab,
146342  int nData,
146343  sqlite3_value **azData,
146344  sqlite_int64 *pRowid
146345){
146346  Rtree *pRtree = (Rtree *)pVtab;
146347  int rc = SQLITE_OK;
146348  RtreeCell cell;                 /* New cell to insert if nData>1 */
146349  int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
146350
146351  rtreeReference(pRtree);
146352  assert(nData>=1);
146353
146354  /* Constraint handling. A write operation on an r-tree table may return
146355  ** SQLITE_CONSTRAINT for two reasons:
146356  **
146357  **   1. A duplicate rowid value, or
146358  **   2. The supplied data violates the "x2>=x1" constraint.
146359  **
146360  ** In the first case, if the conflict-handling mode is REPLACE, then
146361  ** the conflicting row can be removed before proceeding. In the second
146362  ** case, SQLITE_CONSTRAINT must be returned regardless of the
146363  ** conflict-handling mode specified by the user.
146364  */
146365  if( nData>1 ){
146366    int ii;
146367
146368    /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
146369    assert( nData==(pRtree->nDim*2 + 3) );
146370#ifndef SQLITE_RTREE_INT_ONLY
146371    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
146372      for(ii=0; ii<(pRtree->nDim*2); ii+=2){
146373        cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
146374        cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
146375        if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
146376          rc = SQLITE_CONSTRAINT;
146377          goto constraint;
146378        }
146379      }
146380    }else
146381#endif
146382    {
146383      for(ii=0; ii<(pRtree->nDim*2); ii+=2){
146384        cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
146385        cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
146386        if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
146387          rc = SQLITE_CONSTRAINT;
146388          goto constraint;
146389        }
146390      }
146391    }
146392
146393    /* If a rowid value was supplied, check if it is already present in
146394    ** the table. If so, the constraint has failed. */
146395    if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
146396      cell.iRowid = sqlite3_value_int64(azData[2]);
146397      if( sqlite3_value_type(azData[0])==SQLITE_NULL
146398       || sqlite3_value_int64(azData[0])!=cell.iRowid
146399      ){
146400        int steprc;
146401        sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
146402        steprc = sqlite3_step(pRtree->pReadRowid);
146403        rc = sqlite3_reset(pRtree->pReadRowid);
146404        if( SQLITE_ROW==steprc ){
146405          if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
146406            rc = rtreeDeleteRowid(pRtree, cell.iRowid);
146407          }else{
146408            rc = SQLITE_CONSTRAINT;
146409            goto constraint;
146410          }
146411        }
146412      }
146413      bHaveRowid = 1;
146414    }
146415  }
146416
146417  /* If azData[0] is not an SQL NULL value, it is the rowid of a
146418  ** record to delete from the r-tree table. The following block does
146419  ** just that.
146420  */
146421  if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
146422    rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
146423  }
146424
146425  /* If the azData[] array contains more than one element, elements
146426  ** (azData[2]..azData[argc-1]) contain a new record to insert into
146427  ** the r-tree structure.
146428  */
146429  if( rc==SQLITE_OK && nData>1 ){
146430    /* Insert the new record into the r-tree */
146431    RtreeNode *pLeaf = 0;
146432
146433    /* Figure out the rowid of the new row. */
146434    if( bHaveRowid==0 ){
146435      rc = newRowid(pRtree, &cell.iRowid);
146436    }
146437    *pRowid = cell.iRowid;
146438
146439    if( rc==SQLITE_OK ){
146440      rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
146441    }
146442    if( rc==SQLITE_OK ){
146443      int rc2;
146444      pRtree->iReinsertHeight = -1;
146445      rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
146446      rc2 = nodeRelease(pRtree, pLeaf);
146447      if( rc==SQLITE_OK ){
146448        rc = rc2;
146449      }
146450    }
146451  }
146452
146453constraint:
146454  rtreeRelease(pRtree);
146455  return rc;
146456}
146457
146458/*
146459** The xRename method for rtree module virtual tables.
146460*/
146461static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
146462  Rtree *pRtree = (Rtree *)pVtab;
146463  int rc = SQLITE_NOMEM;
146464  char *zSql = sqlite3_mprintf(
146465    "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
146466    "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
146467    "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
146468    , pRtree->zDb, pRtree->zName, zNewName
146469    , pRtree->zDb, pRtree->zName, zNewName
146470    , pRtree->zDb, pRtree->zName, zNewName
146471  );
146472  if( zSql ){
146473    rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
146474    sqlite3_free(zSql);
146475  }
146476  return rc;
146477}
146478
146479/*
146480** This function populates the pRtree->nRowEst variable with an estimate
146481** of the number of rows in the virtual table. If possible, this is based
146482** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
146483*/
146484static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
146485  const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
146486  char *zSql;
146487  sqlite3_stmt *p;
146488  int rc;
146489  i64 nRow = 0;
146490
146491  zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
146492  if( zSql==0 ){
146493    rc = SQLITE_NOMEM;
146494  }else{
146495    rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
146496    if( rc==SQLITE_OK ){
146497      if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
146498      rc = sqlite3_finalize(p);
146499    }else if( rc!=SQLITE_NOMEM ){
146500      rc = SQLITE_OK;
146501    }
146502
146503    if( rc==SQLITE_OK ){
146504      if( nRow==0 ){
146505        pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
146506      }else{
146507        pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
146508      }
146509    }
146510    sqlite3_free(zSql);
146511  }
146512
146513  return rc;
146514}
146515
146516static sqlite3_module rtreeModule = {
146517  0,                          /* iVersion */
146518  rtreeCreate,                /* xCreate - create a table */
146519  rtreeConnect,               /* xConnect - connect to an existing table */
146520  rtreeBestIndex,             /* xBestIndex - Determine search strategy */
146521  rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
146522  rtreeDestroy,               /* xDestroy - Drop a table */
146523  rtreeOpen,                  /* xOpen - open a cursor */
146524  rtreeClose,                 /* xClose - close a cursor */
146525  rtreeFilter,                /* xFilter - configure scan constraints */
146526  rtreeNext,                  /* xNext - advance a cursor */
146527  rtreeEof,                   /* xEof */
146528  rtreeColumn,                /* xColumn - read data */
146529  rtreeRowid,                 /* xRowid - read data */
146530  rtreeUpdate,                /* xUpdate - write data */
146531  0,                          /* xBegin - begin transaction */
146532  0,                          /* xSync - sync transaction */
146533  0,                          /* xCommit - commit transaction */
146534  0,                          /* xRollback - rollback transaction */
146535  0,                          /* xFindFunction - function overloading */
146536  rtreeRename,                /* xRename - rename the table */
146537  0,                          /* xSavepoint */
146538  0,                          /* xRelease */
146539  0                           /* xRollbackTo */
146540};
146541
146542static int rtreeSqlInit(
146543  Rtree *pRtree,
146544  sqlite3 *db,
146545  const char *zDb,
146546  const char *zPrefix,
146547  int isCreate
146548){
146549  int rc = SQLITE_OK;
146550
146551  #define N_STATEMENT 9
146552  static const char *azSql[N_STATEMENT] = {
146553    /* Read and write the xxx_node table */
146554    "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
146555    "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
146556    "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
146557
146558    /* Read and write the xxx_rowid table */
146559    "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
146560    "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
146561    "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
146562
146563    /* Read and write the xxx_parent table */
146564    "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
146565    "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
146566    "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
146567  };
146568  sqlite3_stmt **appStmt[N_STATEMENT];
146569  int i;
146570
146571  pRtree->db = db;
146572
146573  if( isCreate ){
146574    char *zCreate = sqlite3_mprintf(
146575"CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
146576"CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
146577"CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
146578                                  " parentnode INTEGER);"
146579"INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
146580      zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
146581    );
146582    if( !zCreate ){
146583      return SQLITE_NOMEM;
146584    }
146585    rc = sqlite3_exec(db, zCreate, 0, 0, 0);
146586    sqlite3_free(zCreate);
146587    if( rc!=SQLITE_OK ){
146588      return rc;
146589    }
146590  }
146591
146592  appStmt[0] = &pRtree->pReadNode;
146593  appStmt[1] = &pRtree->pWriteNode;
146594  appStmt[2] = &pRtree->pDeleteNode;
146595  appStmt[3] = &pRtree->pReadRowid;
146596  appStmt[4] = &pRtree->pWriteRowid;
146597  appStmt[5] = &pRtree->pDeleteRowid;
146598  appStmt[6] = &pRtree->pReadParent;
146599  appStmt[7] = &pRtree->pWriteParent;
146600  appStmt[8] = &pRtree->pDeleteParent;
146601
146602  rc = rtreeQueryStat1(db, pRtree);
146603  for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
146604    char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
146605    if( zSql ){
146606      rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
146607    }else{
146608      rc = SQLITE_NOMEM;
146609    }
146610    sqlite3_free(zSql);
146611  }
146612
146613  return rc;
146614}
146615
146616/*
146617** The second argument to this function contains the text of an SQL statement
146618** that returns a single integer value. The statement is compiled and executed
146619** using database connection db. If successful, the integer value returned
146620** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
146621** code is returned and the value of *piVal after returning is not defined.
146622*/
146623static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
146624  int rc = SQLITE_NOMEM;
146625  if( zSql ){
146626    sqlite3_stmt *pStmt = 0;
146627    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
146628    if( rc==SQLITE_OK ){
146629      if( SQLITE_ROW==sqlite3_step(pStmt) ){
146630        *piVal = sqlite3_column_int(pStmt, 0);
146631      }
146632      rc = sqlite3_finalize(pStmt);
146633    }
146634  }
146635  return rc;
146636}
146637
146638/*
146639** This function is called from within the xConnect() or xCreate() method to
146640** determine the node-size used by the rtree table being created or connected
146641** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
146642** Otherwise, an SQLite error code is returned.
146643**
146644** If this function is being called as part of an xConnect(), then the rtree
146645** table already exists. In this case the node-size is determined by inspecting
146646** the root node of the tree.
146647**
146648** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
146649** This ensures that each node is stored on a single database page. If the
146650** database page-size is so large that more than RTREE_MAXCELLS entries
146651** would fit in a single node, use a smaller node-size.
146652*/
146653static int getNodeSize(
146654  sqlite3 *db,                    /* Database handle */
146655  Rtree *pRtree,                  /* Rtree handle */
146656  int isCreate,                   /* True for xCreate, false for xConnect */
146657  char **pzErr                    /* OUT: Error message, if any */
146658){
146659  int rc;
146660  char *zSql;
146661  if( isCreate ){
146662    int iPageSize = 0;
146663    zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
146664    rc = getIntFromStmt(db, zSql, &iPageSize);
146665    if( rc==SQLITE_OK ){
146666      pRtree->iNodeSize = iPageSize-64;
146667      if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
146668        pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
146669      }
146670    }else{
146671      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
146672    }
146673  }else{
146674    zSql = sqlite3_mprintf(
146675        "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
146676        pRtree->zDb, pRtree->zName
146677    );
146678    rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
146679    if( rc!=SQLITE_OK ){
146680      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
146681    }
146682  }
146683
146684  sqlite3_free(zSql);
146685  return rc;
146686}
146687
146688/*
146689** This function is the implementation of both the xConnect and xCreate
146690** methods of the r-tree virtual table.
146691**
146692**   argv[0]   -> module name
146693**   argv[1]   -> database name
146694**   argv[2]   -> table name
146695**   argv[...] -> column names...
146696*/
146697static int rtreeInit(
146698  sqlite3 *db,                        /* Database connection */
146699  void *pAux,                         /* One of the RTREE_COORD_* constants */
146700  int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
146701  sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
146702  char **pzErr,                       /* OUT: Error message, if any */
146703  int isCreate                        /* True for xCreate, false for xConnect */
146704){
146705  int rc = SQLITE_OK;
146706  Rtree *pRtree;
146707  int nDb;              /* Length of string argv[1] */
146708  int nName;            /* Length of string argv[2] */
146709  int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
146710
146711  const char *aErrMsg[] = {
146712    0,                                                    /* 0 */
146713    "Wrong number of columns for an rtree table",         /* 1 */
146714    "Too few columns for an rtree table",                 /* 2 */
146715    "Too many columns for an rtree table"                 /* 3 */
146716  };
146717
146718  int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
146719  if( aErrMsg[iErr] ){
146720    *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
146721    return SQLITE_ERROR;
146722  }
146723
146724  sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
146725
146726  /* Allocate the sqlite3_vtab structure */
146727  nDb = (int)strlen(argv[1]);
146728  nName = (int)strlen(argv[2]);
146729  pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
146730  if( !pRtree ){
146731    return SQLITE_NOMEM;
146732  }
146733  memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
146734  pRtree->nBusy = 1;
146735  pRtree->base.pModule = &rtreeModule;
146736  pRtree->zDb = (char *)&pRtree[1];
146737  pRtree->zName = &pRtree->zDb[nDb+1];
146738  pRtree->nDim = (argc-4)/2;
146739  pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
146740  pRtree->eCoordType = eCoordType;
146741  memcpy(pRtree->zDb, argv[1], nDb);
146742  memcpy(pRtree->zName, argv[2], nName);
146743
146744  /* Figure out the node size to use. */
146745  rc = getNodeSize(db, pRtree, isCreate, pzErr);
146746
146747  /* Create/Connect to the underlying relational database schema. If
146748  ** that is successful, call sqlite3_declare_vtab() to configure
146749  ** the r-tree table schema.
146750  */
146751  if( rc==SQLITE_OK ){
146752    if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
146753      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
146754    }else{
146755      char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
146756      char *zTmp;
146757      int ii;
146758      for(ii=4; zSql && ii<argc; ii++){
146759        zTmp = zSql;
146760        zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
146761        sqlite3_free(zTmp);
146762      }
146763      if( zSql ){
146764        zTmp = zSql;
146765        zSql = sqlite3_mprintf("%s);", zTmp);
146766        sqlite3_free(zTmp);
146767      }
146768      if( !zSql ){
146769        rc = SQLITE_NOMEM;
146770      }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
146771        *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
146772      }
146773      sqlite3_free(zSql);
146774    }
146775  }
146776
146777  if( rc==SQLITE_OK ){
146778    *ppVtab = (sqlite3_vtab *)pRtree;
146779  }else{
146780    assert( *ppVtab==0 );
146781    assert( pRtree->nBusy==1 );
146782    rtreeRelease(pRtree);
146783  }
146784  return rc;
146785}
146786
146787
146788/*
146789** Implementation of a scalar function that decodes r-tree nodes to
146790** human readable strings. This can be used for debugging and analysis.
146791**
146792** The scalar function takes two arguments: (1) the number of dimensions
146793** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
146794** an r-tree node.  For a two-dimensional r-tree structure called "rt", to
146795** deserialize all nodes, a statement like:
146796**
146797**   SELECT rtreenode(2, data) FROM rt_node;
146798**
146799** The human readable string takes the form of a Tcl list with one
146800** entry for each cell in the r-tree node. Each entry is itself a
146801** list, containing the 8-byte rowid/pageno followed by the
146802** <num-dimension>*2 coordinates.
146803*/
146804static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
146805  char *zText = 0;
146806  RtreeNode node;
146807  Rtree tree;
146808  int ii;
146809
146810  UNUSED_PARAMETER(nArg);
146811  memset(&node, 0, sizeof(RtreeNode));
146812  memset(&tree, 0, sizeof(Rtree));
146813  tree.nDim = sqlite3_value_int(apArg[0]);
146814  tree.nBytesPerCell = 8 + 8 * tree.nDim;
146815  node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
146816
146817  for(ii=0; ii<NCELL(&node); ii++){
146818    char zCell[512];
146819    int nCell = 0;
146820    RtreeCell cell;
146821    int jj;
146822
146823    nodeGetCell(&tree, &node, ii, &cell);
146824    sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
146825    nCell = (int)strlen(zCell);
146826    for(jj=0; jj<tree.nDim*2; jj++){
146827#ifndef SQLITE_RTREE_INT_ONLY
146828      sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
146829                       (double)cell.aCoord[jj].f);
146830#else
146831      sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
146832                       cell.aCoord[jj].i);
146833#endif
146834      nCell = (int)strlen(zCell);
146835    }
146836
146837    if( zText ){
146838      char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
146839      sqlite3_free(zText);
146840      zText = zTextNew;
146841    }else{
146842      zText = sqlite3_mprintf("{%s}", zCell);
146843    }
146844  }
146845
146846  sqlite3_result_text(ctx, zText, -1, sqlite3_free);
146847}
146848
146849/* This routine implements an SQL function that returns the "depth" parameter
146850** from the front of a blob that is an r-tree node.  For example:
146851**
146852**     SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
146853**
146854** The depth value is 0 for all nodes other than the root node, and the root
146855** node always has nodeno=1, so the example above is the primary use for this
146856** routine.  This routine is intended for testing and analysis only.
146857*/
146858static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
146859  UNUSED_PARAMETER(nArg);
146860  if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
146861   || sqlite3_value_bytes(apArg[0])<2
146862  ){
146863    sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
146864  }else{
146865    u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
146866    sqlite3_result_int(ctx, readInt16(zBlob));
146867  }
146868}
146869
146870/*
146871** Register the r-tree module with database handle db. This creates the
146872** virtual table module "rtree" and the debugging/analysis scalar
146873** function "rtreenode".
146874*/
146875SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
146876  const int utf8 = SQLITE_UTF8;
146877  int rc;
146878
146879  rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
146880  if( rc==SQLITE_OK ){
146881    rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
146882  }
146883  if( rc==SQLITE_OK ){
146884#ifdef SQLITE_RTREE_INT_ONLY
146885    void *c = (void *)RTREE_COORD_INT32;
146886#else
146887    void *c = (void *)RTREE_COORD_REAL32;
146888#endif
146889    rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
146890  }
146891  if( rc==SQLITE_OK ){
146892    void *c = (void *)RTREE_COORD_INT32;
146893    rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
146894  }
146895
146896  return rc;
146897}
146898
146899/*
146900** This routine deletes the RtreeGeomCallback object that was attached
146901** one of the SQL functions create by sqlite3_rtree_geometry_callback()
146902** or sqlite3_rtree_query_callback().  In other words, this routine is the
146903** destructor for an RtreeGeomCallback objecct.  This routine is called when
146904** the corresponding SQL function is deleted.
146905*/
146906static void rtreeFreeCallback(void *p){
146907  RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
146908  if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
146909  sqlite3_free(p);
146910}
146911
146912/*
146913** Each call to sqlite3_rtree_geometry_callback() or
146914** sqlite3_rtree_query_callback() creates an ordinary SQLite
146915** scalar function that is implemented by this routine.
146916**
146917** All this function does is construct an RtreeMatchArg object that
146918** contains the geometry-checking callback routines and a list of
146919** parameters to this function, then return that RtreeMatchArg object
146920** as a BLOB.
146921**
146922** The R-Tree MATCH operator will read the returned BLOB, deserialize
146923** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
146924** out which elements of the R-Tree should be returned by the query.
146925*/
146926static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
146927  RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
146928  RtreeMatchArg *pBlob;
146929  int nBlob;
146930
146931  nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue);
146932  pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
146933  if( !pBlob ){
146934    sqlite3_result_error_nomem(ctx);
146935  }else{
146936    int i;
146937    pBlob->magic = RTREE_GEOMETRY_MAGIC;
146938    pBlob->cb = pGeomCtx[0];
146939    pBlob->nParam = nArg;
146940    for(i=0; i<nArg; i++){
146941#ifdef SQLITE_RTREE_INT_ONLY
146942      pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
146943#else
146944      pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
146945#endif
146946    }
146947    sqlite3_result_blob(ctx, pBlob, nBlob, sqlite3_free);
146948  }
146949}
146950
146951/*
146952** Register a new geometry function for use with the r-tree MATCH operator.
146953*/
146954SQLITE_API int sqlite3_rtree_geometry_callback(
146955  sqlite3 *db,                  /* Register SQL function on this connection */
146956  const char *zGeom,            /* Name of the new SQL function */
146957  int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
146958  void *pContext                /* Extra data associated with the callback */
146959){
146960  RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
146961
146962  /* Allocate and populate the context object. */
146963  pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
146964  if( !pGeomCtx ) return SQLITE_NOMEM;
146965  pGeomCtx->xGeom = xGeom;
146966  pGeomCtx->xQueryFunc = 0;
146967  pGeomCtx->xDestructor = 0;
146968  pGeomCtx->pContext = pContext;
146969  return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
146970      (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
146971  );
146972}
146973
146974/*
146975** Register a new 2nd-generation geometry function for use with the
146976** r-tree MATCH operator.
146977*/
146978SQLITE_API int sqlite3_rtree_query_callback(
146979  sqlite3 *db,                 /* Register SQL function on this connection */
146980  const char *zQueryFunc,      /* Name of new SQL function */
146981  int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
146982  void *pContext,              /* Extra data passed into the callback */
146983  void (*xDestructor)(void*)   /* Destructor for the extra data */
146984){
146985  RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
146986
146987  /* Allocate and populate the context object. */
146988  pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
146989  if( !pGeomCtx ) return SQLITE_NOMEM;
146990  pGeomCtx->xGeom = 0;
146991  pGeomCtx->xQueryFunc = xQueryFunc;
146992  pGeomCtx->xDestructor = xDestructor;
146993  pGeomCtx->pContext = pContext;
146994  return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
146995      (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
146996  );
146997}
146998
146999#if !SQLITE_CORE
147000#ifdef _WIN32
147001__declspec(dllexport)
147002#endif
147003SQLITE_API int sqlite3_rtree_init(
147004  sqlite3 *db,
147005  char **pzErrMsg,
147006  const sqlite3_api_routines *pApi
147007){
147008  SQLITE_EXTENSION_INIT2(pApi)
147009  return sqlite3RtreeInit(db);
147010}
147011#endif
147012
147013#endif
147014
147015/************** End of rtree.c ***********************************************/
147016/************** Begin file icu.c *********************************************/
147017/*
147018** 2007 May 6
147019**
147020** The author disclaims copyright to this source code.  In place of
147021** a legal notice, here is a blessing:
147022**
147023**    May you do good and not evil.
147024**    May you find forgiveness for yourself and forgive others.
147025**    May you share freely, never taking more than you give.
147026**
147027*************************************************************************
147028** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
147029**
147030** This file implements an integration between the ICU library
147031** ("International Components for Unicode", an open-source library
147032** for handling unicode data) and SQLite. The integration uses
147033** ICU to provide the following to SQLite:
147034**
147035**   * An implementation of the SQL regexp() function (and hence REGEXP
147036**     operator) using the ICU uregex_XX() APIs.
147037**
147038**   * Implementations of the SQL scalar upper() and lower() functions
147039**     for case mapping.
147040**
147041**   * Integration of ICU and SQLite collation sequences.
147042**
147043**   * An implementation of the LIKE operator that uses ICU to
147044**     provide case-independent matching.
147045*/
147046
147047#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
147048
147049/* Include ICU headers */
147050#include <unicode/utypes.h>
147051#include <unicode/uregex.h>
147052#include <unicode/ustring.h>
147053#include <unicode/ucol.h>
147054
147055/* #include <assert.h> */
147056
147057#ifndef SQLITE_CORE
147058  SQLITE_EXTENSION_INIT1
147059#else
147060#endif
147061
147062/*
147063** Maximum length (in bytes) of the pattern in a LIKE or GLOB
147064** operator.
147065*/
147066#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
147067# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
147068#endif
147069
147070/*
147071** Version of sqlite3_free() that is always a function, never a macro.
147072*/
147073static void xFree(void *p){
147074  sqlite3_free(p);
147075}
147076
147077/*
147078** Compare two UTF-8 strings for equality where the first string is
147079** a "LIKE" expression. Return true (1) if they are the same and
147080** false (0) if they are different.
147081*/
147082static int icuLikeCompare(
147083  const uint8_t *zPattern,   /* LIKE pattern */
147084  const uint8_t *zString,    /* The UTF-8 string to compare against */
147085  const UChar32 uEsc         /* The escape character */
147086){
147087  static const int MATCH_ONE = (UChar32)'_';
147088  static const int MATCH_ALL = (UChar32)'%';
147089
147090  int iPattern = 0;       /* Current byte index in zPattern */
147091  int iString = 0;        /* Current byte index in zString */
147092
147093  int prevEscape = 0;     /* True if the previous character was uEsc */
147094
147095  while( zPattern[iPattern]!=0 ){
147096
147097    /* Read (and consume) the next character from the input pattern. */
147098    UChar32 uPattern;
147099    U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
147100    assert(uPattern!=0);
147101
147102    /* There are now 4 possibilities:
147103    **
147104    **     1. uPattern is an unescaped match-all character "%",
147105    **     2. uPattern is an unescaped match-one character "_",
147106    **     3. uPattern is an unescaped escape character, or
147107    **     4. uPattern is to be handled as an ordinary character
147108    */
147109    if( !prevEscape && uPattern==MATCH_ALL ){
147110      /* Case 1. */
147111      uint8_t c;
147112
147113      /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
147114      ** MATCH_ALL. For each MATCH_ONE, skip one character in the
147115      ** test string.
147116      */
147117      while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
147118        if( c==MATCH_ONE ){
147119          if( zString[iString]==0 ) return 0;
147120          U8_FWD_1_UNSAFE(zString, iString);
147121        }
147122        iPattern++;
147123      }
147124
147125      if( zPattern[iPattern]==0 ) return 1;
147126
147127      while( zString[iString] ){
147128        if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
147129          return 1;
147130        }
147131        U8_FWD_1_UNSAFE(zString, iString);
147132      }
147133      return 0;
147134
147135    }else if( !prevEscape && uPattern==MATCH_ONE ){
147136      /* Case 2. */
147137      if( zString[iString]==0 ) return 0;
147138      U8_FWD_1_UNSAFE(zString, iString);
147139
147140    }else if( !prevEscape && uPattern==uEsc){
147141      /* Case 3. */
147142      prevEscape = 1;
147143
147144    }else{
147145      /* Case 4. */
147146      UChar32 uString;
147147      U8_NEXT_UNSAFE(zString, iString, uString);
147148      uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
147149      uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
147150      if( uString!=uPattern ){
147151        return 0;
147152      }
147153      prevEscape = 0;
147154    }
147155  }
147156
147157  return zString[iString]==0;
147158}
147159
147160/*
147161** Implementation of the like() SQL function.  This function implements
147162** the build-in LIKE operator.  The first argument to the function is the
147163** pattern and the second argument is the string.  So, the SQL statements:
147164**
147165**       A LIKE B
147166**
147167** is implemented as like(B, A). If there is an escape character E,
147168**
147169**       A LIKE B ESCAPE E
147170**
147171** is mapped to like(B, A, E).
147172*/
147173static void icuLikeFunc(
147174  sqlite3_context *context,
147175  int argc,
147176  sqlite3_value **argv
147177){
147178  const unsigned char *zA = sqlite3_value_text(argv[0]);
147179  const unsigned char *zB = sqlite3_value_text(argv[1]);
147180  UChar32 uEsc = 0;
147181
147182  /* Limit the length of the LIKE or GLOB pattern to avoid problems
147183  ** of deep recursion and N*N behavior in patternCompare().
147184  */
147185  if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
147186    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
147187    return;
147188  }
147189
147190
147191  if( argc==3 ){
147192    /* The escape character string must consist of a single UTF-8 character.
147193    ** Otherwise, return an error.
147194    */
147195    int nE= sqlite3_value_bytes(argv[2]);
147196    const unsigned char *zE = sqlite3_value_text(argv[2]);
147197    int i = 0;
147198    if( zE==0 ) return;
147199    U8_NEXT(zE, i, nE, uEsc);
147200    if( i!=nE){
147201      sqlite3_result_error(context,
147202          "ESCAPE expression must be a single character", -1);
147203      return;
147204    }
147205  }
147206
147207  if( zA && zB ){
147208    sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
147209  }
147210}
147211
147212/*
147213** This function is called when an ICU function called from within
147214** the implementation of an SQL scalar function returns an error.
147215**
147216** The scalar function context passed as the first argument is
147217** loaded with an error message based on the following two args.
147218*/
147219static void icuFunctionError(
147220  sqlite3_context *pCtx,       /* SQLite scalar function context */
147221  const char *zName,           /* Name of ICU function that failed */
147222  UErrorCode e                 /* Error code returned by ICU function */
147223){
147224  char zBuf[128];
147225  sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
147226  zBuf[127] = '\0';
147227  sqlite3_result_error(pCtx, zBuf, -1);
147228}
147229
147230/*
147231** Function to delete compiled regexp objects. Registered as
147232** a destructor function with sqlite3_set_auxdata().
147233*/
147234static void icuRegexpDelete(void *p){
147235  URegularExpression *pExpr = (URegularExpression *)p;
147236  uregex_close(pExpr);
147237}
147238
147239/*
147240** Implementation of SQLite REGEXP operator. This scalar function takes
147241** two arguments. The first is a regular expression pattern to compile
147242** the second is a string to match against that pattern. If either
147243** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
147244** is 1 if the string matches the pattern, or 0 otherwise.
147245**
147246** SQLite maps the regexp() function to the regexp() operator such
147247** that the following two are equivalent:
147248**
147249**     zString REGEXP zPattern
147250**     regexp(zPattern, zString)
147251**
147252** Uses the following ICU regexp APIs:
147253**
147254**     uregex_open()
147255**     uregex_matches()
147256**     uregex_close()
147257*/
147258static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
147259  UErrorCode status = U_ZERO_ERROR;
147260  URegularExpression *pExpr;
147261  UBool res;
147262  const UChar *zString = sqlite3_value_text16(apArg[1]);
147263
147264  (void)nArg;  /* Unused parameter */
147265
147266  /* If the left hand side of the regexp operator is NULL,
147267  ** then the result is also NULL.
147268  */
147269  if( !zString ){
147270    return;
147271  }
147272
147273  pExpr = sqlite3_get_auxdata(p, 0);
147274  if( !pExpr ){
147275    const UChar *zPattern = sqlite3_value_text16(apArg[0]);
147276    if( !zPattern ){
147277      return;
147278    }
147279    pExpr = uregex_open(zPattern, -1, 0, 0, &status);
147280
147281    if( U_SUCCESS(status) ){
147282      sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
147283    }else{
147284      assert(!pExpr);
147285      icuFunctionError(p, "uregex_open", status);
147286      return;
147287    }
147288  }
147289
147290  /* Configure the text that the regular expression operates on. */
147291  uregex_setText(pExpr, zString, -1, &status);
147292  if( !U_SUCCESS(status) ){
147293    icuFunctionError(p, "uregex_setText", status);
147294    return;
147295  }
147296
147297  /* Attempt the match */
147298  res = uregex_matches(pExpr, 0, &status);
147299  if( !U_SUCCESS(status) ){
147300    icuFunctionError(p, "uregex_matches", status);
147301    return;
147302  }
147303
147304  /* Set the text that the regular expression operates on to a NULL
147305  ** pointer. This is not really necessary, but it is tidier than
147306  ** leaving the regular expression object configured with an invalid
147307  ** pointer after this function returns.
147308  */
147309  uregex_setText(pExpr, 0, 0, &status);
147310
147311  /* Return 1 or 0. */
147312  sqlite3_result_int(p, res ? 1 : 0);
147313}
147314
147315/*
147316** Implementations of scalar functions for case mapping - upper() and
147317** lower(). Function upper() converts its input to upper-case (ABC).
147318** Function lower() converts to lower-case (abc).
147319**
147320** ICU provides two types of case mapping, "general" case mapping and
147321** "language specific". Refer to ICU documentation for the differences
147322** between the two.
147323**
147324** To utilise "general" case mapping, the upper() or lower() scalar
147325** functions are invoked with one argument:
147326**
147327**     upper('ABC') -> 'abc'
147328**     lower('abc') -> 'ABC'
147329**
147330** To access ICU "language specific" case mapping, upper() or lower()
147331** should be invoked with two arguments. The second argument is the name
147332** of the locale to use. Passing an empty string ("") or SQL NULL value
147333** as the second argument is the same as invoking the 1 argument version
147334** of upper() or lower().
147335**
147336**     lower('I', 'en_us') -> 'i'
147337**     lower('I', 'tr_tr') -> '��' (small dotless i)
147338**
147339** http://www.icu-project.org/userguide/posix.html#case_mappings
147340*/
147341static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
147342  const UChar *zInput;
147343  UChar *zOutput;
147344  int nInput;
147345  int nOutput;
147346
147347  UErrorCode status = U_ZERO_ERROR;
147348  const char *zLocale = 0;
147349
147350  assert(nArg==1 || nArg==2);
147351  if( nArg==2 ){
147352    zLocale = (const char *)sqlite3_value_text(apArg[1]);
147353  }
147354
147355  zInput = sqlite3_value_text16(apArg[0]);
147356  if( !zInput ){
147357    return;
147358  }
147359  nInput = sqlite3_value_bytes16(apArg[0]);
147360
147361  nOutput = nInput * 2 + 2;
147362  zOutput = sqlite3_malloc(nOutput);
147363  if( !zOutput ){
147364    return;
147365  }
147366
147367  if( sqlite3_user_data(p) ){
147368    u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
147369  }else{
147370    u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
147371  }
147372
147373  if( !U_SUCCESS(status) ){
147374    icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
147375    return;
147376  }
147377
147378  sqlite3_result_text16(p, zOutput, -1, xFree);
147379}
147380
147381/*
147382** Collation sequence destructor function. The pCtx argument points to
147383** a UCollator structure previously allocated using ucol_open().
147384*/
147385static void icuCollationDel(void *pCtx){
147386  UCollator *p = (UCollator *)pCtx;
147387  ucol_close(p);
147388}
147389
147390/*
147391** Collation sequence comparison function. The pCtx argument points to
147392** a UCollator structure previously allocated using ucol_open().
147393*/
147394static int icuCollationColl(
147395  void *pCtx,
147396  int nLeft,
147397  const void *zLeft,
147398  int nRight,
147399  const void *zRight
147400){
147401  UCollationResult res;
147402  UCollator *p = (UCollator *)pCtx;
147403  res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
147404  switch( res ){
147405    case UCOL_LESS:    return -1;
147406    case UCOL_GREATER: return +1;
147407    case UCOL_EQUAL:   return 0;
147408  }
147409  assert(!"Unexpected return value from ucol_strcoll()");
147410  return 0;
147411}
147412
147413/*
147414** Implementation of the scalar function icu_load_collation().
147415**
147416** This scalar function is used to add ICU collation based collation
147417** types to an SQLite database connection. It is intended to be called
147418** as follows:
147419**
147420**     SELECT icu_load_collation(<locale>, <collation-name>);
147421**
147422** Where <locale> is a string containing an ICU locale identifier (i.e.
147423** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
147424** collation sequence to create.
147425*/
147426static void icuLoadCollation(
147427  sqlite3_context *p,
147428  int nArg,
147429  sqlite3_value **apArg
147430){
147431  sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
147432  UErrorCode status = U_ZERO_ERROR;
147433  const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
147434  const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
147435  UCollator *pUCollator;    /* ICU library collation object */
147436  int rc;                   /* Return code from sqlite3_create_collation_x() */
147437
147438  assert(nArg==2);
147439  zLocale = (const char *)sqlite3_value_text(apArg[0]);
147440  zName = (const char *)sqlite3_value_text(apArg[1]);
147441
147442  if( !zLocale || !zName ){
147443    return;
147444  }
147445
147446  pUCollator = ucol_open(zLocale, &status);
147447  if( !U_SUCCESS(status) ){
147448    icuFunctionError(p, "ucol_open", status);
147449    return;
147450  }
147451  assert(p);
147452
147453  rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
147454      icuCollationColl, icuCollationDel
147455  );
147456  if( rc!=SQLITE_OK ){
147457    ucol_close(pUCollator);
147458    sqlite3_result_error(p, "Error registering collation function", -1);
147459  }
147460}
147461
147462/*
147463** Register the ICU extension functions with database db.
147464*/
147465SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
147466  struct IcuScalar {
147467    const char *zName;                        /* Function name */
147468    int nArg;                                 /* Number of arguments */
147469    int enc;                                  /* Optimal text encoding */
147470    void *pContext;                           /* sqlite3_user_data() context */
147471    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
147472  } scalars[] = {
147473    {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
147474
147475    {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
147476    {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
147477    {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
147478    {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
147479
147480    {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
147481    {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
147482    {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
147483    {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
147484
147485    {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
147486    {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
147487
147488    {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
147489  };
147490
147491  int rc = SQLITE_OK;
147492  int i;
147493
147494  for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
147495    struct IcuScalar *p = &scalars[i];
147496    rc = sqlite3_create_function(
147497        db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
147498    );
147499  }
147500
147501  return rc;
147502}
147503
147504#if !SQLITE_CORE
147505#ifdef _WIN32
147506__declspec(dllexport)
147507#endif
147508SQLITE_API int sqlite3_icu_init(
147509  sqlite3 *db,
147510  char **pzErrMsg,
147511  const sqlite3_api_routines *pApi
147512){
147513  SQLITE_EXTENSION_INIT2(pApi)
147514  return sqlite3IcuInit(db);
147515}
147516#endif
147517
147518#endif
147519
147520/************** End of icu.c *************************************************/
147521/************** Begin file fts3_icu.c ****************************************/
147522/*
147523** 2007 June 22
147524**
147525** The author disclaims copyright to this source code.  In place of
147526** a legal notice, here is a blessing:
147527**
147528**    May you do good and not evil.
147529**    May you find forgiveness for yourself and forgive others.
147530**    May you share freely, never taking more than you give.
147531**
147532*************************************************************************
147533** This file implements a tokenizer for fts3 based on the ICU library.
147534*/
147535#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
147536#ifdef SQLITE_ENABLE_ICU
147537
147538/* #include <assert.h> */
147539/* #include <string.h> */
147540
147541#include <unicode/ubrk.h>
147542/* #include <unicode/ucol.h> */
147543/* #include <unicode/ustring.h> */
147544#include <unicode/utf16.h>
147545
147546typedef struct IcuTokenizer IcuTokenizer;
147547typedef struct IcuCursor IcuCursor;
147548
147549struct IcuTokenizer {
147550  sqlite3_tokenizer base;
147551  char *zLocale;
147552};
147553
147554struct IcuCursor {
147555  sqlite3_tokenizer_cursor base;
147556
147557  UBreakIterator *pIter;      /* ICU break-iterator object */
147558  int nChar;                  /* Number of UChar elements in pInput */
147559  UChar *aChar;               /* Copy of input using utf-16 encoding */
147560  int *aOffset;               /* Offsets of each character in utf-8 input */
147561
147562  int nBuffer;
147563  char *zBuffer;
147564
147565  int iToken;
147566};
147567
147568/*
147569** Create a new tokenizer instance.
147570*/
147571static int icuCreate(
147572  int argc,                            /* Number of entries in argv[] */
147573  const char * const *argv,            /* Tokenizer creation arguments */
147574  sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
147575){
147576  IcuTokenizer *p;
147577  int n = 0;
147578
147579  if( argc>0 ){
147580    n = strlen(argv[0])+1;
147581  }
147582  p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
147583  if( !p ){
147584    return SQLITE_NOMEM;
147585  }
147586  memset(p, 0, sizeof(IcuTokenizer));
147587
147588  if( n ){
147589    p->zLocale = (char *)&p[1];
147590    memcpy(p->zLocale, argv[0], n);
147591  }
147592
147593  *ppTokenizer = (sqlite3_tokenizer *)p;
147594
147595  return SQLITE_OK;
147596}
147597
147598/*
147599** Destroy a tokenizer
147600*/
147601static int icuDestroy(sqlite3_tokenizer *pTokenizer){
147602  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
147603  sqlite3_free(p);
147604  return SQLITE_OK;
147605}
147606
147607/*
147608** Prepare to begin tokenizing a particular string.  The input
147609** string to be tokenized is pInput[0..nBytes-1].  A cursor
147610** used to incrementally tokenize this string is returned in
147611** *ppCursor.
147612*/
147613static int icuOpen(
147614  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
147615  const char *zInput,                    /* Input string */
147616  int nInput,                            /* Length of zInput in bytes */
147617  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
147618){
147619  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
147620  IcuCursor *pCsr;
147621
147622  const int32_t opt = U_FOLD_CASE_DEFAULT;
147623  UErrorCode status = U_ZERO_ERROR;
147624  int nChar;
147625
147626  UChar32 c;
147627  int iInput = 0;
147628  int iOut = 0;
147629
147630  *ppCursor = 0;
147631
147632  if( zInput==0 ){
147633    nInput = 0;
147634    zInput = "";
147635  }else if( nInput<0 ){
147636    nInput = strlen(zInput);
147637  }
147638  nChar = nInput+1;
147639  pCsr = (IcuCursor *)sqlite3_malloc(
147640      sizeof(IcuCursor) +                /* IcuCursor */
147641      ((nChar+3)&~3) * sizeof(UChar) +   /* IcuCursor.aChar[] */
147642      (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
147643  );
147644  if( !pCsr ){
147645    return SQLITE_NOMEM;
147646  }
147647  memset(pCsr, 0, sizeof(IcuCursor));
147648  pCsr->aChar = (UChar *)&pCsr[1];
147649  pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
147650
147651  pCsr->aOffset[iOut] = iInput;
147652  U8_NEXT(zInput, iInput, nInput, c);
147653  while( c>0 ){
147654    int isError = 0;
147655    c = u_foldCase(c, opt);
147656    U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
147657    if( isError ){
147658      sqlite3_free(pCsr);
147659      return SQLITE_ERROR;
147660    }
147661    pCsr->aOffset[iOut] = iInput;
147662
147663    if( iInput<nInput ){
147664      U8_NEXT(zInput, iInput, nInput, c);
147665    }else{
147666      c = 0;
147667    }
147668  }
147669
147670  pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
147671  if( !U_SUCCESS(status) ){
147672    sqlite3_free(pCsr);
147673    return SQLITE_ERROR;
147674  }
147675  pCsr->nChar = iOut;
147676
147677  ubrk_first(pCsr->pIter);
147678  *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
147679  return SQLITE_OK;
147680}
147681
147682/*
147683** Close a tokenization cursor previously opened by a call to icuOpen().
147684*/
147685static int icuClose(sqlite3_tokenizer_cursor *pCursor){
147686  IcuCursor *pCsr = (IcuCursor *)pCursor;
147687  ubrk_close(pCsr->pIter);
147688  sqlite3_free(pCsr->zBuffer);
147689  sqlite3_free(pCsr);
147690  return SQLITE_OK;
147691}
147692
147693/*
147694** Extract the next token from a tokenization cursor.
147695*/
147696static int icuNext(
147697  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
147698  const char **ppToken,               /* OUT: *ppToken is the token text */
147699  int *pnBytes,                       /* OUT: Number of bytes in token */
147700  int *piStartOffset,                 /* OUT: Starting offset of token */
147701  int *piEndOffset,                   /* OUT: Ending offset of token */
147702  int *piPosition                     /* OUT: Position integer of token */
147703){
147704  IcuCursor *pCsr = (IcuCursor *)pCursor;
147705
147706  int iStart = 0;
147707  int iEnd = 0;
147708  int nByte = 0;
147709
147710  while( iStart==iEnd ){
147711    UChar32 c;
147712
147713    iStart = ubrk_current(pCsr->pIter);
147714    iEnd = ubrk_next(pCsr->pIter);
147715    if( iEnd==UBRK_DONE ){
147716      return SQLITE_DONE;
147717    }
147718
147719    while( iStart<iEnd ){
147720      int iWhite = iStart;
147721      U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
147722      if( u_isspace(c) ){
147723        iStart = iWhite;
147724      }else{
147725        break;
147726      }
147727    }
147728    assert(iStart<=iEnd);
147729  }
147730
147731  do {
147732    UErrorCode status = U_ZERO_ERROR;
147733    if( nByte ){
147734      char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
147735      if( !zNew ){
147736        return SQLITE_NOMEM;
147737      }
147738      pCsr->zBuffer = zNew;
147739      pCsr->nBuffer = nByte;
147740    }
147741
147742    u_strToUTF8(
147743        pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
147744        &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
147745        &status                                  /* Output success/failure */
147746    );
147747  } while( nByte>pCsr->nBuffer );
147748
147749  *ppToken = pCsr->zBuffer;
147750  *pnBytes = nByte;
147751  *piStartOffset = pCsr->aOffset[iStart];
147752  *piEndOffset = pCsr->aOffset[iEnd];
147753  *piPosition = pCsr->iToken++;
147754
147755  return SQLITE_OK;
147756}
147757
147758/*
147759** The set of routines that implement the simple tokenizer
147760*/
147761static const sqlite3_tokenizer_module icuTokenizerModule = {
147762  0,                           /* iVersion */
147763  icuCreate,                   /* xCreate  */
147764  icuDestroy,                  /* xCreate  */
147765  icuOpen,                     /* xOpen    */
147766  icuClose,                    /* xClose   */
147767  icuNext,                     /* xNext    */
147768};
147769
147770/*
147771** Set *ppModule to point at the implementation of the ICU tokenizer.
147772*/
147773SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
147774  sqlite3_tokenizer_module const**ppModule
147775){
147776  *ppModule = &icuTokenizerModule;
147777}
147778
147779#endif /* defined(SQLITE_ENABLE_ICU) */
147780#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
147781
147782/************** End of fts3_icu.c ********************************************/
147783